-
Notifications
You must be signed in to change notification settings - Fork 62
/
controller.go
401 lines (345 loc) · 12.4 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
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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
package localbuild
import (
"context"
"fmt"
"time"
argov1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
"github.com/cnoe-io/idpbuilder/api/v1alpha1"
"github.com/cnoe-io/idpbuilder/globals"
"github.com/cnoe-io/idpbuilder/pkg/apps"
"github.com/cnoe-io/idpbuilder/pkg/resources/localbuild"
"github.com/cnoe-io/idpbuilder/pkg/util"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/log"
)
const (
defaultArgoCDProjectName string = "default"
EmbeddedGitServerName string = "embedded"
gitServerIngressHostnameBase string = ".cnoe.localtest.me"
repoUrlFmt string = "http://%s.%s.svc/idpbuilder-resources.git"
)
func getRepoUrl(resource *v1alpha1.GitServer) string {
return fmt.Sprintf(repoUrlFmt, managedResourceName(resource), resource.Namespace)
}
var gitServerLabelKey string = fmt.Sprintf("%s-gitserver", globals.ProjectName)
func ingressHostname(resource *v1alpha1.GitServer) string {
return fmt.Sprintf("%s%s", resource.Name, gitServerIngressHostnameBase)
}
func managedResourceName(resource *v1alpha1.GitServer) string {
return fmt.Sprintf("%s-%s", globals.GitServerResourcename(), resource.Name)
}
type LocalbuildReconciler struct {
client.Client
Scheme *runtime.Scheme
CancelFunc context.CancelFunc
shouldShutdown bool
}
type subReconciler func(ctx context.Context, req ctrl.Request, resource *v1alpha1.Localbuild) (ctrl.Result, error)
func (r *LocalbuildReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
log := log.FromContext(ctx)
log.Info("Reconciling", "resource", req.NamespacedName)
var localBuild v1alpha1.Localbuild
if err := r.Get(ctx, req.NamespacedName, &localBuild); err != nil {
log.Error(err, "unable to fetch Resource")
// we'll ignore not-found errors, since they can't be fixed by an immediate
// requeue (we'll need to wait for a new notification), and we can get them
// on deleted requests.
return ctrl.Result{}, client.IgnoreNotFound(err)
}
// Make sure we post process
defer r.postProcessReconcile(ctx, req, &localBuild)
// respecting order of installation matters as there are hard dependencies
subReconcilers := []subReconciler{
r.ReconcileProjectNamespace,
r.ReconcileNginx,
r.ReconcileArgo,
}
switch localBuild.Spec.PackageConfigs.GitConfig.Type {
case globals.GitServerResourcename():
subReconcilers = append(
subReconcilers,
[]subReconciler{r.ReconcileEmbeddedGitServer, r.ReconcileArgoAppsWithGitServer}...,
)
case globals.GiteaResourceName():
subReconcilers = append(
subReconcilers,
[]subReconciler{r.ReconcileGitea, r.ReconcileArgoAppsWithGitea}...,
)
default:
return ctrl.Result{}, fmt.Errorf("GitConfig %s is invalid for LocalBuild %s", localBuild.Spec.PackageConfigs.GitConfig.Type, localBuild.GetName())
}
for _, sub := range subReconcilers {
result, err := sub(ctx, req, &localBuild)
if err != nil || result.Requeue || result.RequeueAfter != 0 {
return result, err
}
}
return ctrl.Result{}, nil
}
// Responsible to updating ObservedGeneration in status
func (r *LocalbuildReconciler) postProcessReconcile(ctx context.Context, req ctrl.Request, resource *v1alpha1.Localbuild) {
log := log.FromContext(ctx)
resource.Status.ObservedGeneration = resource.GetGeneration()
if err := r.Status().Update(ctx, resource); err != nil {
log.Error(err, "Failed to update resource status after reconcile")
}
log.Info("Checking if we should shutdown")
if r.shouldShutdown {
log.Info("Shutting Down")
r.CancelFunc()
}
}
func (r *LocalbuildReconciler) ReconcileProjectNamespace(ctx context.Context, req ctrl.Request, resource *v1alpha1.Localbuild) (ctrl.Result, error) {
log := log.FromContext(ctx)
nsResource := &corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: globals.GetProjectNamespace(resource.Name),
},
}
log.Info("Create or update namespace", "resource", nsResource)
_, err := controllerutil.CreateOrUpdate(ctx, r.Client, nsResource, func() error {
if err := controllerutil.SetControllerReference(resource, nsResource, r.Scheme); err != nil {
log.Error(err, "Setting controller ref on namespace resource")
return err
}
return nil
})
if err != nil {
log.Error(err, "Create or update namespace resource")
}
return ctrl.Result{}, err
}
func (r *LocalbuildReconciler) ReconcileEmbeddedGitServer(ctx context.Context, req ctrl.Request, resource *v1alpha1.Localbuild) (ctrl.Result, error) {
log := log.FromContext(ctx)
// Bail if argo is not yet available
if !resource.Status.ArgoCD.Available {
log.Info("argo not yet available, not installing embedded git server")
return ctrl.Result{}, nil
}
// Bail if embedded argo applications not enabled
if !resource.Spec.PackageConfigs.EmbeddedArgoApplications.Enabled {
log.Info("embedded argo applications disabled, not installing embedded git server")
return ctrl.Result{}, nil
}
gitServerResource := &v1alpha1.GitServer{
ObjectMeta: metav1.ObjectMeta{
Name: EmbeddedGitServerName,
Namespace: globals.GetProjectNamespace(resource.Name),
},
}
log.Info("Create or update git server", "resource", gitServerResource)
_, err := controllerutil.CreateOrUpdate(ctx, r.Client, gitServerResource, func() error {
if err := controllerutil.SetControllerReference(resource, gitServerResource, r.Scheme); err != nil {
log.Error(err, "Setting controller ref on git server resource")
return err
}
gitServerResource.Spec.Source.Embedded = true
return nil
})
if err != nil {
log.Error(err, "Create or Update git server resource")
}
// Bail if the GitServer deployment is not yet available
if !gitServerResource.Status.DeploymentAvailable {
log.Info("Waiting for GitServer to become available before creating argo applications")
return ctrl.Result{
RequeueAfter: time.Second * 10,
}, nil
}
return ctrl.Result{}, err
}
func (r *LocalbuildReconciler) ReconcileArgoAppsWithGitServer(ctx context.Context, req ctrl.Request, resource *v1alpha1.Localbuild) (ctrl.Result, error) {
log := log.FromContext(ctx)
// Bail if embedded argo applications not enabled
if !resource.Spec.PackageConfigs.EmbeddedArgoApplications.Enabled {
log.Info("embedded argo applications disabled, not installing embedded git server")
r.shouldShutdown = true
return ctrl.Result{}, nil
}
// Create argo project
// DeepEqual is broken on argo resources for some reason so we have to DIY create/update
project := &argov1alpha1.AppProject{
ObjectMeta: metav1.ObjectMeta{
Name: resource.GetArgoProjectName(),
Namespace: "argocd",
},
}
if err := r.Client.Get(ctx, client.ObjectKeyFromObject(project), project); err != nil {
localbuild.SetProjectSpec(project)
log.Info("Creating project", "resource", project)
if err := r.Client.Create(ctx, project); err != nil {
log.Error(err, "Creating argo project", "resource", project)
return ctrl.Result{}, err
}
}
foundGitServer := &v1alpha1.GitServer{
ObjectMeta: metav1.ObjectMeta{
Name: EmbeddedGitServerName,
Namespace: globals.GetProjectNamespace(resource.Name),
},
}
err := r.Client.Get(ctx, client.ObjectKeyFromObject(foundGitServer), foundGitServer)
if err != nil && errors.IsNotFound(err) {
log.Error(err, "Could not find GitServer")
return ctrl.Result{}, err
}
if !foundGitServer.Spec.Source.Embedded {
log.Info("Not using embedded source, skipping argo app creation")
return ctrl.Result{}, nil
}
// Install Argo Apps
for _, embedApp := range apps.EmbedApps {
log.Info("Ensuring Argo Application", "name", embedApp.Name)
app := &argov1alpha1.Application{
ObjectMeta: metav1.ObjectMeta{
Name: resource.GetArgoApplicationName(embedApp.Name),
Namespace: "argocd",
},
}
if err := controllerutil.SetControllerReference(resource, app, r.Scheme); err != nil {
return ctrl.Result{}, err
}
if err := r.Client.Get(ctx, client.ObjectKeyFromObject(app), app); err != nil {
log.Info("Argo app doesnt exist, creating", "name", embedApp.Name)
repoUrl := getRepoUrl(foundGitServer)
localbuild.SetApplicationSpec(
app,
repoUrl,
embedApp.Path,
defaultArgoCDProjectName,
"argocd",
nil,
)
if err := r.Client.Create(ctx, app); err != nil {
log.Error(err, "Creating argo app", "resource", app)
return ctrl.Result{}, err
}
} else {
log.Info("Argo app exists, skipping", "name", embedApp.Name)
}
}
resource.Status.ArgoCD.AppsCreated = true
r.shouldShutdown = true
return ctrl.Result{}, nil
}
// SetupWithManager sets up the controller with the Manager.
func (r *LocalbuildReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&v1alpha1.Localbuild{}).
Complete(r)
}
func (r *LocalbuildReconciler) ReconcileArgoAppsWithGitea(ctx context.Context, req ctrl.Request, resource *v1alpha1.Localbuild) (ctrl.Result, error) {
logger := log.FromContext(ctx)
logger.Info("installing bootstrap apps to ArgoCD")
// push bootstrap app manifests to Gitea. let ArgoCD take over
// will need a way to filter them based on user input
bootStrapApps := []string{"argocd", "nginx", "gitea"}
for _, n := range bootStrapApps {
result, err := r.reconcileEmbeddedApp(ctx, n, resource)
if err != nil {
return result, fmt.Errorf("reconciling bootstrap apps %w", err)
}
}
// do the same for embedded applications
for _, embedApp := range apps.EmbedApps {
result, err := r.reconcileEmbeddedApp(ctx, embedApp.Name, resource)
if err != nil {
return result, fmt.Errorf("reconciling embedded apps %w", err)
}
}
shutdown, err := r.shouldShutDown(ctx, resource)
if err != nil {
return ctrl.Result{Requeue: true}, err
}
r.shouldShutdown = shutdown
return ctrl.Result{RequeueAfter: time.Second * 30}, nil
}
func (r *LocalbuildReconciler) reconcileEmbeddedApp(ctx context.Context, appName string, resource *v1alpha1.Localbuild) (ctrl.Result, error) {
logger := log.FromContext(ctx)
logger.Info("Ensuring Argo Application", "name", appName)
repo := &v1alpha1.GitRepository{
ObjectMeta: metav1.ObjectMeta{
Name: appName,
Namespace: globals.GetProjectNamespace(resource.Name),
},
Spec: v1alpha1.GitRepositorySpec{
Source: v1alpha1.GitRepositorySource{
EmbeddedAppName: appName,
Type: "embedded",
},
GitURL: resource.Status.Gitea.ExternalURL,
SecretRef: v1alpha1.SecretReference{
Name: resource.Status.Gitea.AdminUserSecretName,
Namespace: resource.Status.Gitea.AdminUserSecretNamespace,
},
},
}
_, err := controllerutil.CreateOrUpdate(ctx, r.Client, repo, func() error {
if err := controllerutil.SetControllerReference(resource, repo, r.Scheme); err != nil {
return err
}
return nil
})
if err != nil {
return ctrl.Result{}, fmt.Errorf("creating %s repo CR: %w", appName, err)
}
app := &argov1alpha1.Application{
ObjectMeta: metav1.ObjectMeta{
Name: appName,
Namespace: "argocd",
},
}
if err := controllerutil.SetControllerReference(resource, app, r.Scheme); err != nil {
return ctrl.Result{}, err
}
err = r.Client.Get(ctx, client.ObjectKeyFromObject(app), app)
if err != nil && errors.IsNotFound(err) {
localbuild.SetApplicationSpec(
app,
getRepositoryURL(repo.Namespace, repo.Name, resource.Status.Gitea.InternalURL),
".",
defaultArgoCDProjectName,
appName,
nil,
)
err = r.Client.Create(ctx, app)
if err != nil {
return ctrl.Result{}, fmt.Errorf("creating %s app CR: %w", appName, err)
}
}
return ctrl.Result{}, nil
}
func (r *LocalbuildReconciler) shouldShutDown(ctx context.Context, resource *v1alpha1.Localbuild) (bool, error) {
repos := &v1alpha1.GitRepositoryList{}
err := r.Client.List(ctx, repos, client.InNamespace(resource.Namespace))
if err != nil {
return false, fmt.Errorf("getting repo list %w", err)
}
for i := range repos.Items {
repo := repos.Items[i]
if !repo.Status.Synced {
return false, nil
}
}
return true, nil
}
func GetEmbeddedRawInstallResources(name string) ([][]byte, error) {
switch name {
case "argocd":
return RawArgocdInstallResources()
case "backstage", "crossplane":
return util.ConvertFSToBytes(apps.EmbeddedAppsFS, fmt.Sprintf("srv/%s", name))
case "gitea":
return RawGiteaInstallResources()
case "nginx":
return RawNginxInstallResources()
default:
return nil, fmt.Errorf("unsupported embedded app name %s", name)
}
}