-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworkspaces.go
More file actions
1096 lines (994 loc) · 34.4 KB
/
Copy pathworkspaces.go
File metadata and controls
1096 lines (994 loc) · 34.4 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 kubeworkspaces
import (
"context"
"fmt"
"strings"
"time"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"github.com/kube-workspaces/api/gen/workspaces"
"github.com/kube-workspaces/api/internal/auth"
"github.com/kube-workspaces/api/internal/k8s"
"goa.design/clue/log"
)
// workspaces service implementation.
type workspacessrvc struct {
client *k8s.WorkspaceClient
imageClient *k8s.ImageClient
coreClient *k8s.CoreClient
podDefaultClient *k8s.PodDefaultClient
authProvider *auth.ConfigProvider
}
// NewWorkspaces returns the workspaces service implementation.
func NewWorkspaces(client *k8s.WorkspaceClient, imageClient *k8s.ImageClient, coreClient *k8s.CoreClient, authProvider *auth.ConfigProvider, podDefaultClient *k8s.PodDefaultClient) workspaces.Service {
return &workspacessrvc{client: client, imageClient: imageClient, coreClient: coreClient, authProvider: authProvider, podDefaultClient: podDefaultClient}
}
// List all workspaces
func (s *workspacessrvc) List(ctx context.Context, p *workspaces.ListPayload) (res []*workspaces.Workspace, err error) {
ns := p.Namespace
if ns == "_all" {
ns = ""
}
log.Printf(ctx, "workspaces.list namespace=%s", ns)
// If namespace access is restricted, filter to user's allowed namespaces
ns, err = s.resolveNamespace(ctx, ns)
if err != nil {
return []*workspaces.Workspace{}, nil
}
list, err := s.client.ListWorkspaces(ctx, ns)
if err != nil {
return nil, fmt.Errorf("failed to list workspaces: %w", err)
}
res = make([]*workspaces.Workspace, 0, len(list.Items))
for i := range list.Items {
ws := unstructuredToWorkspace(&list.Items[i])
res = append(res, ws)
}
// Filter results if listing across all namespaces
if p.Namespace == "_all" || p.Namespace == "" {
res = s.filterWorkspacesByAccess(ctx, res)
}
return res, nil
}
// resolveNamespace checks if the user has access to the requested namespace.
// Returns the namespace to query, or error if access denied.
func (s *workspacessrvc) resolveNamespace(ctx context.Context, ns string) (string, error) {
if !s.isNamespaceRestricted(ctx) {
return ns, nil
}
user := auth.UserFromContext(ctx)
if user == nil || user.Role == "admin" {
return ns, nil
}
// If a specific namespace is requested, verify access
if ns != "" {
if !auth.UserHasNamespaceAccess(user, ns) {
return "", fmt.Errorf("no access to namespace %s", ns)
}
}
return ns, nil
}
// filterWorkspacesByAccess filters workspaces to those in namespaces the user can access.
func (s *workspacessrvc) filterWorkspacesByAccess(ctx context.Context, items []*workspaces.Workspace) []*workspaces.Workspace {
if !s.isNamespaceRestricted(ctx) {
return items
}
user := auth.UserFromContext(ctx)
if user == nil || user.Role == "admin" {
return items
}
var filtered []*workspaces.Workspace
for _, ws := range items {
if auth.UserHasNamespaceAccess(user, ws.Namespace) {
filtered = append(filtered, ws)
}
}
if filtered == nil {
filtered = []*workspaces.Workspace{}
}
return filtered
}
// isNamespaceRestricted checks whether namespace access restriction is enabled.
func (s *workspacessrvc) isNamespaceRestricted(ctx context.Context) bool {
if s.authProvider == nil {
return false
}
cfg, err := s.authProvider.GetConfig(ctx)
if err != nil || cfg == nil {
return false
}
return cfg.Enabled && cfg.RestrictNamespaceAccess
}
// Get a workspace by name
func (s *workspacessrvc) Get(ctx context.Context, p *workspaces.GetPayload) (res *workspaces.Workspace, err error) {
log.Printf(ctx, "workspaces.get name=%s namespace=%s", p.Name, p.Namespace)
obj, err := s.client.GetWorkspace(ctx, p.Namespace, p.Name)
if err != nil {
return nil, workspaces.NotFound(fmt.Sprintf("workspace %s/%s not found", p.Namespace, p.Name))
}
return unstructuredToWorkspace(obj), nil
}
// Create a new workspace
func (s *workspacessrvc) Create(ctx context.Context, p *workspaces.CreateWorkspacePayload) (res *workspaces.Workspace, err error) {
log.Printf(ctx, "workspaces.create name=%s namespace=%s type=%s", p.Name, p.Namespace, p.Type)
// Validate per-type constraints. VM workspaces boot a containerDisk image
// via KubeVirt. GPU requests are supported: the requested GPU resource is
// recorded in the container limits and the controller translates it into a
// KubeVirt `domain.devices.gpus` passthrough device. shared_memory and
// volume mounts are still container-only and rejected for VMs.
if p.Type == "vm" {
if p.SharedMemory {
return nil, workspaces.Invalid("shared_memory is not supported for vm workspaces")
}
if len(p.VolumeMounts) > 0 {
return nil, workspaces.Invalid("volume_mounts are not supported for vm workspaces yet")
}
}
// Determine actor
actor := "unknown"
if user := auth.UserFromContext(ctx); user != nil {
actor = user.Email
}
// Build the Workspace CR
ws := buildWorkspaceCR(p, s.imageClient)
// Apply PodDefaults from the target namespace
if s.podDefaultClient != nil {
log.Printf(ctx, "workspaces.create: applying PodDefaults from namespace=%s", p.Namespace)
applyPodDefaults(ctx, ws, s.podDefaultClient, p.Namespace)
} else {
log.Printf(ctx, "workspaces.create: podDefaultClient is nil, skipping PodDefaults")
}
// Set action annotations on the CR before creation
annotations := ws.GetAnnotations()
if annotations == nil {
annotations = make(map[string]string)
}
annotations["kubeworkspaces.io/created-by"] = actor
annotations["kubeworkspaces.io/last-action"] = "Created"
annotations["kubeworkspaces.io/last-action-by"] = actor
annotations["kubeworkspaces.io/last-action-time"] = time.Now().UTC().Format(time.RFC3339)
ws.SetAnnotations(annotations)
created, err := s.client.CreateWorkspace(ctx, ws)
if err != nil {
return nil, fmt.Errorf("failed to create workspace: %w", err)
}
// Emit a Kubernetes Event for the action (best-effort)
if s.coreClient != nil {
msg := fmt.Sprintf("Workspace created by %s", actor)
if evErr := s.coreClient.CreateWorkspaceEvent(ctx, p.Namespace, p.Name, "Created", actor, msg); evErr != nil {
log.Printf(ctx, "warning: failed to emit workspace event: %v", evErr)
}
}
return unstructuredToWorkspace(created), nil
}
// Delete a workspace
func (s *workspacessrvc) Delete(ctx context.Context, p *workspaces.DeletePayload) (err error) {
log.Printf(ctx, "workspaces.delete name=%s namespace=%s", p.Name, p.Namespace)
err = s.client.DeleteWorkspace(ctx, p.Namespace, p.Name)
if err != nil {
return workspaces.NotFound(fmt.Sprintf("workspace %s/%s not found", p.Namespace, p.Name))
}
return nil
}
// Start a stopped workspace (removes the stopped annotation)
func (s *workspacessrvc) Start(ctx context.Context, p *workspaces.StartPayload) (res *workspaces.Workspace, err error) {
log.Printf(ctx, "workspaces.start name=%s namespace=%s", p.Name, p.Namespace)
// Determine actor
actor := "unknown"
if user := auth.UserFromContext(ctx); user != nil {
actor = user.Email
}
obj, err := s.client.GetWorkspace(ctx, p.Namespace, p.Name)
if err != nil {
return nil, workspaces.NotFound(fmt.Sprintf("workspace %s/%s not found", p.Namespace, p.Name))
}
// Remove the stopped annotation and set action annotations
annotations := obj.GetAnnotations()
if annotations == nil {
annotations = make(map[string]string)
}
delete(annotations, "kubeworkspaces.io/stopped")
annotations["kubeworkspaces.io/last-action"] = "Started"
annotations["kubeworkspaces.io/last-action-by"] = actor
annotations["kubeworkspaces.io/last-action-time"] = time.Now().UTC().Format(time.RFC3339)
obj.SetAnnotations(annotations)
updated, err := s.client.UpdateWorkspace(ctx, obj)
if err != nil {
return nil, fmt.Errorf("failed to start workspace: %w", err)
}
// Emit a Kubernetes Event for the action (best-effort)
if s.coreClient != nil {
msg := fmt.Sprintf("Workspace started by %s", actor)
if evErr := s.coreClient.CreateWorkspaceEvent(ctx, p.Namespace, p.Name, "Started", actor, msg); evErr != nil {
log.Printf(ctx, "warning: failed to emit workspace event: %v", evErr)
}
}
return unstructuredToWorkspace(updated), nil
}
// Stop a running workspace (adds the stopped annotation)
func (s *workspacessrvc) Stop(ctx context.Context, p *workspaces.StopPayload) (res *workspaces.Workspace, err error) {
log.Printf(ctx, "workspaces.stop name=%s namespace=%s", p.Name, p.Namespace)
// Determine actor
actor := "unknown"
if user := auth.UserFromContext(ctx); user != nil {
actor = user.Email
}
obj, err := s.client.GetWorkspace(ctx, p.Namespace, p.Name)
if err != nil {
return nil, workspaces.NotFound(fmt.Sprintf("workspace %s/%s not found", p.Namespace, p.Name))
}
// Add the stopped annotation and set action annotations
annotations := obj.GetAnnotations()
if annotations == nil {
annotations = make(map[string]string)
}
annotations["kubeworkspaces.io/stopped"] = "true"
annotations["kubeworkspaces.io/last-action"] = "Stopped"
annotations["kubeworkspaces.io/last-action-by"] = actor
annotations["kubeworkspaces.io/last-action-time"] = time.Now().UTC().Format(time.RFC3339)
obj.SetAnnotations(annotations)
updated, err := s.client.UpdateWorkspace(ctx, obj)
if err != nil {
return nil, fmt.Errorf("failed to stop workspace: %w", err)
}
// Emit a Kubernetes Event for the action (best-effort)
if s.coreClient != nil {
msg := fmt.Sprintf("Workspace stopped by %s", actor)
if evErr := s.coreClient.CreateWorkspaceEvent(ctx, p.Namespace, p.Name, "Stopped", actor, msg); evErr != nil {
log.Printf(ctx, "warning: failed to emit workspace event: %v", evErr)
}
}
return unstructuredToWorkspace(updated), nil
}
// Reset a workspace by re-provisioning it from its image. For vm workspaces the
// controller reacts to this by deleting the VirtualMachine (and with it the
// persistent root volume it owns) and recreating the workspace fresh, the
// equivalent of re-provisioning. The annotation value is a timestamp so each
// reset is unique and reliably triggers a reconcile.
func (s *workspacessrvc) Reset(ctx context.Context, p *workspaces.ResetPayload) (res *workspaces.Workspace, err error) {
log.Printf(ctx, "workspaces.reset name=%s namespace=%s", p.Name, p.Namespace)
// Determine actor
actor := "unknown"
if user := auth.UserFromContext(ctx); user != nil {
actor = user.Email
}
obj, err := s.client.GetWorkspace(ctx, p.Namespace, p.Name)
if err != nil {
return nil, workspaces.NotFound(fmt.Sprintf("workspace %s/%s not found", p.Namespace, p.Name))
}
// Reset re-provisions the workload's root storage. Today only vm
// workspaces back their root volume from an image, so anything else is a
// no-op and rejected up front rather than pretending it did something.
if wsType, _, _ := unstructured.NestedString(obj.Object, "spec", "type"); wsType != "vm" {
return nil, workspaces.Invalid(fmt.Sprintf("workspace %s/%s has type %q; only vm workspaces can be reset", p.Namespace, p.Name, wsType))
}
// Add the reset annotation and set action annotations
annotations := obj.GetAnnotations()
if annotations == nil {
annotations = make(map[string]string)
}
annotations["kubeworkspaces.io/reset"] = time.Now().UTC().Format(time.RFC3339Nano)
annotations["kubeworkspaces.io/last-action"] = "Reset"
annotations["kubeworkspaces.io/last-action-by"] = actor
annotations["kubeworkspaces.io/last-action-time"] = time.Now().UTC().Format(time.RFC3339)
obj.SetAnnotations(annotations)
updated, err := s.client.UpdateWorkspace(ctx, obj)
if err != nil {
return nil, fmt.Errorf("failed to reset workspace: %w", err)
}
// Emit a Kubernetes Event for the action (best-effort)
if s.coreClient != nil {
msg := fmt.Sprintf("Workspace reset (re-provisioned from image) by %s", actor)
if evErr := s.coreClient.CreateWorkspaceEvent(ctx, p.Namespace, p.Name, "Reset", actor, msg); evErr != nil {
log.Printf(ctx, "warning: failed to emit workspace event: %v", evErr)
}
}
return unstructuredToWorkspace(updated), nil
}
// Clone copies an existing workspace under a new name in the same namespace.
// The clone inherits the source workspace's spec, including volume mounts
// (which reference PVCs in the namespace). It does NOT copy the source's data
// volumes: the controller provisions a fresh workload, so the clone gets its
// own empty storage (and, for vm workspaces, a fresh root disk booted fresh
// from the image).
func (s *workspacessrvc) Clone(ctx context.Context, p *workspaces.ClonePayload) (res *workspaces.Workspace, err error) {
log.Printf(ctx, "workspaces.clone name=%s new_name=%s namespace=%s", p.Name, p.NewName, p.Namespace)
if p.NewName == p.Name {
return nil, workspaces.Invalid("new_name must differ from the source workspace name")
}
src, err := s.client.GetWorkspace(ctx, p.Namespace, p.Name)
if err != nil {
return nil, workspaces.NotFound(fmt.Sprintf("workspace %s/%s not found", p.Namespace, p.Name))
}
// Determine actor
actor := "unknown"
if user := auth.UserFromContext(ctx); user != nil {
actor = user.Email
}
clone := src.DeepCopy()
// Reset identity/metadata that belongs to the source object. Volume mounts
// referencing PVCs in the namespace are intentionally carried over.
clone.SetName(p.NewName)
clone.SetNamespace(p.Namespace)
clone.SetResourceVersion("")
clone.SetUID("")
clone.SetSelfLink("")
clone.SetGeneration(0)
clone.SetCreationTimestamp(metav1.Time{})
clone.SetManagedFields(nil)
clone.SetOwnerReferences(nil)
unstructured.RemoveNestedField(clone.Object, "status")
// Drop one-shot action triggers and the audit trail, carry over proxy
// annotations and the stopped marker, and stamp the clone lineage.
annotations := clone.GetAnnotations()
if annotations == nil {
annotations = make(map[string]string)
}
for _, a := range []string{
"kubeworkspaces.io/created-by",
"kubeworkspaces.io/last-action",
"kubeworkspaces.io/last-action-by",
"kubeworkspaces.io/last-action-time",
"kubeworkspaces.io/reset",
} {
delete(annotations, a)
}
annotations["kubeworkspaces.io/cloned-from"] = p.Name
annotations["kubeworkspaces.io/created-by"] = actor
annotations["kubeworkspaces.io/last-action"] = "Cloned"
annotations["kubeworkspaces.io/last-action-by"] = actor
annotations["kubeworkspaces.io/last-action-time"] = time.Now().UTC().Format(time.RFC3339)
clone.SetAnnotations(annotations)
// Apply optional overrides to the main container.
containers, found, _ := unstructured.NestedSlice(clone.Object, "spec", "template", "spec", "containers")
if found && len(containers) > 0 {
if container, ok := containers[0].(map[string]interface{}); ok {
if p.Image != nil && *p.Image != "" {
container["image"] = *p.Image
}
if p.Port != nil {
container["ports"] = []interface{}{
map[string]interface{}{
"containerPort": *p.Port,
"name": "workspace-port",
"protocol": "TCP",
},
}
}
resources, _ := container["resources"].(map[string]interface{})
if resources == nil {
resources = make(map[string]interface{})
}
if p.CPURequest != nil || p.MemoryRequest != nil {
requests, _ := resources["requests"].(map[string]interface{})
if requests == nil {
requests = make(map[string]interface{})
}
if p.CPURequest != nil {
requests["cpu"] = *p.CPURequest
}
if p.MemoryRequest != nil {
requests["memory"] = *p.MemoryRequest
}
resources["requests"] = requests
}
if p.CPULimit != nil || p.MemoryLimit != nil {
limits, _ := resources["limits"].(map[string]interface{})
if limits == nil {
limits = make(map[string]interface{})
}
if p.CPULimit != nil {
limits["cpu"] = *p.CPULimit
}
if p.MemoryLimit != nil {
limits["memory"] = *p.MemoryLimit
}
resources["limits"] = limits
}
container["resources"] = resources
containers[0] = container
}
if err := unstructured.SetNestedSlice(clone.Object, containers, "spec", "template", "spec", "containers"); err != nil {
return nil, fmt.Errorf("failed to apply clone overrides: %w", err)
}
}
created, err := s.client.CreateWorkspace(ctx, clone)
if err != nil {
if apierrors.IsAlreadyExists(err) {
return nil, workspaces.AlreadyExists(fmt.Sprintf("workspace %s/%s already exists", p.Namespace, p.NewName))
}
return nil, fmt.Errorf("failed to clone workspace: %w", err)
}
// Emit a Kubernetes Event for the action (best-effort)
if s.coreClient != nil {
msg := fmt.Sprintf("Workspace %s cloned from %s by %s", p.NewName, p.Name, actor)
if evErr := s.coreClient.CreateWorkspaceEvent(ctx, p.Namespace, p.NewName, "Cloned", actor, msg); evErr != nil {
log.Printf(ctx, "warning: failed to emit workspace event: %v", evErr)
}
}
return unstructuredToWorkspace(created), nil
}
// buildWorkspaceCR builds an unstructured Workspace CR from the create payload.
func buildWorkspaceCR(p *workspaces.CreateWorkspacePayload, imageClient *k8s.ImageClient) *unstructured.Unstructured {
containerPort := int64(p.Container.Port)
container := map[string]interface{}{
"name": p.Container.Name,
"image": p.Container.Image,
"ports": []interface{}{
map[string]interface{}{
"containerPort": containerPort,
"name": "workspace-port",
"protocol": "TCP",
},
},
"resources": map[string]interface{}{
"requests": map[string]interface{}{
"cpu": p.Container.CPURequest,
"memory": p.Container.MemoryRequest,
},
"limits": map[string]interface{}{
"cpu": p.Container.CPULimit,
"memory": p.Container.MemoryLimit,
},
},
}
// Set imagePullPolicy (always set it explicitly on the container spec)
if p.ImagePullPolicy != "" {
container["imagePullPolicy"] = p.ImagePullPolicy
}
// Look up Image CR for default args/env and security settings
var defaultUID *int64
var defaultInitContainers []k8s.ImageInitContainer
var preservePathPrefix bool
var additionalPorts []k8s.ImagePort
if imageClient != nil {
if img, err := imageClient.GetImageByRef(context.Background(), p.Container.Image); err == nil {
if len(img.DefaultArgs) > 0 {
args := make([]interface{}, len(img.DefaultArgs))
for i, a := range img.DefaultArgs {
a = strings.ReplaceAll(a, "{{namespace}}", p.Namespace)
a = strings.ReplaceAll(a, "{{name}}", p.Name)
args[i] = a
}
container["args"] = args
}
if len(img.DefaultEnv) > 0 {
envs := make([]interface{}, 0, len(img.DefaultEnv))
for _, e := range img.DefaultEnv {
value := e.Value
value = strings.ReplaceAll(value, "{{namespace}}", p.Namespace)
value = strings.ReplaceAll(value, "{{name}}", p.Name)
envs = append(envs, map[string]interface{}{
"name": e.Name,
"value": value,
})
}
container["env"] = envs
}
if img.Privileged {
container["securityContext"] = map[string]interface{}{
"privileged": true,
}
}
defaultUID = img.DefaultUID
defaultInitContainers = img.DefaultInitContainers
additionalPorts = img.AdditionalPorts
if img.DefaultSharedMemory {
p.SharedMemory = true
}
if img.ProxyConfig != nil {
preservePathPrefix = img.ProxyConfig.PreservePathPrefix
}
}
}
// Merge user-specified custom env vars (appended after image defaults)
if len(p.Env) > 0 {
existingEnvs, _ := container["env"].([]interface{})
if existingEnvs == nil {
existingEnvs = make([]interface{}, 0)
}
for _, e := range p.Env {
value := e.Value
value = strings.ReplaceAll(value, "{{namespace}}", p.Namespace)
value = strings.ReplaceAll(value, "{{name}}", p.Name)
existingEnvs = append(existingEnvs, map[string]interface{}{
"name": e.Name,
"value": value,
})
}
container["env"] = existingEnvs
}
// Add GPU resource limits if requested
if p.Container.GpuRequest != nil && *p.Container.GpuRequest != "" && *p.Container.GpuRequest != "0" {
resources := container["resources"].(map[string]interface{})
limits := resources["limits"].(map[string]interface{})
gpuVendor := p.Container.GpuVendor
if gpuVendor == "" {
gpuVendor = "nvidia.com/gpu"
}
limits[gpuVendor] = *p.Container.GpuRequest
}
// Add volume mounts if specified
if len(p.VolumeMounts) > 0 {
mounts := make([]interface{}, 0, len(p.VolumeMounts))
for _, vm := range p.VolumeMounts {
mounts = append(mounts, map[string]interface{}{
"name": vm.Name,
"mountPath": vm.MountPath,
})
}
container["volumeMounts"] = mounts
}
// Add additional ports from Image CR
if len(additionalPorts) > 0 {
ports := container["ports"].([]interface{})
for _, ap := range additionalPorts {
protocol := ap.Protocol
if protocol == "" {
protocol = "TCP"
}
ports = append(ports, map[string]interface{}{
"containerPort": int64(ap.Port),
"name": ap.Name,
"protocol": protocol,
})
}
container["ports"] = ports
}
spec := map[string]interface{}{
"containers": []interface{}{container},
}
// Add volumes for any volume mounts (referencing PVCs)
if len(p.VolumeMounts) > 0 {
volumes := make([]interface{}, 0, len(p.VolumeMounts))
for _, vm := range p.VolumeMounts {
volumes = append(volumes, map[string]interface{}{
"name": vm.Name,
"persistentVolumeClaim": map[string]interface{}{
"claimName": vm.Name,
},
})
}
spec["volumes"] = volumes
}
// Add /dev/shm as emptyDir with medium=Memory when shared_memory is enabled
if p.SharedMemory {
shmVolume := map[string]interface{}{
"name": "dshm",
"emptyDir": map[string]interface{}{
"medium": "Memory",
},
}
shmMount := map[string]interface{}{
"name": "dshm",
"mountPath": "/dev/shm",
}
// Append to existing volumes or create new list
if existing, ok := spec["volumes"].([]interface{}); ok {
spec["volumes"] = append(existing, shmVolume)
} else {
spec["volumes"] = []interface{}{shmVolume}
}
// Append mount to container
if existingMounts, ok := container["volumeMounts"].([]interface{}); ok {
container["volumeMounts"] = append(existingMounts, shmMount)
} else {
container["volumeMounts"] = []interface{}{shmMount}
}
}
// Set pod-level securityContext if defaultUID is specified
if defaultUID != nil {
spec["securityContext"] = map[string]interface{}{
"runAsUser": *defaultUID,
"fsGroup": *defaultUID,
}
}
// Add init containers if specified by Image CR
if len(defaultInitContainers) > 0 {
uidStr := ""
if defaultUID != nil {
uidStr = fmt.Sprintf("%d", *defaultUID)
}
initContainers := make([]interface{}, 0, len(defaultInitContainers))
for _, ic := range defaultInitContainers {
initC := map[string]interface{}{
"name": ic.Name,
"image": ic.Image,
}
if len(ic.Command) > 0 {
cmd := make([]interface{}, len(ic.Command))
for i, c := range ic.Command {
c = strings.ReplaceAll(c, "{{namespace}}", p.Namespace)
c = strings.ReplaceAll(c, "{{name}}", p.Name)
c = strings.ReplaceAll(c, "{{uid}}", uidStr)
cmd[i] = c
}
initC["command"] = cmd
}
if len(ic.Args) > 0 {
args := make([]interface{}, len(ic.Args))
for i, a := range ic.Args {
a = strings.ReplaceAll(a, "{{namespace}}", p.Namespace)
a = strings.ReplaceAll(a, "{{name}}", p.Name)
a = strings.ReplaceAll(a, "{{uid}}", uidStr)
args[i] = a
}
initC["args"] = args
}
if len(ic.Env) > 0 {
envs := make([]interface{}, 0, len(ic.Env))
for _, e := range ic.Env {
value := e.Value
value = strings.ReplaceAll(value, "{{namespace}}", p.Namespace)
value = strings.ReplaceAll(value, "{{name}}", p.Name)
value = strings.ReplaceAll(value, "{{uid}}", uidStr)
envs = append(envs, map[string]interface{}{
"name": e.Name,
"value": value,
})
}
initC["env"] = envs
}
// If init container has explicit volumeMounts, use them;
// otherwise, inherit the main container's volumeMounts
if len(ic.VolumeMounts) > 0 {
vms := make([]interface{}, 0, len(ic.VolumeMounts))
for _, vm := range ic.VolumeMounts {
vms = append(vms, map[string]interface{}{
"name": vm.Name,
"mountPath": vm.MountPath,
})
}
initC["volumeMounts"] = vms
} else if mounts, ok := container["volumeMounts"]; ok {
// Inherit main container's volume mounts
initC["volumeMounts"] = mounts
}
// Run init containers as root to allow chown operations
initC["securityContext"] = map[string]interface{}{
"runAsUser": int64(0),
}
initContainers = append(initContainers, initC)
}
spec["initContainers"] = initContainers
}
// Add node selector if specified
if len(p.NodeSelector) > 0 {
nodeSelector := make(map[string]interface{}, len(p.NodeSelector))
for k, v := range p.NodeSelector {
nodeSelector[k] = v
}
spec["nodeSelector"] = nodeSelector
}
// Add tolerations if specified
if len(p.Tolerations) > 0 {
tolerations := make([]interface{}, 0, len(p.Tolerations))
for _, t := range p.Tolerations {
tol := map[string]interface{}{
"key": t.Key,
"operator": t.Operator,
}
if t.Value != nil && *t.Value != "" {
tol["value"] = *t.Value
}
if t.Effect != nil && *t.Effect != "" {
tol["effect"] = *t.Effect
}
tolerations = append(tolerations, tol)
}
spec["tolerations"] = tolerations
}
// Auto-add GPU toleration if GPU is requested and not already specified
if p.Container.GpuRequest != nil && *p.Container.GpuRequest != "" && *p.Container.GpuRequest != "0" {
gpuVendor := p.Container.GpuVendor
if gpuVendor == "" {
gpuVendor = "nvidia.com/gpu"
}
// Check if a toleration for this GPU vendor already exists
hasGPUToleration := false
for _, t := range p.Tolerations {
if t.Key == gpuVendor {
hasGPUToleration = true
break
}
}
if !hasGPUToleration {
existingTolerations, _ := spec["tolerations"].([]interface{})
if existingTolerations == nil {
existingTolerations = make([]interface{}, 0)
}
existingTolerations = append(existingTolerations, map[string]interface{}{
"key": gpuVendor,
"operator": "Exists",
"effect": "NoSchedule",
})
spec["tolerations"] = existingTolerations
}
}
metadata := map[string]interface{}{
"name": p.Name,
"namespace": p.Namespace,
}
// Store proxy config as annotations so the proxy can read them directly
// from the workspace CR without depending on the current Image CR state.
if preservePathPrefix {
metadata["annotations"] = map[string]interface{}{
"kubeworkspaces.io/preserve-path-prefix": "true",
}
}
ws := &unstructured.Unstructured{
Object: map[string]interface{}{
"apiVersion": "kubeworkspaces.io/v1alpha1",
"kind": "Workspace",
"metadata": metadata,
"spec": map[string]interface{}{
"type": p.Type,
"template": map[string]interface{}{
"spec": spec,
},
},
},
}
return ws
}
// applyPodDefaults looks up PodDefaults in the target namespace and injects their
// configuration (env, volumes, volumeMounts, annotations, labels) into the workspace CR.
func applyPodDefaults(ctx context.Context, ws *unstructured.Unstructured, pdClient *k8s.PodDefaultClient, namespace string) {
log.Printf(ctx, "applyPodDefaults: checking namespace=%s", namespace)
// Get workspace labels (from pod template metadata, if any)
wsLabels := make(map[string]string)
if spec, ok := ws.Object["spec"].(map[string]interface{}); ok {
if template, ok := spec["template"].(map[string]interface{}); ok {
if podSpec, ok := template["spec"].(map[string]interface{}); ok {
_ = podSpec // labels come from pod template metadata, not spec
}
if meta, ok := template["metadata"].(map[string]interface{}); ok {
if lbl, ok := meta["labels"].(map[string]interface{}); ok {
for k, v := range lbl {
if s, ok := v.(string); ok {
wsLabels[k] = s
}
}
}
}
}
}
matching, err := pdClient.GetMatchingPodDefaults(ctx, namespace, wsLabels)
if err != nil {
log.Printf(ctx, "applyPodDefaults: error getting PodDefaults: %v", err)
return
}
if len(matching) == 0 {
log.Printf(ctx, "applyPodDefaults: no matching PodDefaults found in namespace=%s", namespace)
return
}
log.Printf(ctx, "applyPodDefaults: found %d matching PodDefaults", len(matching))
// Navigate to the pod spec and container
spec, _ := ws.Object["spec"].(map[string]interface{})
if spec == nil {
return
}
template, _ := spec["template"].(map[string]interface{})
if template == nil {
return
}
podSpec, _ := template["spec"].(map[string]interface{})
if podSpec == nil {
return
}
// Get the first container (workspace container)
containers, _ := podSpec["containers"].([]interface{})
if len(containers) == 0 {
return
}
container, _ := containers[0].(map[string]interface{})
if container == nil {
return
}
for _, pd := range matching {
// Inject env vars
if len(pd.Env) > 0 {
existingEnv, _ := container["env"].([]interface{})
for _, e := range pd.Env {
existingEnv = append(existingEnv, map[string]interface{}{
"name": e.Name,
"value": e.Value,
})
}
container["env"] = existingEnv
}
// Inject volume mounts
if len(pd.VolumeMounts) > 0 {
existingMounts, _ := container["volumeMounts"].([]interface{})
for _, vm := range pd.VolumeMounts {
mount := map[string]interface{}{
"name": vm.Name,
"mountPath": vm.MountPath,
}
if vm.ReadOnly {
mount["readOnly"] = true
}
existingMounts = append(existingMounts, mount)
}
container["volumeMounts"] = existingMounts
}
// Inject volumes
if len(pd.Volumes) > 0 {
existingVolumes, _ := podSpec["volumes"].([]interface{})
for _, v := range pd.Volumes {
existingVolumes = append(existingVolumes, v)
}
podSpec["volumes"] = existingVolumes
}
// Override service account name
if pd.ServiceAccountName != "" {
podSpec["serviceAccountName"] = pd.ServiceAccountName
}
// Inject annotations into workspace metadata
if len(pd.Annotations) > 0 {
annotations := ws.GetAnnotations()
if annotations == nil {
annotations = make(map[string]string)
}
for k, v := range pd.Annotations {
annotations[k] = v
}
ws.SetAnnotations(annotations)
}
// Inject labels into workspace metadata
if len(pd.Labels) > 0 {
existingLabels := ws.GetLabels()
if existingLabels == nil {
existingLabels = make(map[string]string)
}
for k, v := range pd.Labels {
existingLabels[k] = v
}
ws.SetLabels(existingLabels)
}
}
}
// unstructuredToWorkspace converts an unstructured Workspace CR to the API result type.
func unstructuredToWorkspace(obj *unstructured.Unstructured) *workspaces.Workspace {
ws := &workspaces.Workspace{
Name: obj.GetName(),
Namespace: obj.GetNamespace(),
}
// Workspace type (defaults to container for CRs created before the field existed)
wsType, _, _ := unstructured.NestedString(obj.Object, "spec", "type")
if wsType == "" {
wsType = "container"
}
ws.Type = wsType
// Check if stopped
annotations := obj.GetAnnotations()
if _, ok := annotations["kubeworkspaces.io/stopped"]; ok {
ws.Stopped = true
}
// Creation timestamp
createdAt := obj.GetCreationTimestamp().Format("2006-01-02T15:04:05Z")
ws.CreatedAt = &createdAt
// Extract container info from spec
containers, found, _ := unstructured.NestedSlice(obj.Object, "spec", "template", "spec", "containers")
if found && len(containers) > 0 {
container, ok := containers[0].(map[string]interface{})
if ok {
if image, ok := container["image"].(string); ok {
ws.Image = image
}
// Extract port
if ports, ok := container["ports"].([]interface{}); ok && len(ports) > 0 {
if portMap, ok := ports[0].(map[string]interface{}); ok {
if port, ok := portMap["containerPort"].(int64); ok {
portInt := int(port)
ws.Port = &portInt
}
}
}
// Extract resources
if resources, ok := container["resources"].(map[string]interface{}); ok {
if requests, ok := resources["requests"].(map[string]interface{}); ok {
if cpu, ok := requests["cpu"].(string); ok {
ws.CPURequest = &cpu
}
if mem, ok := requests["memory"].(string); ok {
ws.MemoryRequest = &mem
}
}
if limits, ok := resources["limits"].(map[string]interface{}); ok {
if cpu, ok := limits["cpu"].(string); ok {
ws.CPULimit = &cpu
}
if mem, ok := limits["memory"].(string); ok {