/
app_repository.go
575 lines (491 loc) · 16.6 KB
/
app_repository.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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
package repositories
import (
"context"
"fmt"
"sort"
"strings"
"time"
"code.cloudfoundry.org/cf-k8s-controllers/api/apierrors"
"code.cloudfoundry.org/cf-k8s-controllers/api/authorization"
workloadsv1alpha1 "code.cloudfoundry.org/cf-k8s-controllers/controllers/apis/workloads/v1alpha1"
"code.cloudfoundry.org/cf-k8s-controllers/controllers/webhooks"
"github.com/google/uuid"
corev1 "k8s.io/api/core/v1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
_ "k8s.io/client-go/plugin/pkg/client/auth"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
)
//+kubebuilder:rbac:groups=workloads.cloudfoundry.org,resources=cfapps,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=workloads.cloudfoundry.org,resources=cfapps/status,verbs=get
//+kubebuilder:rbac:groups="",resources=secrets,verbs=create;patch;update
const (
StartedState DesiredState = "STARTED"
StoppedState DesiredState = "STOPPED"
Kind string = "CFApp"
APIVersion string = "workloads.cloudfoundry.org/v1alpha1"
TimestampFormat string = time.RFC3339
CFAppGUIDLabel string = "workloads.cloudfoundry.org/app-guid"
AppResourceType string = "App"
AppEnvResourceType string = "App Env"
)
type AppRepo struct {
privilegedClient client.Client
namespaceRetriever NamespaceRetriever
userClientFactory UserK8sClientFactory
namespacePermissions *authorization.NamespacePermissions
}
func NewAppRepo(
privilegedClient client.Client,
namespaceRetriever NamespaceRetriever,
userClientFactory UserK8sClientFactory,
authPerms *authorization.NamespacePermissions,
) *AppRepo {
return &AppRepo{
privilegedClient: privilegedClient,
namespaceRetriever: namespaceRetriever,
userClientFactory: userClientFactory,
namespacePermissions: authPerms,
}
}
type AppRecord struct {
Name string
GUID string
EtcdUID types.UID
Revision string
SpaceGUID string
DropletGUID string
Labels map[string]string
Annotations map[string]string
State DesiredState
Lifecycle Lifecycle
CreatedAt string
UpdatedAt string
envSecretName string
}
type DesiredState string
type Lifecycle struct {
Type string
Data LifecycleData
}
type LifecycleData struct {
Buildpacks []string
Stack string
}
type AppEnvVarsRecord struct {
Name string
AppGUID string
SpaceGUID string
EnvironmentVariables map[string]string
}
type CurrentDropletRecord struct {
AppGUID string
DropletGUID string
}
type CreateAppMessage struct {
Name string
SpaceGUID string
Labels map[string]string
Annotations map[string]string
State DesiredState
Lifecycle Lifecycle
EnvironmentVariables map[string]string
}
type DeleteAppMessage struct {
AppGUID string
SpaceGUID string
}
type CreateOrPatchAppEnvVarsMessage struct {
AppGUID string
AppEtcdUID types.UID
SpaceGUID string
EnvironmentVariables map[string]string
}
type PatchAppEnvVarsMessage struct {
AppGUID string
SpaceGUID string
EnvironmentVariables map[string]*string
}
type SetCurrentDropletMessage struct {
AppGUID string
DropletGUID string
SpaceGUID string
}
type SetAppDesiredStateMessage struct {
AppGUID string
SpaceGUID string
DesiredState string
}
type ListAppsMessage struct {
Names []string
Guids []string
SpaceGuids []string
}
type byName []AppRecord
func (a byName) Len() int {
return len(a)
}
func (a byName) Less(i, j int) bool {
return a[i].Name < a[j].Name
}
func (a byName) Swap(i, j int) {
a[i], a[j] = a[j], a[i]
}
func (f *AppRepo) GetApp(ctx context.Context, authInfo authorization.Info, appGUID string) (AppRecord, error) {
ns, err := f.namespaceRetriever.NamespaceFor(ctx, appGUID, AppResourceType)
if err != nil {
return AppRecord{}, err
}
userClient, err := f.userClientFactory.BuildClient(authInfo)
if err != nil {
return AppRecord{}, fmt.Errorf("get-app failed to build user client: %w", err)
}
app := workloadsv1alpha1.CFApp{}
err = userClient.Get(ctx, client.ObjectKey{Namespace: ns, Name: appGUID}, &app)
if err != nil {
return AppRecord{}, fmt.Errorf("failed to get app: %w", apierrors.FromK8sError(err, AppResourceType))
}
return cfAppToAppRecord(app), nil
}
func (f *AppRepo) GetAppByNameAndSpace(ctx context.Context, authInfo authorization.Info, appName string, spaceGUID string) (AppRecord, error) {
appList := new(workloadsv1alpha1.CFAppList)
err := f.privilegedClient.List(ctx, appList, client.InNamespace(spaceGUID))
if err != nil {
return AppRecord{}, apierrors.FromK8sError(fmt.Errorf("get app: failed to list apps: %w", err), AppResourceType)
}
var matchingApps []workloadsv1alpha1.CFApp
for _, app := range appList.Items {
if app.Spec.Name == appName {
matchingApps = append(matchingApps, app)
}
}
if len(matchingApps) == 0 {
return AppRecord{}, apierrors.NewNotFoundError(fmt.Errorf("app %q in space %q not found", appName, spaceGUID), AppResourceType)
}
if len(matchingApps) > 1 {
return AppRecord{}, fmt.Errorf("duplicate instances of app %q in space %q", appName, spaceGUID)
}
return cfAppToAppRecord(matchingApps[0]), nil
}
func (f *AppRepo) CreateApp(ctx context.Context, authInfo authorization.Info, appCreateMessage CreateAppMessage) (AppRecord, error) {
userClient, err := f.userClientFactory.BuildClient(authInfo)
if err != nil {
return AppRecord{}, fmt.Errorf("failed to build user client: %w", err)
}
cfApp := appCreateMessage.toCFApp()
err = userClient.Create(ctx, &cfApp)
if err != nil {
if webhooks.HasErrorCode(err, webhooks.DuplicateAppError) {
errorDetail := fmt.Sprintf("App with the name '%s' already exists.", appCreateMessage.Name)
return AppRecord{}, apierrors.NewUniquenessError(err, errorDetail)
}
return AppRecord{}, apierrors.FromK8sError(err, AppResourceType)
}
envVarsMessage := CreateOrPatchAppEnvVarsMessage{
AppGUID: cfApp.Name,
AppEtcdUID: cfApp.UID,
SpaceGUID: cfApp.Namespace,
EnvironmentVariables: appCreateMessage.EnvironmentVariables,
}
_, err = f.CreateOrPatchAppEnvVars(ctx, authInfo, envVarsMessage)
if err != nil {
return AppRecord{}, err
}
return cfAppToAppRecord(cfApp), nil
}
func (f *AppRepo) ListApps(ctx context.Context, authInfo authorization.Info, message ListAppsMessage) ([]AppRecord, error) {
nsList, err := f.namespacePermissions.GetAuthorizedSpaceNamespaces(ctx, authInfo)
if err != nil {
return nil, fmt.Errorf("failed to list namespaces for spaces with user role bindings: %w", err)
}
userClient, err := f.userClientFactory.BuildClient(authInfo)
if err != nil {
return []AppRecord{}, fmt.Errorf("failed to build user client: %w", err)
}
var filteredApps []workloadsv1alpha1.CFApp
for ns := range nsList {
appList := &workloadsv1alpha1.CFAppList{}
err := userClient.List(ctx, appList, client.InNamespace(ns))
if k8serrors.IsForbidden(err) {
continue
}
if err != nil {
return []AppRecord{}, fmt.Errorf("failed to list apps in namespace %s: %w", ns, apierrors.FromK8sError(err, AppResourceType))
}
filteredApps = append(filteredApps, applyAppListFilter(appList.Items, message)...)
}
appRecords := returnAppList(filteredApps)
// By default sort it by App.Name
sort.Sort(byName(appRecords))
return appRecords, nil
}
func applyAppListFilter(appList []workloadsv1alpha1.CFApp, message ListAppsMessage) []workloadsv1alpha1.CFApp {
nameFilterSpecified := len(message.Names) > 0
guidsFilterSpecified := len(message.Guids) > 0
spaceGUIDFilterSpecified := len(message.SpaceGuids) > 0
var filtered []workloadsv1alpha1.CFApp
if guidsFilterSpecified {
for _, app := range appList {
for _, guid := range message.Guids {
if appMatchesGUID(app, guid) {
filtered = append(filtered, app)
}
}
}
}
if guidsFilterSpecified && len(filtered) == 0 {
return filtered
}
if len(filtered) > 0 {
appList = filtered
filtered = []workloadsv1alpha1.CFApp{}
}
if !nameFilterSpecified && !spaceGUIDFilterSpecified {
return appList
}
for _, app := range appList {
if nameFilterSpecified && spaceGUIDFilterSpecified {
for _, name := range message.Names {
for _, spaceGUID := range message.SpaceGuids {
if appBelongsToSpace(app, spaceGUID) && appMatchesName(app, name) {
filtered = append(filtered, app)
}
}
}
} else if nameFilterSpecified {
for _, name := range message.Names {
if appMatchesName(app, name) {
filtered = append(filtered, app)
}
}
} else if spaceGUIDFilterSpecified {
for _, spaceGUID := range message.SpaceGuids {
if appBelongsToSpace(app, spaceGUID) {
filtered = append(filtered, app)
}
}
}
}
return filtered
}
func appBelongsToSpace(app workloadsv1alpha1.CFApp, spaceGUID string) bool {
return app.Namespace == spaceGUID
}
func appMatchesName(app workloadsv1alpha1.CFApp, name string) bool {
return app.Spec.Name == name
}
func appMatchesGUID(app workloadsv1alpha1.CFApp, guid string) bool {
return app.Name == guid
}
func returnAppList(appList []workloadsv1alpha1.CFApp) []AppRecord {
appRecords := make([]AppRecord, 0, len(appList))
for _, app := range appList {
appRecords = append(appRecords, cfAppToAppRecord(app))
}
return appRecords
}
func (f *AppRepo) PatchAppEnvVars(ctx context.Context, authInfo authorization.Info, message PatchAppEnvVarsMessage) (AppEnvVarsRecord, error) {
secretObj := corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: generateEnvSecretName(message.AppGUID),
Namespace: message.SpaceGUID,
},
}
userClient, err := f.userClientFactory.BuildClient(authInfo)
if err != nil {
return AppEnvVarsRecord{}, fmt.Errorf("failed to build user client: %w", err)
}
_, err = controllerutil.CreateOrPatch(ctx, userClient, &secretObj, func() error {
secretObj.StringData = map[string]string{}
for k, v := range message.EnvironmentVariables {
if v == nil {
delete(secretObj.Data, k)
} else {
secretObj.StringData[k] = *v
}
}
return nil
})
if err != nil {
return AppEnvVarsRecord{}, apierrors.FromK8sError(err, AppEnvResourceType)
}
return appEnvVarsSecretToRecord(secretObj), nil
}
func (f *AppRepo) CreateOrPatchAppEnvVars(ctx context.Context, authInfo authorization.Info, envVariables CreateOrPatchAppEnvVarsMessage) (AppEnvVarsRecord, error) {
secretObj := appEnvVarsRecordToSecret(envVariables)
_, err := controllerutil.CreateOrPatch(ctx, f.privilegedClient, &secretObj, func() error {
secretObj.StringData = envVariables.EnvironmentVariables
return nil
})
if err != nil {
return AppEnvVarsRecord{}, apierrors.FromK8sError(err, AppEnvResourceType)
}
return appEnvVarsSecretToRecord(secretObj), nil
}
func (f *AppRepo) SetCurrentDroplet(ctx context.Context, authInfo authorization.Info, message SetCurrentDropletMessage) (CurrentDropletRecord, error) {
userClient, err := f.userClientFactory.BuildClient(authInfo)
if err != nil {
return CurrentDropletRecord{}, fmt.Errorf("set-current-droplet: failed to create k8s user client: %w", err)
}
baseCFApp := &workloadsv1alpha1.CFApp{
ObjectMeta: metav1.ObjectMeta{
Name: message.AppGUID,
Namespace: message.SpaceGUID,
},
}
cfApp := baseCFApp.DeepCopy()
cfApp.Spec.CurrentDropletRef = corev1.LocalObjectReference{Name: message.DropletGUID}
err = userClient.Patch(ctx, cfApp, client.MergeFrom(baseCFApp))
if err != nil {
return CurrentDropletRecord{}, fmt.Errorf("failed to set app droplet: %w", apierrors.FromK8sError(err, AppResourceType))
}
return CurrentDropletRecord{
AppGUID: message.AppGUID,
DropletGUID: message.DropletGUID,
}, nil
}
func (f *AppRepo) SetAppDesiredState(ctx context.Context, authInfo authorization.Info, message SetAppDesiredStateMessage) (AppRecord, error) {
baseCFApp := &workloadsv1alpha1.CFApp{
ObjectMeta: metav1.ObjectMeta{
Name: message.AppGUID,
Namespace: message.SpaceGUID,
},
}
cfApp := baseCFApp.DeepCopy()
cfApp.Spec.DesiredState = workloadsv1alpha1.DesiredState(message.DesiredState)
userClient, err := f.userClientFactory.BuildClient(authInfo)
if err != nil {
return AppRecord{}, fmt.Errorf("failed to build user client: %w", err)
}
err = userClient.Patch(ctx, cfApp, client.MergeFrom(baseCFApp))
if err != nil {
return AppRecord{}, fmt.Errorf("failed to set app desired state: %w", apierrors.FromK8sError(err, AppResourceType))
}
return cfAppToAppRecord(*cfApp), nil
}
func (f *AppRepo) DeleteApp(ctx context.Context, authInfo authorization.Info, message DeleteAppMessage) error {
cfApp := &workloadsv1alpha1.CFApp{
ObjectMeta: metav1.ObjectMeta{
Name: message.AppGUID,
Namespace: message.SpaceGUID,
},
}
userClient, err := f.userClientFactory.BuildClient(authInfo)
if err != nil {
return fmt.Errorf("failed to build user client: %w", err)
}
return apierrors.FromK8sError(userClient.Delete(ctx, cfApp), AppResourceType)
}
func (f *AppRepo) GetAppEnv(ctx context.Context, authInfo authorization.Info, appGUID string) (map[string]string, error) {
app, err := f.GetApp(ctx, authInfo, appGUID)
if err != nil {
return nil, err
}
if app.envSecretName == "" {
return nil, nil
}
userClient, err := f.userClientFactory.BuildClient(authInfo)
if err != nil {
return nil, fmt.Errorf("failed to build user client: %w", err)
}
key := client.ObjectKey{Name: app.envSecretName, Namespace: app.SpaceGUID}
secret := new(corev1.Secret)
err = userClient.Get(ctx, key, secret)
if err != nil {
return nil, fmt.Errorf("error finding environment variable Secret %q for App %q: %w",
app.envSecretName,
app.GUID,
apierrors.FromK8sError(err, AppEnvResourceType),
)
}
return convertByteSliceValuesToStrings(secret.Data), nil
}
func generateEnvSecretName(appGUID string) string {
return appGUID + "-env"
}
func (m *CreateAppMessage) toCFApp() workloadsv1alpha1.CFApp {
guid := uuid.NewString()
return workloadsv1alpha1.CFApp{
ObjectMeta: metav1.ObjectMeta{
Name: guid,
Namespace: m.SpaceGUID,
Labels: m.Labels,
Annotations: m.Annotations,
},
Spec: workloadsv1alpha1.CFAppSpec{
Name: m.Name,
DesiredState: workloadsv1alpha1.DesiredState(m.State),
EnvSecretName: generateEnvSecretName(guid),
Lifecycle: workloadsv1alpha1.Lifecycle{
Type: workloadsv1alpha1.LifecycleType(m.Lifecycle.Type),
Data: workloadsv1alpha1.LifecycleData{
Buildpacks: m.Lifecycle.Data.Buildpacks,
Stack: m.Lifecycle.Data.Stack,
},
},
},
}
}
func cfAppToAppRecord(cfApp workloadsv1alpha1.CFApp) AppRecord {
updatedAtTime, _ := getTimeLastUpdatedTimestamp(&cfApp.ObjectMeta)
return AppRecord{
GUID: cfApp.Name,
EtcdUID: cfApp.GetUID(),
Revision: getLabelOrAnnotation(cfApp.GetAnnotations(), workloadsv1alpha1.CFAppRevisionKey),
Name: cfApp.Spec.Name,
SpaceGUID: cfApp.Namespace,
DropletGUID: cfApp.Spec.CurrentDropletRef.Name,
Labels: cfApp.Labels,
Annotations: cfApp.Annotations,
State: DesiredState(cfApp.Spec.DesiredState),
Lifecycle: Lifecycle{
Type: string(cfApp.Spec.Lifecycle.Type),
Data: LifecycleData{
Buildpacks: cfApp.Spec.Lifecycle.Data.Buildpacks,
Stack: cfApp.Spec.Lifecycle.Data.Stack,
},
},
CreatedAt: cfApp.CreationTimestamp.UTC().Format(TimestampFormat),
UpdatedAt: updatedAtTime,
envSecretName: cfApp.Spec.EnvSecretName,
}
}
func appEnvVarsRecordToSecret(envVars CreateOrPatchAppEnvVarsMessage) corev1.Secret {
labels := make(map[string]string, 1)
labels[CFAppGUIDLabel] = envVars.AppGUID
return corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: generateEnvSecretName(envVars.AppGUID),
Namespace: envVars.SpaceGUID,
Labels: labels,
OwnerReferences: []metav1.OwnerReference{
{
APIVersion: APIVersion,
Kind: Kind,
Name: envVars.AppGUID,
UID: envVars.AppEtcdUID,
},
},
},
StringData: envVars.EnvironmentVariables,
}
}
func appEnvVarsSecretToRecord(envVars corev1.Secret) AppEnvVarsRecord {
appGUID := strings.TrimSuffix(envVars.Name, "-env")
return AppEnvVarsRecord{
Name: envVars.Name,
AppGUID: appGUID,
SpaceGUID: envVars.Namespace,
EnvironmentVariables: convertByteSliceValuesToStrings(envVars.Data),
}
}
func convertByteSliceValuesToStrings(inputMap map[string][]byte) map[string]string {
// StringData is a write-only field of a corev1.Secret, the real data lives in .Data and is []byte & base64 encoded
outputMap := make(map[string]string, len(inputMap))
for k, v := range inputMap {
outputMap[k] = string(v)
}
return outputMap
}