-
Notifications
You must be signed in to change notification settings - Fork 2
/
runner.go
658 lines (559 loc) · 16.5 KB
/
runner.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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
package bootstrap
import (
"context"
"fmt"
"io"
"os"
"time"
"github.com/giantswarm/apiextensions/v3/pkg/apis/application/v1alpha1"
pkgcrd "github.com/giantswarm/app/v5/pkg/crd"
"github.com/giantswarm/appcatalog"
"github.com/giantswarm/apptest"
"github.com/giantswarm/backoff"
"github.com/giantswarm/helmclient/v4/pkg/helmclient"
"github.com/giantswarm/k8sclient/v5/pkg/k8sclient"
"github.com/giantswarm/microerror"
"github.com/giantswarm/micrologger"
"github.com/giantswarm/to"
"github.com/spf13/afero"
"github.com/spf13/cobra"
corev1 "k8s.io/api/core/v1"
v1 "k8s.io/api/core/v1"
networkingv1 "k8s.io/api/networking/v1"
policyv1beta1 "k8s.io/api/policy/v1beta1"
rbacv1 "k8s.io/api/rbac/v1"
schedulingv1 "k8s.io/api/scheduling/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
clientcmdlatest "k8s.io/client-go/tools/clientcmd/api/latest"
"sigs.k8s.io/yaml"
)
const (
appOperatorVersion = "5.2.0"
chartMuseumName = "chartmuseum"
chartMuseumCatalogStorageURL = "http://chartmuseum-chartmuseum:8080/charts/"
chartMuseumVersion = "2.13.3"
chartOperatorVersion = "2.19.0"
controlPlaneCatalogStorageURL = "https://giantswarm.github.io/control-plane-catalog/"
helmStableCatalogName = "helm-stable"
helmStableCatalogStorageURL = "https://charts.helm.sh/stable/packages/"
namespace = "giantswarm"
)
type runner struct {
flag *flag
logger micrologger.Logger
stdout io.Writer
stderr io.Writer
}
type Patch struct {
Op string `json:"op"`
Path string `json:"path"`
Value string `json:"value,omitempty"`
}
func (r *runner) Run(cmd *cobra.Command, args []string) error {
ctx := context.Background()
err := r.flag.Validate()
if err != nil {
return microerror.Mask(err)
}
err = r.run(ctx, cmd, args)
if err != nil {
return microerror.Mask(err)
}
return nil
}
func (r *runner) run(ctx context.Context, cmd *cobra.Command, args []string) error {
var err error
var kubeConfig string
var restConfig *rest.Config
{
if r.flag.KubeConfig != "" {
// Set kube config for passing to the apptest library.
kubeConfig = r.flag.KubeConfig
bytes := []byte(kubeConfig)
restConfig, err = clientcmd.RESTConfigFromKubeConfig(bytes)
if err != nil {
return microerror.Mask(err)
}
} else if r.flag.KubeConfigPath != "" {
restConfig, err = clientcmd.BuildConfigFromFlags("", r.flag.KubeConfigPath)
if err != nil {
return microerror.Mask(err)
}
} else if os.Getenv(kubeconfigEnvVar) != "" {
loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
mergedConfig, err := loadingRules.Load()
if err != nil {
return microerror.Mask(err)
}
json, err := runtime.Encode(clientcmdlatest.Codec, mergedConfig)
if err != nil {
return microerror.Mask(err)
}
bytes, err := yaml.JSONToYAML(json)
if err != nil {
return microerror.Mask(err)
}
// Set kube config for passing to the apptest library.
kubeConfig = string(bytes)
restConfig, err = clientcmd.RESTConfigFromKubeConfig(bytes)
if err != nil {
return microerror.Mask(err)
}
} else {
// Shouldn't happen but returning error just in case.
return microerror.Maskf(invalidConfigError, "KubeConfig and KubeConfigPath must not be empty at the same time")
}
}
var k8sClients k8sclient.Interface
{
c := k8sclient.ClientsConfig{
Logger: r.logger,
RestConfig: restConfig,
}
k8sClients, err = k8sclient.NewClients(c)
if err != nil {
return microerror.Mask(err)
}
}
var helmClient helmclient.Interface
{
c := helmclient.Config{
K8sClient: k8sClients.K8sClient(),
Logger: r.logger,
RestClient: k8sClients.RESTClient(),
RestConfig: k8sClients.RESTConfig(),
}
helmClient, err = helmclient.New(c)
if err != nil {
return microerror.Mask(err)
}
}
var appTest apptest.Interface
{
c := apptest.Config{
KubeConfig: kubeConfig,
KubeConfigPath: r.flag.KubeConfigPath,
Logger: r.logger,
}
appTest, err = apptest.New(c)
if err != nil {
return microerror.Mask(err)
}
}
err = r.ensureCRDs(ctx, k8sClients)
if err != nil {
return microerror.Mask(err)
}
err = r.ensurePriorityClass(ctx, k8sClients)
if err != nil {
return microerror.Mask(err)
}
err = r.ensureNamespace(ctx, k8sClients)
if err != nil {
return microerror.Mask(err)
}
if r.flag.InstallOperators {
err = r.installOperators(ctx, helmClient, k8sClients)
if err != nil {
return microerror.Mask(err)
}
} else {
r.logger.LogCtx(ctx, "level", "debug", "message", "skipping installing operators")
}
err = r.installCatalogs(ctx, k8sClients)
if err != nil {
return microerror.Mask(err)
}
err = r.ensureChartMuseumPSP(ctx, k8sClients)
if err != nil {
return microerror.Mask(err)
}
err = r.installChartMuseum(ctx, appTest)
if err != nil {
return microerror.Mask(err)
}
err = r.waitForChartMuseum(ctx, appTest)
if err != nil {
return microerror.Mask(err)
}
return nil
}
func (r *runner) ensureCRDs(ctx context.Context, k8sClients k8sclient.Interface) error {
var err error
// Ensure Application group CRDs are created.
crds := []string{
"AppCatalogEntry",
"AppCatalog",
"App",
"Catalog",
"Chart",
}
var crdGetter *pkgcrd.CRDGetter
{
cc := pkgcrd.Config{
Logger: r.logger,
GitHubToken: r.flag.GithubToken,
}
crdGetter, err = pkgcrd.NewCRDGetter(cc)
if err != nil {
return microerror.Mask(err)
}
}
{
for _, crdName := range crds {
r.logger.Debugf(ctx, "ensuring %#q CRD", crdName)
crd, err := crdGetter.LoadCRD(ctx, "application.giantswarm.io", crdName)
if err != nil {
return microerror.Mask(err)
}
err = k8sClients.CRDClient().EnsureCreated(ctx, crd, backoff.NewMaxRetries(7, 1*time.Second))
if err != nil {
return microerror.Mask(err)
}
r.logger.Debugf(ctx, "ensured %#q CRD exists", crdName)
}
}
return nil
}
func (r *runner) ensureNamespace(ctx context.Context, k8sClients k8sclient.Interface) error {
namespace := "giantswarm"
r.logger.Debugf(ctx, "ensuring namespace %#q", namespace)
o := func() error {
{
n := &corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: namespace,
},
}
_, err := k8sClients.K8sClient().CoreV1().Namespaces().Create(ctx, n, metav1.CreateOptions{})
if apierrors.IsAlreadyExists(err) {
r.logger.Debugf(ctx, "namespace %#q already exists", namespace)
// fall through
} else if err != nil {
return microerror.Mask(err)
}
}
{
n, err := k8sClients.K8sClient().CoreV1().Namespaces().Get(ctx, namespace, metav1.GetOptions{})
if err != nil {
return microerror.Mask(err)
}
if n.Status.Phase != v1.NamespaceActive {
return microerror.Maskf(executionFailedError, fmt.Sprintf("namespace in status %#q", n.Status.Phase))
}
}
return nil
}
b := backoff.NewExponential(backoff.ShortMaxWait, backoff.ShortMaxInterval)
err := backoff.Retry(o, b)
if err != nil {
return microerror.Mask(err)
}
r.logger.Debugf(ctx, "ensured namespace %#q", namespace)
return nil
}
func (r *runner) ensurePriorityClass(ctx context.Context, k8sClients k8sclient.Interface) error {
priorityClassName := "giantswarm-critical"
r.logger.Debugf(ctx, "creating priorityclass %#q", priorityClassName)
pc := &schedulingv1.PriorityClass{
ObjectMeta: metav1.ObjectMeta{
Name: priorityClassName,
},
Value: 1000000000,
GlobalDefault: false,
Description: "This priority class is used by giantswarm kubernetes components.",
}
_, err := k8sClients.K8sClient().SchedulingV1().PriorityClasses().Create(ctx, pc, metav1.CreateOptions{})
if apierrors.IsAlreadyExists(err) {
r.logger.Debugf(ctx, "priorityclass %#q already exists", priorityClassName)
// fall through
} else if err != nil {
return microerror.Mask(err)
} else {
r.logger.Debugf(ctx, "created priorityclass %#q", priorityClassName)
}
return nil
}
func (r *runner) installCatalogs(ctx context.Context, k8sClients k8sclient.Interface) error {
var err error
catalogs := map[string]string{
chartMuseumName: chartMuseumCatalogStorageURL,
}
for name, url := range catalogs {
r.logger.Debugf(ctx, "creating %#q catalog cr", name)
catalogCR := &v1alpha1.Catalog{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: metav1.NamespaceDefault,
},
Spec: v1alpha1.CatalogSpec{
Description: name,
Title: name,
Storage: v1alpha1.CatalogSpecStorage{
Type: "helm",
URL: url,
},
},
}
_, err = k8sClients.G8sClient().ApplicationV1alpha1().Catalogs(catalogCR.Namespace).Create(ctx, catalogCR, metav1.CreateOptions{})
if apierrors.IsAlreadyExists(err) {
r.logger.Debugf(ctx, "%#q catalog CR already exists", catalogCR.Name)
} else if err != nil {
return microerror.Mask(err)
}
r.logger.Debugf(ctx, "created %#q catalog cr", name)
}
return nil
}
func (r *runner) ensureChartMuseumPSP(ctx context.Context, k8sClients k8sclient.Interface) error {
name := "chartmuseum-psp"
r.logger.Debugf(ctx, "ensuring psp %#q", name)
o := func() error {
{
clusterRole := &rbacv1.ClusterRole{
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
Rules: []rbacv1.PolicyRule{
{
APIGroups: []string{"extensions"},
Resources: []string{"podsecuritypolicies"},
ResourceNames: []string{name},
Verbs: []string{"use"},
},
},
}
_, err := k8sClients.K8sClient().RbacV1().ClusterRoles().Create(ctx, clusterRole, metav1.CreateOptions{})
if apierrors.IsAlreadyExists(err) {
r.logger.Debugf(ctx, "clusterRole %#q already exists", name)
// fall through
} else if err != nil {
return microerror.Mask(err)
}
}
{
clusterRoleBinding := &rbacv1.ClusterRoleBinding{
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
Subjects: []rbacv1.Subject{
{
Kind: "ServiceAccount",
Name: "chartmuseum",
Namespace: namespace,
},
},
RoleRef: rbacv1.RoleRef{
Kind: "ClusterRole",
Name: name,
APIGroup: "rbac.authorization.k8s.io",
},
}
_, err := k8sClients.K8sClient().RbacV1().ClusterRoleBindings().Create(ctx, clusterRoleBinding, metav1.CreateOptions{})
if apierrors.IsAlreadyExists(err) {
r.logger.Debugf(ctx, "clusterRoleBinding %#q already exists", name)
// fall through
} else if err != nil {
return microerror.Mask(err)
}
}
{
psp := &policyv1beta1.PodSecurityPolicy{
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
Spec: policyv1beta1.PodSecurityPolicySpec{
AllowPrivilegeEscalation: to.BoolP(true),
Volumes: []policyv1beta1.FSType{
policyv1beta1.All,
},
RunAsUser: policyv1beta1.RunAsUserStrategyOptions{
Rule: policyv1beta1.RunAsUserStrategyRunAsAny,
},
SupplementalGroups: policyv1beta1.SupplementalGroupsStrategyOptions{
Rule: policyv1beta1.SupplementalGroupsStrategyRunAsAny,
},
FSGroup: policyv1beta1.FSGroupStrategyOptions{
Rule: policyv1beta1.FSGroupStrategyRunAsAny,
},
SELinux: policyv1beta1.SELinuxStrategyOptions{
Rule: policyv1beta1.SELinuxStrategyRunAsAny,
},
},
}
_, err := k8sClients.K8sClient().PolicyV1beta1().PodSecurityPolicies().Create(ctx, psp, metav1.CreateOptions{})
if apierrors.IsAlreadyExists(err) {
r.logger.Debugf(ctx, "psp %#q already exists", name)
// fall through
} else if err != nil {
return microerror.Mask(err)
}
}
{
tcp := corev1.ProtocolTCP
chartmuseumPort := intstr.FromInt(8080)
np := &networkingv1.NetworkPolicy{
ObjectMeta: metav1.ObjectMeta{
Name: "chartmuseum",
Namespace: namespace,
},
Spec: networkingv1.NetworkPolicySpec{
PodSelector: metav1.LabelSelector{
MatchLabels: map[string]string{
"app": "chartmuseum",
"release": "chartmuseum",
},
},
Egress: []networkingv1.NetworkPolicyEgressRule{},
Ingress: []networkingv1.NetworkPolicyIngressRule{
{
Ports: []networkingv1.NetworkPolicyPort{
{
Protocol: &tcp,
Port: &chartmuseumPort,
},
},
},
},
PolicyTypes: []networkingv1.PolicyType{
networkingv1.PolicyTypeIngress,
networkingv1.PolicyTypeEgress,
},
},
}
_, err := k8sClients.K8sClient().NetworkingV1().NetworkPolicies(namespace).Create(ctx, np, metav1.CreateOptions{})
if apierrors.IsAlreadyExists(err) {
r.logger.Debugf(ctx, "networkpolicy %#q already exists", name)
// fall through
} else if err != nil {
return microerror.Mask(err)
}
}
return nil
}
b := backoff.NewExponential(backoff.ShortMaxWait, backoff.ShortMaxInterval)
err := backoff.Retry(o, b)
if err != nil {
return microerror.Mask(err)
}
r.logger.Debugf(ctx, "ensured psp %#q", name)
return nil
}
func (r *runner) installChartMuseum(ctx context.Context, appTest apptest.Interface) error {
var err error
{
r.logger.Debugf(ctx, "creating %#q app cr", chartMuseumName)
apps := []apptest.App{
{
CatalogName: helmStableCatalogName,
CatalogURL: helmStableCatalogStorageURL,
Name: chartMuseumName,
Namespace: namespace,
ValuesYAML: chartMuseumValuesYAML,
Version: chartMuseumVersion,
WaitForDeploy: r.flag.Wait,
},
}
err = appTest.InstallApps(ctx, apps)
if err != nil {
return microerror.Mask(err)
}
r.logger.Debugf(ctx, "created %#q app cr", chartMuseumName)
}
return nil
}
func (r *runner) installOperators(ctx context.Context, helmClient helmclient.Interface, k8sClients k8sclient.Interface) error {
var err error
operators := map[string]string{
"app-operator": appOperatorVersion,
"chart-operator": chartOperatorVersion,
}
for name, version := range operators {
err = r.installOperator(ctx, helmClient, name, version)
if err != nil {
return microerror.Mask(err)
}
}
return nil
}
func (r *runner) installOperator(ctx context.Context, helmClient helmclient.Interface, name, version string) error {
var operatorTarballPath string
{
r.logger.Debugf(ctx, "getting tarball URL for %#q", name)
operatorTarballURL, err := appcatalog.GetLatestChart(ctx, controlPlaneCatalogStorageURL, name, version)
if err != nil {
return microerror.Mask(err)
}
r.logger.Debugf(ctx, "tarball URL is %#q", operatorTarballURL)
r.logger.Debugf(ctx, "pulling tarball")
operatorTarballPath, err = helmClient.PullChartTarball(ctx, operatorTarballURL)
if err != nil {
return microerror.Mask(err)
}
r.logger.Debugf(ctx, "tarball path is %#q", operatorTarballPath)
}
{
defer func() {
fs := afero.NewOsFs()
err := fs.Remove(operatorTarballPath)
if err != nil {
r.logger.Errorf(ctx, err, "deletion of %#q failed", operatorTarballPath)
}
}()
r.logger.Debugf(ctx, "installing %#q", name)
var input map[string]interface{}
err := yaml.Unmarshal([]byte(operatorValuesYAML), &input)
if err != nil {
return microerror.Mask(err)
}
opts := helmclient.InstallOptions{
ReleaseName: name,
}
err = helmClient.InstallReleaseFromTarball(ctx,
operatorTarballPath,
namespace,
input,
opts)
if helmclient.IsCannotReuseRelease(err) {
r.logger.Debugf(ctx, "%#q already installed", name)
return nil
} else if helmclient.IsReleaseAlreadyExists(err) {
r.logger.Debugf(ctx, "%#q already installed", name)
return nil
} else if err != nil {
return microerror.Mask(err)
}
r.logger.Debugf(ctx, "installed %#q", name)
}
return nil
}
func (r *runner) waitForChartMuseum(ctx context.Context, appTest apptest.Interface) error {
var err error
deployName := fmt.Sprintf("%s-%s", chartMuseumName, chartMuseumName)
r.logger.Debugf(ctx, "waiting for ready %#q deployment", deployName)
o := func() error {
deploy, err := appTest.K8sClient().AppsV1().Deployments(namespace).Get(ctx, deployName, metav1.GetOptions{})
if err != nil {
return microerror.Mask(err)
}
if *deploy.Spec.Replicas != deploy.Status.ReadyReplicas {
return microerror.Maskf(executionFailedError, "waiting for %d ready pods, current %d", *deploy.Spec.Replicas, deploy.Status.ReadyReplicas)
}
return nil
}
n := func(err error, t time.Duration) {
r.logger.Errorf(ctx, err, "failed to get ready deployment '%s': retrying in %s", deployName, t)
}
b := backoff.NewConstant(5*time.Minute, 10*time.Second)
err = backoff.RetryNotify(o, b, n)
if err != nil {
return microerror.Mask(err)
}
r.logger.Debugf(ctx, "waited for ready %#q deployment", deployName)
return nil
}