Repository navigation
Expand file tree
/
Copy pathgitops.go
More file actions
2963 lines (2834 loc) · 113 KB
/
Copy pathgitops.go
File metadata and controls
2963 lines (2834 loc) · 113 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[^>]*>`)
// A Cloud SQL instance is addressed by project:region:instance, which is not
// a DNS name, so it travels beside the ExternalName rather than inside it.
// The optional leading segment is the legacy domain-scoped project form
// (example.com:project:region:instance) that older organizations still carry.
instanceConnectionPattern = regexp.MustCompile(`^(?:[a-z0-9](?:[-a-z0-9]*[a-z0-9])?(?:\.[a-z0-9](?:[-a-z0-9]*[a-z0-9])?)+:)?[a-z][-a-z0-9]{4,28}[a-z0-9]:[a-z0-9]+(?:-[a-z0-9]+)*:[a-z](?:[-a-z0-9]{0,96}[a-z0-9])?$`)
)
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"`
// KeyService is which key service holds this environment's keys, in the
// same vocabulary the `key-service` configuration group's
// KEY_SERVICE_BACKEND uses. It decides whether this module composes a Vault
// here at all. Unstated means `vault`; resolveKeyService says why that is a
// default rather than a refusal, and what has to change for it to become
// one.
KeyService string `yaml:"key-service,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"`
DeployJobs []bundleDeployJob `json:"deployJobs,omitempty"`
}
// bundleDeployJob is a store-writing one-shot the promotion driver runs against
// a dependency's store after that dependency's own bring-up. Unlike a service's
// self-serving bootstrap Job (bootstrap_job_endpoints, which reaches the
// service's own endpoints), it runs one service's image but writes to a
// dependency it declares — carrying the generated artifact and the target the
// driver mounts and connects. The driver schedules it after the target's
// migration and fails the promotion if it exits non-zero.
type bundleDeployJob struct {
Name string `json:"name"`
Service string `json:"service"`
Command string `json:"command"`
Catalog string `json:"catalog"`
Force bool `json:"force,omitempty"`
Writes bundleDeployTarget `json:"writes"`
After []string `json:"after,omitempty"`
}
type bundleDeployTarget struct {
Service string `json:"service"`
Endpoint string `json:"endpoint"`
Port uint32 `json:"port"`
}
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"`
Kind string `json:"kind"`
ExternalName string `json:"externalName"`
AuthMode string `json:"authMode,omitempty"`
// EgressNamespace is the in-cluster namespace that holds this dependency,
// set only for a kind the cell runs inside the same cluster. It is what the
// caller's egress policy selects on; such a dependency has no stable address
// to write a CIDR for, and the pod CIDR would authorize the whole cluster.
EgressNamespace string `json:"egressNamespace,omitempty"`
InstanceConnectionName string `json:"instanceConnectionName,omitempty"`
SecretReferences []string `json:"secretReferences,omitempty"`
}
// UnmarshalJSON reads the handoff kind from "kind", falling back to the legacy
// "awsKind" key so bundles written before the rename still parse. Drop the
// fallback once every producer emits "kind".
func (h *managedServiceHandoff) UnmarshalJSON(data []byte) error {
type alias managedServiceHandoff
aux := struct {
*alias
LegacyAWSKind string `json:"awsKind"`
}{alias: (*alias)(h)}
if err := json.Unmarshal(data, &aux); err != nil {
return err
}
if h.Kind == "" {
h.Kind = aux.LegacyAWSKind
}
return nil
}
type managedServiceConfig struct {
Kind string `yaml:"kind"`
ExternalName string `yaml:"external-name"`
AuthMode string `yaml:"auth-mode,omitempty"`
InstanceConnectionName string `yaml:"instance-connection-name,omitempty"`
EgressCIDRs []string `yaml:"egress-cidrs,omitempty"`
EgressNamespace string `yaml:"egress-namespace,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"`
Namespace string `yaml:"namespace,omitempty"`
Resources []string `yaml:"resources"`
}
type environmentPlan struct {
environment *environmentConfig
cluster string
services []string
ingress []ingressRoutePlan
handoffs []managedServiceHandoff
managed map[string]managedServiceConfig
// keyService is the resolved `key-service` selection for this environment.
keyService string
// withdrawn holds the services this environment's key-service selection
// takes OUT of the composition: not an in-cluster workload, and not a
// managed dependency either — nothing reaches them, so every edge to one is
// dropped rather than needing a handoff. It is a third state beside
// in-cluster and managed, and it exists because "the keys are in the cell's
// cloud key service" names nothing for a handoff to point at.
withdrawn map[string]struct{}
}
type ingressRoutePlan struct {
name string
service string
endpoint string
// port is the pod port the ingress gateway's traffic arrives on (what the
// AuthorizationPolicy and NetworkPolicy match); servicePort is the
// Kubernetes Service port the VirtualService routes to.
port uint32
servicePort uint32
hosts []string
}
type deploymentTopology struct {
Version string `yaml:"version"`
Module topologyModule `yaml:"module"`
Interface []topologyInterface `yaml:"interface"`
Services []topologyService `yaml:"services"`
DeployJobs []topologyDeployJob `yaml:"deploy_jobs,omitempty"`
// internalMethodPaths holds, per service, the gRPC method paths marked
// EXPOSURE_INTERNAL in that service's generated authorization catalog. It is
// populated after decoding and drives the mesh reach gate for the internal
// authority surface.
internalMethodPaths map[string][]string
}
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"`
Kubernetes *topologyKubernetesIdentity `yaml:"kubernetes,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"`
InternalHTTPRoutes []topologyInternalHTTPRoute `yaml:"internal_http_routes,omitempty"`
PublicEgressPorts []uint32 `yaml:"public_egress_ports,omitempty"`
Spec map[string]any `yaml:"spec,omitempty"`
}
// topologyInternalHTTPRoute is an HTTP route carrying cluster-internal
// authority on a port that also serves browser-facing traffic. Path and method
// are the only thing separating the two, so it is authored rather than derived.
type topologyInternalHTTPRoute struct {
Path string `yaml:"path"`
Methods []string `yaml:"methods"`
}
type topologyKubernetesIdentity struct {
ServiceName string `yaml:"service-name"`
AppLabel string `yaml:"app-label"`
}
type topologySecretServiceConfiguration struct {
Name string `yaml:"name"`
Entries []topologySecretServiceConfigurationEntry `yaml:"entries"`
}
type topologySecretServiceConfigurationEntry struct {
Key string `yaml:"key"`
}
// topologyEndpoint carries both of an endpoint's ports. Port is the pod port
// the process binds — what a NetworkPolicy and an Istio AuthorizationPolicy
// match. ServicePort is the Kubernetes Service port Codefly's render allocates
// (network.DeployedEndpointPorts) — what a VirtualService destination names.
type topologyEndpoint struct {
Name string `yaml:"name"`
API string `yaml:"api,omitempty"`
Visibility string `yaml:"visibility"`
Port uint32 `yaml:"port"`
ServicePort uint32 `yaml:"service_port"`
}
type topologyDependency struct {
Service string `yaml:"service"`
Endpoints []string `yaml:"endpoints"`
}
// topologyDeployJob declares a store-writing one-shot the promotion driver runs
// as a deploy step. It runs Service's image but writes to a dependency's
// endpoint (Writes) rather than serving its own — the boundary a self-serving
// bootstrap_job_endpoints Job cannot express — consuming the generated Catalog
// artifact. Force selects the importer's authoritative-catalog semantics: the
// generated catalog is base-tracked and only changes through contribution →
// regeneration, so a removal in it is intentional and applied past the
// truncation guard.
type topologyDeployJob struct {
Name string `yaml:"name"`
Service string `yaml:"service"`
Command string `yaml:"command"`
Catalog string `yaml:"catalog"`
Force bool `yaml:"force,omitempty"`
Writes topologyDeployJobTarget `yaml:"writes"`
After []string `yaml:"after,omitempty"`
}
type topologyDeployJobTarget struct {
Service string `yaml:"service"`
Endpoint string `yaml:"endpoint"`
}
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 {
_, managed, kind, err := classifyEnvironment(environment)
if err != nil {
return err
}
plan, err := planEnvironment(environment, serviceNames(services), topology, kind, managed)
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...),
DeployJobs: planDeployJobs(topology, plan),
})
}
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
}
// planDeployJobs records the deploy Jobs the promotion driver must run for this
// environment: those whose running service is in-cluster and whose write target
// is reachable (in-cluster or a managed handoff). Each carries the generated
// catalog artifact and the resolved target endpoint so the driver mounts the
// document and connects the store without consulting the topology itself.
func planDeployJobs(topology deploymentTopology, plan environmentPlan) []bundleDeployJob {
inCluster := make(map[string]struct{}, len(plan.services))
for _, service := range plan.services {
inCluster[service] = struct{}{}
}
jobs := make([]bundleDeployJob, 0, len(topology.DeployJobs))
for _, job := range topology.DeployJobs {
if _, exists := inCluster[job.Service]; !exists {
continue
}
_, targetInCluster := inCluster[job.Writes.Service]
_, targetManaged := plan.managed[job.Writes.Service]
if !targetInCluster && !targetManaged {
continue
}
target, _ := topologyServiceByName(topology, job.Writes.Service)
endpoint, _ := topologyEndpointByName(target, job.Writes.Endpoint)
jobs = append(jobs, bundleDeployJob{
Name: job.Name,
Service: job.Service,
Command: job.Command,
Catalog: job.Catalog,
Force: job.Force,
Writes: bundleDeployTarget{
Service: job.Writes.Service,
Endpoint: job.Writes.Endpoint,
Port: endpoint.Port,
},
After: append([]string(nil), job.After...),
})
}
if len(jobs) == 0 {
return nil
}
return jobs
}
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,
managedCapable bool,
) (environmentPlan, error) {
plan := environmentPlan{
environment: environment,
cluster: cluster,
managed: make(map[string]managedServiceConfig),
}
keyService, withdrawn, err := resolveKeyService(environment, services)
if err != nil {
return environmentPlan{}, err
}
plan.keyService, plan.withdrawn = keyService, withdrawn
if err := validateManagedServices(environment, services, topology, managedCapable, &plan); err != nil {
return environmentPlan{}, err
}
for _, service := range services {
if _, managed := plan.managed[service]; managed {
continue
}
if _, gone := plan.withdrawn[service]; gone {
continue
}
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,
servicePort: endpoint.ServicePort,
}
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,
managedCapable bool,
plan *environmentPlan,
) error {
if !managedCapable && 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)
}
// A withdrawn service is not an in-cluster workload AND not something a
// handoff can point at: the selection that withdrew it says the keys are
// in the cell's cloud key service, so there is no Vault to name an
// ExternalName for. Accepting both would render reach to an address
// nothing dials and leave the reader unable to say which declaration won.
if _, gone := plan.withdrawn[service]; gone {
return fmt.Errorf(
"environment %q declares both key-service: %s and a managed service %q: the selection means the keys are in the cell's cloud key-management service, so there is no Vault for a handoff to point at — declare key-service: %s with the %q handoff, or key-service: %s with neither",
environment.Name, plan.keyService, service, keyServiceVault, managedKindCellVault, keyServiceKMS)
}
switch config.Kind {
case "elasticache", "rds-postgresql", "s3", "secrets-manager", "azure-postgres-flexible", "cloud-sql-postgres", managedKindCellVault:
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)
}
authMode, instanceConnection, err := validateManagedAuth(environment.Name, service, config)
if err != nil {
return err
}
egressNamespace, err := validateManagedEgress(environment.Name, service, config)
if err != nil {
return err
}
// Store what was validated rather than what was written: the renderer and
// the bundle both read these back, so a padded or defaulted spelling must
// not survive past the one place that checked it.
config.AuthMode = authMode
config.InstanceConnectionName = instanceConnection
config.EgressNamespace = egressNamespace
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,
Kind: config.Kind,
ExternalName: config.ExternalName,
EgressNamespace: egressNamespace,
InstanceConnectionName: instanceConnection,
}
// Only a non-default mode earns a key: every consumer already reads an
// absent authMode as the password-backed shape, so emitting it for the
// default would rewrite every existing handoff to say what it already said.
if authMode != "password" {
handoff.AuthMode = authMode
}
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)
}
// The key services an environment may select, spelled exactly as
// KEY_SERVICE_BACKEND spells them in the `key-service` configuration group
// (module/configurations/local/key-service.env), so one word means one thing on
// both sides of the deployment.
const (
keyServiceVault = "vault"
keyServiceKMS = "kms"
)
// keyServiceVaultService is the service this module composes to BE the `vault`
// key service. It is the only service a key-service selection withdraws, and it
// is named here rather than discovered because the relationship runs the other
// way: the service exists to serve that selection.
const keyServiceVaultService = "vault"
// keyServiceGroup is the workspace-configuration group the `vault` key service
// is REACHED through: the address, the auth method, the AppRole mount and, in
// its secret half, the credential that uses them.
//
// It is named beside the service rather than derived from it because the two
// are different facts about the same selection, and only one of them governs
// the group. A group is required by the BACKEND an environment selected — it is
// how a process reaches that backend — not by whether a workload of the same
// name happens to be in the inventory. The two coincide for this module, which
// is exactly why keying the group off the service read as correct while being
// the wrong owner: a cell that selects the cloud key service and still composes
// a Vault for something else would have kept a binding nothing uses, and a cell
// that selects the vault backend from a Vault the CELL runs — composed here as
// a managed cell-vault — must keep the group though no Vault of this module's
// is ever rendered.
const keyServiceGroup = "vault"
// resolveKeyService answers, for one environment, which key service holds its
// keys — and therefore whether this module composes a Vault here.
//
// WHY THIS IS A MANIFEST FACT AND NOT A CONFIGURATION READ. accounts selects its
// backend at runtime from the `key-service` group, and on
// KEY_SERVICE_BACKEND=kms with KEY_SERVICE_SIGNING_BACKEND=kms-wrapped it opens
// no Vault connection at all (services/accounts/code/pkg/keyservice/load.go:
// the Vault binding is built only by the `vault` sealer, and the wrapped signing
// key is unwrapped from configuration). The INVENTORY, though, is decided here,
// before any process exists: what is rendered, scheduled and given a volume.
// Those two planes had no declaration in common, so a cell whose keys live in
// Cloud KMS still got a Vault StatefulSet — rendered, scheduled, refusing to
// start without the auto-unseal seal it is forbidden to hold, and crash-looping
// as a permanently degraded workload that nothing reads.
//
// The renderer could have read the group's .env instead. It must not: a group's
// values are the configuration plane's to deliver per environment, the renderer
// has never read one, and a file that may legitimately be absent would make the
// render fall back to composing a Vault — which is exactly the failure. So the
// selection is DECLARED on the environment, where the inventory is decided.
//
// AN UNSTATED SELECTION IS ANSWERED BY THE INVENTORY, which is the other
// declaration a composition makes about this module's Vault and the only one it
// can write today: composing the `vault` service selects the vault backend,
// composing none selects the cell's cloud key service. That keeps the inventory
// a SOURCE of the selection while the selection alone decides what follows from
// it — which workloads are rendered, which edges exist, and which configuration
// group is declared. On a deployed environment an unstated selection should be
// refused outright, exactly as `keyservice.selectedBackend` refuses the same
// unstated fact at boot. It is not refused yet, and the reason is a tooling gap
// rather than a judgement:
//
// THE ENVIRONMENT BLOCK'S SCHEMA IS NOT THIS MODULE'S. `workspace.codefly.yaml`
// is parsed by the CLI's own `pkg/environments.Environment`, strictly and
// recursively, and that type has no extension seam — core's
// `resources.Environment` has an inline `Extensions map[string]YAMLValue` for
// host-owned keys, but the CLI does not use it here. So until the CLI accepts
// `key-service`, a composition cannot write the line, and refusing an unstated
// selection would refuse every composition instead of the one mistake it is
// aimed at. Verified against codefly 0.1.181: the field is rejected with
// "field key-service not found in type environments.Environment", and so are
// the `auth-mode` and `egress-namespace` keys this module's own cell-vault
// handoff already documents.
//
// Making it required is therefore one line here plus the CLI's field; issue
// #1128 carries that. Everything else below is live now: a composition that
// composes no `vault` service at all selects the cloud key service by saying
// so in the inventory, which the CLI does parse, and the selection withdraws
// the workload and the `vault` configuration group with it.
//
// A local environment composes this module's own Vault, which is what `codefly
// run service --fixture dev-admin` reaches over loopback with a token, so the
// default is right there in any case.
func resolveKeyService(
environment *environmentConfig,
services []string,
) (string, map[string]struct{}, error) {
// Whether this composition has a Vault AT ALL. A cell that runs its own
// declares `vault` as a managed service of kind cell-vault, which
// validateManagedServices requires to be in the inventory too, so one