-
Notifications
You must be signed in to change notification settings - Fork 62
/
controller.go
263 lines (221 loc) · 8.25 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
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"
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 (
EmbeddedGitServerName string = "embedded"
gitServerResourceName string = "gitserver"
gitServerDeploymentContainerName string = "httpd"
gitServerIngressHostnameBase string = ".idpbuilder.cnoe.io.local"
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", 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)
subReconcilers := []subReconciler{
r.ReconcileProjectNamespace,
r.ReconcileArgo,
r.ReconcileEmbeddedGitServer,
r.ReconcileArgoApps,
}
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.ArgoAvailable {
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) ReconcileArgoApps(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,
resource.GetArgoProjectName(),
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.ArgoAppsCreated = 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)
}