-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgitops.go
More file actions
1814 lines (1724 loc) · 60.6 KB
/
Copy pathgitops.go
File metadata and controls
1814 lines (1724 loc) · 60.6 KB
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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"os"
"path"
"path/filepath"
"regexp"
"slices"
"strconv"
"strings"
"gopkg.in/yaml.v3"
)
const moduleBundleSchema = "codefly.dev/module-bundle/v1"
var (
dnsLabelPattern = regexp.MustCompile(`^[a-z0-9](?:[-a-z0-9]*[a-z0-9])?$`)
unresolvedPattern = regexp.MustCompile(`(?i)REPLACE_ME|saas-starter|\$\{[^}]+\}|<[^>]*replace[^>]*>`)
)
type moduleManifest struct {
Name string `yaml:"name"`
ServiceEntry string `yaml:"service-entry,omitempty"`
Services []serviceReference `yaml:"services"`
}
type workspaceManifest struct {
Name string `yaml:"name"`
Environments []*environmentConfig `yaml:"environments,omitempty"`
root string
}
type environmentConfig struct {
Name string `yaml:"name"`
Namespace string `yaml:"namespace"`
Cluster environmentCluster `yaml:"cluster"`
Ingress []environmentIngressRoute `yaml:"ingress,omitempty"`
ManagedServices map[string]managedServiceConfig `yaml:"managed-services,omitempty"`
}
type environmentCluster struct {
Kind string `yaml:"kind"`
}
type environmentIngressRoute struct {
Name string `yaml:"name"`
Service string `yaml:"service"`
Endpoint string `yaml:"endpoint"`
Hosts []string `yaml:"hosts"`
}
type serviceReference struct {
Name string `yaml:"name"`
Path *string `yaml:"path,omitempty"`
}
type serviceDefinition struct {
name string
directory string
}
// moduleBundle is the typed, transport-neutral output the module plugin emits.
// It carries the module identity and, per declared environment, the
// module-owned Kubernetes overlay path plus the topology and placement metadata
// a promotion driver needs to compose repository transport (Argo, Flux, or
// otherwise) on its own. The plugin never records repositories, revisions, or
// Argo resources.
type moduleBundle struct {
SchemaVersion string `json:"schemaVersion"`
Module string `json:"module"`
Namespace string `json:"namespace"`
ServiceEntry string `json:"serviceEntry"`
Environments []bundleEnvironment `json:"environments"`
}
type bundleEnvironment struct {
Name string `json:"name"`
Namespace string `json:"namespace"`
Cluster string `json:"cluster"`
ResourcePath string `json:"resourcePath"`
Services []string `json:"services"`
Ingress []bundleIngressRoute `json:"ingress"`
ManagedServiceHandoffs []managedServiceHandoff `json:"managedServiceHandoffs,omitempty"`
}
type bundleIngressRoute struct {
Name string `json:"name"`
Service string `json:"service"`
Endpoint string `json:"endpoint"`
Port uint32 `json:"port"`
Hosts []string `json:"hosts"`
}
type managedServiceHandoff struct {
Service string `json:"service"`
AWSKind string `json:"awsKind"`
ExternalName string `json:"externalName"`
SecretReferences []string `json:"secretReferences,omitempty"`
}
type managedServiceConfig struct {
Kind string `yaml:"kind"`
ExternalName string `yaml:"external-name"`
EgressCIDRs []string `yaml:"egress-cidrs,omitempty"`
SecretReferences []managedSecretReference `yaml:"secret-references,omitempty"`
}
type managedSecretReference struct {
Name string `yaml:"name"`
RemoteKey string `yaml:"remote-key"`
SecretStore secretStoreRef `yaml:"secret-store"`
}
type secretStoreRef struct {
Name string `yaml:"name"`
Kind string `yaml:"kind"`
}
type objectMeta struct {
Name string `yaml:"name"`
Namespace string `yaml:"namespace,omitempty"`
Labels map[string]string `yaml:"labels,omitempty"`
Finalizers []string `yaml:"finalizers,omitempty"`
}
type kubeObject struct {
APIVersion string `yaml:"apiVersion"`
Kind string `yaml:"kind"`
Metadata objectMeta `yaml:"metadata"`
Spec any `yaml:"spec,omitempty"`
}
type kustomization struct {
APIVersion string `yaml:"apiVersion"`
Kind string `yaml:"kind"`
Resources []string `yaml:"resources"`
}
type environmentPlan struct {
environment *environmentConfig
cluster string
services []string
ingress []ingressRoutePlan
handoffs []managedServiceHandoff
managed map[string]managedServiceConfig
}
type ingressRoutePlan struct {
name string
service string
endpoint string
port uint32
hosts []string
}
type deploymentTopology struct {
Version string `yaml:"version"`
Module topologyModule `yaml:"module"`
Interface []topologyInterface `yaml:"interface"`
Services []topologyService `yaml:"services"`
}
type topologyModule struct {
Name string `yaml:"name"`
Namespace string `yaml:"namespace"`
ServiceEntry string `yaml:"service_entry"`
Description string `yaml:"description"`
Agent map[string]any `yaml:"agent,omitempty"`
}
type topologyInterface struct {
Service string `yaml:"service"`
Endpoint string `yaml:"endpoint"`
Visibility string `yaml:"visibility"`
}
type topologyService struct {
Name string `yaml:"name"`
Version string `yaml:"version,omitempty"`
Description string `yaml:"description,omitempty"`
Agent map[string]any `yaml:"agent,omitempty"`
WorkspaceConfigurationDependencies []string `yaml:"workspace_configuration_dependencies,omitempty"`
SecretServiceConfigurations []topologySecretServiceConfiguration `yaml:"secret_service_configurations,omitempty"`
Endpoints []topologyEndpoint `yaml:"endpoints"`
BootstrapJobEndpoints []string `yaml:"bootstrap_job_endpoints,omitempty"`
Dependencies []topologyDependency `yaml:"dependencies,omitempty"`
PublicEgressPorts []uint32 `yaml:"public_egress_ports,omitempty"`
Spec map[string]any `yaml:"spec,omitempty"`
}
type topologySecretServiceConfiguration struct {
Name string `yaml:"name"`
Entries []topologySecretServiceConfigurationEntry `yaml:"entries"`
}
type topologySecretServiceConfigurationEntry struct {
Key string `yaml:"key"`
}
type topologyEndpoint struct {
Name string `yaml:"name"`
API string `yaml:"api,omitempty"`
Visibility string `yaml:"visibility"`
Port uint32 `yaml:"port"`
}
type topologyDependency struct {
Service string `yaml:"service"`
Endpoints []string `yaml:"endpoints"`
}
func loadWorkspaceManifest(root string) (*workspaceManifest, error) {
data, err := os.ReadFile(filepath.Join(root, workspaceYamlPath))
if err != nil {
return nil, err
}
var workspace workspaceManifest
if err := yaml.Unmarshal(data, &workspace); err != nil {
return nil, err
}
workspace.root = root
return &workspace, nil
}
// generateDeploymentBundle renders the module-owned Kubernetes overlay for every
// declared environment and writes a typed, transport-neutral bundle manifest.
// It requires no Git binary, checkout, network, or cluster access.
func generateDeploymentBundle(moduleDir string, workspace *workspaceManifest) error {
manifest, err := loadModuleManifest(moduleDir)
if err != nil {
return err
}
services, err := validateServiceInventory(moduleDir, manifest.Services)
if err != nil {
return err
}
topology, err := loadDeploymentTopology(moduleDir, manifest.Name, services)
if err != nil {
return err
}
environments, err := selectEnvironments(workspace)
if err != nil {
return err
}
root := filepath.Join(moduleDir, filepath.FromSlash(bundleRelativeDir))
if err := os.MkdirAll(filepath.Dir(root), 0o755); err != nil {
return fmt.Errorf("create deployment directory: %w", err)
}
stage, err := os.MkdirTemp(filepath.Dir(root), ".kustomize-stage-*")
if err != nil {
return fmt.Errorf("create bundle staging directory: %w", err)
}
defer func() { _ = os.RemoveAll(stage) }()
bundle := moduleBundle{
SchemaVersion: moduleBundleSchema,
Module: manifest.Name,
Namespace: topology.Module.Namespace,
ServiceEntry: topology.Module.ServiceEntry,
}
for _, environment := range environments {
_, aws, kind, err := classifyEnvironment(environment)
if err != nil {
return err
}
plan, err := planEnvironment(environment, serviceNames(services), topology, kind, aws)
if err != nil {
return err
}
if err := renderEnvironment(stage, workspace.Name, manifest.Name, topology, plan); err != nil {
return err
}
bundle.Environments = append(bundle.Environments, bundleEnvironment{
Name: plan.environment.Name,
Namespace: plan.environment.Namespace,
Cluster: plan.cluster,
ResourcePath: path.Join("overlays", plan.environment.Name),
Services: append([]string(nil), plan.services...),
Ingress: bundleIngress(plan.ingress),
ManagedServiceHandoffs: append([]managedServiceHandoff(nil), plan.handoffs...),
})
}
if err := writeJSON(filepath.Join(stage, "bundle.json"), bundle); err != nil {
return err
}
if err := validateGeneratedBundle(stage, bundle); err != nil {
return err
}
return replaceGeneratedTree(stage, root)
}
func bundleIngress(routes []ingressRoutePlan) []bundleIngressRoute {
result := make([]bundleIngressRoute, 0, len(routes))
for _, route := range routes {
result = append(result, bundleIngressRoute{
Name: route.name,
Service: route.service,
Endpoint: route.endpoint,
Port: route.port,
Hosts: append([]string(nil), route.hosts...),
})
}
return result
}
func replaceGeneratedTree(stage, root string) error {
if _, err := os.Lstat(root); errors.Is(err, os.ErrNotExist) {
if err := os.Rename(stage, root); err != nil {
return fmt.Errorf("install generated bundle directory: %w", err)
}
return nil
} else if err != nil {
return fmt.Errorf("inspect generated bundle directory: %w", err)
}
backup, err := os.MkdirTemp(filepath.Dir(root), ".kustomize-backup-*")
if err != nil {
return fmt.Errorf("create bundle backup path: %w", err)
}
if err := os.Remove(backup); err != nil {
return fmt.Errorf("prepare bundle backup path: %w", err)
}
if err := os.Rename(root, backup); err != nil {
return fmt.Errorf("back up generated bundle directory: %w", err)
}
if err := os.Rename(stage, root); err != nil {
if rollbackErr := os.Rename(backup, root); rollbackErr != nil {
return fmt.Errorf("install generated bundle directory: %w (rollback failed: %v; previous tree remains at %s)", err, rollbackErr, backup)
}
return fmt.Errorf("install generated bundle directory: %w", err)
}
if err := os.RemoveAll(backup); err != nil {
return fmt.Errorf("remove previous bundle directory: %w", err)
}
return nil
}
func loadModuleManifest(moduleDir string) (moduleManifest, error) {
data, err := os.ReadFile(filepath.Join(moduleDir, moduleYamlPath))
if err != nil {
return moduleManifest{}, fmt.Errorf("read %s: %w", moduleYamlPath, err)
}
var manifest moduleManifest
if err := yaml.Unmarshal(data, &manifest); err != nil {
return moduleManifest{}, fmt.Errorf("parse %s: %w", moduleYamlPath, err)
}
if err := validateDNSLabel("module name", manifest.Name); err != nil {
return moduleManifest{}, err
}
if len(manifest.Services) == 0 {
return moduleManifest{}, fmt.Errorf("module %q declares no services", manifest.Name)
}
return manifest, nil
}
func validateServiceInventory(moduleDir string, references []serviceReference) ([]serviceDefinition, error) {
declared := make(map[string]string, len(references))
declaredPaths := make(map[string]string, len(references))
services := make([]serviceDefinition, 0, len(references))
serviceRoot := filepath.Join(moduleDir, "services")
for _, reference := range references {
if err := validateDNSLabel("service name", reference.Name); err != nil {
return nil, err
}
if _, exists := declared[reference.Name]; exists {
return nil, fmt.Errorf("module declares service %q more than once", reference.Name)
}
servicePath := filepath.Join(serviceRoot, reference.Name)
displayPath := reference.Name
if reference.Path != nil {
override := *reference.Path
if strings.ContainsRune(override, '\x00') {
return nil, fmt.Errorf("service %q path contains NUL", reference.Name)
}
if filepath.IsAbs(override) {
servicePath = filepath.Clean(override)
displayPath = servicePath
} else {
relative, err := cleanRelativeFilesystemPath(override)
if err != nil {
return nil, fmt.Errorf("service %q path: %w", reference.Name, err)
}
servicePath = filepath.Join(serviceRoot, relative)
displayPath = filepath.ToSlash(relative)
}
}
canonicalPath, err := filepath.Abs(servicePath)
if err != nil {
return nil, fmt.Errorf("service %q path: %w", reference.Name, err)
}
if owner, exists := declaredPaths[canonicalPath]; exists {
return nil, fmt.Errorf("services %q and %q declare the same path %q", owner, reference.Name, displayPath)
}
declared[reference.Name] = canonicalPath
declaredPaths[canonicalPath] = reference.Name
services = append(services, serviceDefinition{name: reference.Name, directory: canonicalPath})
if !filepath.IsAbs(valueOrEmpty(reference.Path)) {
current := serviceRoot
relative, err := filepath.Rel(serviceRoot, canonicalPath)
if err != nil {
return nil, fmt.Errorf("service %q path: %w", reference.Name, err)
}
for _, element := range strings.Split(relative, string(filepath.Separator)) {
current = filepath.Join(current, element)
info, statErr := os.Lstat(current)
if statErr != nil {
return nil, fmt.Errorf("declared service %q path %q is missing: %w", reference.Name, displayPath, statErr)
}
if !info.IsDir() {
return nil, fmt.Errorf("declared service %q path %q is not a directory", reference.Name, displayPath)
}
}
} else {
info, statErr := os.Stat(canonicalPath)
if statErr != nil {
return nil, fmt.Errorf("declared service %q path %q is missing: %w", reference.Name, displayPath, statErr)
}
if !info.IsDir() {
return nil, fmt.Errorf("declared service %q path %q is not a directory", reference.Name, displayPath)
}
}
}
expectedPaths := make(map[string]struct{}, len(declared))
for _, absolute := range declared {
relative, err := filepath.Rel(serviceRoot, absolute)
if err == nil && filepath.IsLocal(relative) {
expectedPaths[relative] = struct{}{}
}
}
if _, err := os.Stat(serviceRoot); errors.Is(err, os.ErrNotExist) && len(expectedPaths) == 0 {
return services, nil
}
if err := filepath.WalkDir(serviceRoot, func(file string, entry os.DirEntry, err error) error {
if err != nil {
return err
}
if !entry.IsDir() || file == serviceRoot {
return nil
}
relative, err := filepath.Rel(serviceRoot, file)
if err != nil {
return err
}
if _, exists := expectedPaths[relative]; exists {
return filepath.SkipDir
}
prefix := relative + string(filepath.Separator)
for expected := range expectedPaths {
if strings.HasPrefix(expected, prefix) {
return nil
}
}
return fmt.Errorf("service path %q has no module service declaration", filepath.ToSlash(relative))
}); err != nil {
return nil, fmt.Errorf("validate service paths: %w", err)
}
return services, nil
}
func valueOrEmpty(value *string) string {
if value == nil {
return ""
}
return *value
}
func serviceNames(services []serviceDefinition) []string {
names := make([]string, 0, len(services))
for _, service := range services {
names = append(names, service.name)
}
return names
}
func selectEnvironments(workspace *workspaceManifest) ([]*environmentConfig, error) {
if err := validateDNSLabel("workspace name", workspace.Name); err != nil {
return nil, err
}
if len(workspace.Environments) == 0 {
return nil, fmt.Errorf("workspace %q declares no deployment environments", workspace.Name)
}
seen := make(map[string]struct{}, len(workspace.Environments))
for _, environment := range workspace.Environments {
if environment == nil {
return nil, fmt.Errorf("workspace contains an empty environment")
}
if err := validateDNSLabel("environment name", environment.Name); err != nil {
return nil, err
}
if _, exists := seen[environment.Name]; exists {
return nil, fmt.Errorf("workspace declares environment %q more than once", environment.Name)
}
seen[environment.Name] = struct{}{}
if err := validateDNSLabel("environment namespace", environment.Namespace); err != nil {
return nil, fmt.Errorf("environment %q: %w", environment.Name, err)
}
}
return workspace.Environments, nil
}
func planEnvironment(
environment *environmentConfig,
services []string,
topology deploymentTopology,
cluster string,
aws bool,
) (environmentPlan, error) {
plan := environmentPlan{
environment: environment,
cluster: cluster,
managed: make(map[string]managedServiceConfig),
}
if err := validateManagedServices(environment, services, topology, aws, &plan); err != nil {
return environmentPlan{}, err
}
for _, service := range services {
if _, managed := plan.managed[service]; !managed {
plan.services = append(plan.services, service)
}
}
slices.Sort(plan.services)
if err := validateIngressRoutes(environment, topology, &plan); err != nil {
return environmentPlan{}, err
}
return plan, nil
}
func validateIngressRoutes(
environment *environmentConfig,
topology deploymentTopology,
plan *environmentPlan,
) error {
// Public ingress is optional: an environment may front the mesh with a
// gateway this module does not own, or expose nothing publicly yet. Such an
// environment renders module-owned baseline resources without a Gateway.
if len(environment.Ingress) == 0 {
return nil
}
routeNames := make(map[string]struct{}, len(environment.Ingress))
hosts := make(map[string]string)
for _, route := range environment.Ingress {
if err := validateDNSLabel("ingress route name", route.Name); err != nil {
return fmt.Errorf("environment %q: %w", environment.Name, err)
}
if _, duplicate := routeNames[route.Name]; duplicate {
return fmt.Errorf("environment %q repeats ingress route %q", environment.Name, route.Name)
}
routeNames[route.Name] = struct{}{}
if !slices.Contains(plan.services, route.Service) {
return fmt.Errorf(
"environment %q ingress route %q targets service %q outside its in-cluster inventory",
environment.Name,
route.Name,
route.Service,
)
}
service, exists := topologyServiceByName(topology, route.Service)
if !exists {
return fmt.Errorf(
"environment %q ingress route %q targets unknown service %q",
environment.Name,
route.Name,
route.Service,
)
}
endpoint, exists := topologyEndpointByName(service, route.Endpoint)
if !exists || !topologyExposesPublicEndpoint(topology, route.Service, route.Endpoint) {
return fmt.Errorf(
"environment %q ingress route %q target %s/%s is not a public module interface",
environment.Name,
route.Name,
route.Service,
route.Endpoint,
)
}
if len(route.Hosts) == 0 {
return fmt.Errorf("environment %q ingress route %q declares no exact hosts", environment.Name, route.Name)
}
planned := ingressRoutePlan{
name: route.Name,
service: route.Service,
endpoint: route.Endpoint,
port: endpoint.Port,
}
for _, host := range route.Hosts {
host = strings.TrimSpace(host)
if !validExternalName(host) {
return fmt.Errorf(
"environment %q ingress route %q host %q is not an exact DNS name",
environment.Name,
route.Name,
host,
)
}
if owner, duplicate := hosts[host]; duplicate {
return fmt.Errorf(
"environment %q ingress host %q is declared by routes %q and %q",
environment.Name,
host,
owner,
route.Name,
)
}
hosts[host] = route.Name
planned.hosts = append(planned.hosts, host)
}
plan.ingress = append(plan.ingress, planned)
}
return nil
}
func topologyExposesPublicEndpoint(topology deploymentTopology, service, endpoint string) bool {
return slices.ContainsFunc(topology.Interface, func(exposed topologyInterface) bool {
return exposed.Service == service &&
exposed.Endpoint == endpoint &&
exposed.Visibility == "public"
})
}
func validateManagedServices(
environment *environmentConfig,
services []string,
topology deploymentTopology,
aws bool,
plan *environmentPlan,
) error {
if !aws && len(environment.ManagedServices) > 0 {
return fmt.Errorf("environment %q declares managed services for an in-cluster environment", environment.Name)
}
declared := make(map[string]struct{}, len(services))
for _, service := range services {
declared[service] = struct{}{}
}
for service, config := range environment.ManagedServices {
_, exists := declared[service]
if !exists {
return fmt.Errorf("environment %q declares unexpected managed service %q", environment.Name, service)
}
switch config.Kind {
case "elasticache", "rds-postgresql", "s3", "secrets-manager":
default:
return fmt.Errorf("environment %q managed service %q kind %q is not supported", environment.Name, service, config.Kind)
}
if !validExternalName(config.ExternalName) {
return fmt.Errorf("environment %q managed service %q external-name %q is not an exact DNS name", environment.Name, service, config.ExternalName)
}
for _, cidr := range config.EgressCIDRs {
if _, _, err := net.ParseCIDR(cidr); err != nil {
return fmt.Errorf("environment %q managed service %q egress CIDR %q is invalid", environment.Name, service, cidr)
}
}
referenceNames := make(map[string]struct{}, len(config.SecretReferences))
handoff := managedServiceHandoff{
Service: service,
AWSKind: config.Kind,
ExternalName: config.ExternalName,
}
for _, reference := range config.SecretReferences {
if err := validateDNSLabel("managed secret reference name", reference.Name); err != nil {
return fmt.Errorf("environment %q managed service %q: %w", environment.Name, service, err)
}
if _, duplicate := referenceNames[reference.Name]; duplicate {
return fmt.Errorf("environment %q managed service %q repeats secret reference %q", environment.Name, service, reference.Name)
}
referenceNames[reference.Name] = struct{}{}
if strings.TrimSpace(reference.RemoteKey) == "" ||
strings.ContainsAny(reference.RemoteKey, "\r\n") ||
strings.TrimSpace(reference.SecretStore.Name) == "" ||
(reference.SecretStore.Kind != "SecretStore" && reference.SecretStore.Kind != "ClusterSecretStore") {
return fmt.Errorf("environment %q managed service %q secret reference %q is incomplete", environment.Name, service, reference.Name)
}
handoff.SecretReferences = append(handoff.SecretReferences, reference.Name)
}
plan.managed[service] = config
plan.handoffs = append(plan.handoffs, handoff)
}
slices.SortFunc(plan.handoffs, func(left, right managedServiceHandoff) int {
return strings.Compare(left.Service, right.Service)
})
return validateManagedDependencyCIDRs(environment.Name, topology, plan.managed)
}
func validateManagedDependencyCIDRs(environment string, topology deploymentTopology, managed map[string]managedServiceConfig) error {
for _, service := range topology.Services {
for _, dependency := range service.Dependencies {
config, exists := managed[dependency.Service]
if exists && len(config.EgressCIDRs) == 0 {
return fmt.Errorf(
"environment %q managed service %q requires at least one exact egress CIDR for caller %q",
environment,
dependency.Service,
service.Name,
)
}
}
}
return nil
}
func validExternalName(value string) bool {
name := strings.TrimSuffix(strings.TrimSpace(value), ".")
if name == "" || net.ParseIP(name) != nil || len(name) > 253 {
return false
}
for _, label := range strings.Split(name, ".") {
if len(label) > 63 || !dnsLabelPattern.MatchString(label) {
return false
}
}
return true
}
func classifyEnvironment(environment *environmentConfig) (local bool, aws bool, cluster string, err error) {
kind := strings.TrimSpace(environment.Cluster.Kind)
switch kind {
case "k3d":
return true, false, kind, nil
case "eks":
return false, true, kind, nil
case "":
if strings.HasPrefix(environment.Name, "local") {
return true, false, "k3d", nil
}
}
return false, false, "", fmt.Errorf("environment %q cluster kind %q is not supported by the SaaS deployment generator", environment.Name, kind)
}
func renderEnvironment(
root,
workspaceName,
moduleName string,
topology deploymentTopology,
plan environmentPlan,
) error {
environmentRoot := filepath.Join(root, "overlays", plan.environment.Name)
resourceRoot := filepath.Join(environmentRoot, "resources")
if err := os.MkdirAll(resourceRoot, 0o755); err != nil {
return err
}
identityLabels := map[string]string{
"app.kubernetes.io/managed-by": "codefly",
"app.kubernetes.io/part-of": kubernetesName(workspaceName, moduleName),
"codefly.dev/workspace": workspaceName,
"codefly.dev/module": moduleName,
"codefly.dev/environment": plan.environment.Name,
}
namespace := kubeObject{
APIVersion: "v1",
Kind: "Namespace",
Metadata: objectMeta{
Name: plan.environment.Namespace,
Labels: mergeLabels(identityLabels, map[string]string{
"istio.io/dataplane-mode": "ambient",
"pod-security.kubernetes.io/enforce": "baseline",
"pod-security.kubernetes.io/enforce-version": "latest",
"pod-security.kubernetes.io/audit": "restricted",
"pod-security.kubernetes.io/audit-version": "latest",
"pod-security.kubernetes.io/warn": "restricted",
"pod-security.kubernetes.io/warn-version": "latest",
"kubernetes.io/metadata.name": plan.environment.Namespace,
}),
},
}
if err := writeYAML(filepath.Join(resourceRoot, "namespace.yaml"), namespace); err != nil {
return err
}
sharedPaths, err := renderSharedResources(resourceRoot, plan.environment.Namespace, identityLabels, topology, plan)
if err != nil {
return err
}
resourcePaths := []string{
"resources/namespace.yaml",
"resources/resource-quota.yaml",
"resources/limit-range.yaml",
}
resourcePaths = append(resourcePaths, sharedPaths...)
if err := writeYAML(filepath.Join(environmentRoot, "kustomization.yaml"), kustomization{
APIVersion: "kustomize.config.k8s.io/v1beta1",
Kind: "Kustomization",
Resources: resourcePaths,
}); err != nil {
return err
}
return nil
}
func renderSharedResources(
root,
namespace string,
labels map[string]string,
topology deploymentTopology,
plan environmentPlan,
) ([]string, error) {
name := labels["app.kubernetes.io/part-of"]
quota := kubeObject{
APIVersion: "v1",
Kind: "ResourceQuota",
Metadata: objectMeta{Name: name, Namespace: namespace, Labels: labels},
Spec: map[string]any{"hard": map[string]string{
"configmaps": "60",
"limits.cpu": "16",
"limits.memory": "32Gi",
"persistentvolumeclaims": "20",
"pods": "60",
"requests.cpu": "8",
"requests.memory": "16Gi",
"requests.storage": "100Gi",
"secrets": "60",
"services": "30",
}},
}
if err := writeYAML(filepath.Join(root, "resource-quota.yaml"), quota); err != nil {
return nil, err
}
limit := kubeObject{
APIVersion: "v1",
Kind: "LimitRange",
Metadata: objectMeta{Name: name, Namespace: namespace, Labels: labels},
Spec: map[string]any{"limits": []any{
map[string]any{
"type": "Container",
"default": map[string]string{"cpu": "500m", "memory": "512Mi"},
"defaultRequest": map[string]string{"cpu": "100m", "memory": "128Mi"},
"max": map[string]string{"cpu": "4", "memory": "8Gi"},
"min": map[string]string{"cpu": "10m", "memory": "16Mi"},
},
map[string]any{
"type": "PersistentVolumeClaim",
"max": map[string]string{"storage": "50Gi"},
"min": map[string]string{"storage": "1Gi"},
},
}},
}
if err := writeYAML(filepath.Join(root, "limit-range.yaml"), limit); err != nil {
return nil, err
}
networkPolicies, err := topologyNetworkPolicies(topology, plan, namespace, labels)
if err != nil {
return nil, err
}
if err := writeYAMLDocuments(filepath.Join(root, "network-policy.yaml"), networkPolicies); err != nil {
return nil, err
}
istio, gateway, err := topologyIstioResources(topology, plan, namespace, labels)
if err != nil {
return nil, err
}
if err := writeYAMLDocuments(filepath.Join(root, "istio-mtls.yaml"), istio); err != nil {
return nil, err
}
paths := []string{"resources/network-policy.yaml", "resources/istio-mtls.yaml"}
if len(gateway) > 0 {
if err := writeYAMLDocuments(filepath.Join(root, "istio-gateway.yaml"), gateway); err != nil {
return nil, err
}
paths = append(paths, "resources/istio-gateway.yaml")
}
handoffPaths, err := renderManagedServiceHandoffs(root, namespace, labels, topology, plan)
if err != nil {
return nil, err
}
paths = append(paths, handoffPaths...)
return paths, nil
}
func topologyIstioResources(
topology deploymentTopology,
plan environmentPlan,
namespace string,
labels map[string]string,
) ([]kubeObject, []kubeObject, error) {
name := labels["app.kubernetes.io/part-of"]
istio := []kubeObject{
{
APIVersion: "security.istio.io/v1",
Kind: "PeerAuthentication",
Metadata: objectMeta{Name: name + "-mtls", Namespace: namespace, Labels: labels},
Spec: map[string]any{"mtls": map[string]string{"mode": "STRICT"}},
},
{
APIVersion: "security.istio.io/v1",
Kind: "AuthorizationPolicy",
Metadata: objectMeta{Name: "default-deny", Namespace: namespace, Labels: labels},
Spec: map[string]any{},
},
}
istio = append(istio, topologyInternalAuthorizationPolicies(topology, plan, namespace, labels)...)
if len(plan.ingress) == 0 {
// No public ingress: emit the mTLS baseline only, no Gateway.
return istio, nil, nil
}
ingressPorts := make(map[string]map[uint32]struct{})
for _, route := range plan.ingress {
if ingressPorts[route.service] == nil {
ingressPorts[route.service] = make(map[uint32]struct{})
}
ingressPorts[route.service][route.port] = struct{}{}
}
ingressServices := make([]string, 0, len(ingressPorts))
for service := range ingressPorts {
ingressServices = append(ingressServices, service)
}
slices.Sort(ingressServices)
for _, service := range ingressServices {
ports := make([]uint32, 0, len(ingressPorts[service]))
for port := range ingressPorts[service] {
ports = append(ports, port)
}
slices.Sort(ports)
renderedPorts := make([]string, 0, len(ports))
for _, port := range ports {
renderedPorts = append(renderedPorts, strconv.FormatUint(uint64(port), 10))
}
istio = append(istio, kubeObject{
APIVersion: "security.istio.io/v1",
Kind: "AuthorizationPolicy",
Metadata: objectMeta{
Name: "allow-istio-ingress-to-" + service,
Namespace: namespace,
Labels: labels,
},
Spec: map[string]any{
"selector": map[string]any{"matchLabels": map[string]string{"app": service}},
"rules": []any{map[string]any{
"from": []any{map[string]any{"source": map[string]any{
"principals": []string{"cluster.local/ns/istio-system/sa/istio-ingressgateway-service-account"},
}}},
"to": []any{map[string]any{"operation": map[string]any{
"ports": renderedPorts,
}}},
}},
},
})
}
gatewayHosts := []string{"*"}
var httpRoutes []any
if len(plan.ingress[0].hosts) == 0 {
route := plan.ingress[0]
httpRoutes = []any{map[string]any{
"name": route.name,
"match": []any{map[string]any{"uri": map[string]string{"prefix": "/"}}},
"route": []any{map[string]any{"destination": map[string]any{
"host": route.service + "." + namespace + ".svc.cluster.local",
"port": map[string]any{"number": route.port},
}}},
"timeout": "30s",
}}
} else {
gatewayHosts = nil
hostSet := make(map[string]struct{})
for _, route := range plan.ingress {
matches := make([]any, 0, len(route.hosts))
for _, host := range route.hosts {
if _, exists := hostSet[host]; !exists {
hostSet[host] = struct{}{}
gatewayHosts = append(gatewayHosts, host)
}
matches = append(matches, map[string]any{
"authority": map[string]string{
"regex": "^" + regexp.QuoteMeta(host) + "(:[0-9]+)?$",
},
})
}
httpRoutes = append(httpRoutes, map[string]any{
"name": route.name,
"match": matches,
"route": []any{map[string]any{"destination": map[string]any{
"host": route.service + "." + namespace + ".svc.cluster.local",
"port": map[string]any{"number": route.port},
}}},
"timeout": "30s",
})
}
slices.Sort(gatewayHosts)
}
gatewayName := topology.Module.Name
gateway := []kubeObject{
{
APIVersion: "networking.istio.io/v1",
Kind: "Gateway",
Metadata: objectMeta{Name: gatewayName, Namespace: namespace, Labels: labels},
Spec: map[string]any{
"selector": map[string]string{"istio": "ingressgateway"},
"servers": []any{map[string]any{