-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzen_precommit.changeset
More file actions
2557 lines (2468 loc) · 76.5 KB
/
zen_precommit.changeset
File metadata and controls
2557 lines (2468 loc) · 76.5 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
diff --git a/.golangci.yml b/.golangci.yml
index 8aaf592..ec99894 100644
--- a/.golangci.yml
+++ b/.golangci.yml
@@ -1,4 +1,6 @@
# golangci-lint configuration for kfunc
+version: 2
+
run:
timeout: 5m
tests: true
@@ -9,21 +11,11 @@ run:
linters:
enable:
- errcheck # Check for unchecked errors
- - gosimple # Simplify code
- govet # Go vet examination
- ineffassign # Detect ineffectual assignments
- staticcheck # Static analysis
- - typecheck # Type-check Go code
- unused # Check for unused constants, variables, functions
- - gofmt # Check formatting
- - goimports # Check imports formatting
- - goconst # Find repeated strings that could be constants
- - misspell # Find misspelled words
- - unparam # Find unused function parameters
- - unconvert # Remove unnecessary type conversions
- - exportloopref # Check for pointer to loop variables
- gosec # Security checks
- - nolintlint # Reports ill-formed or insufficient nolint directives
linters-settings:
errcheck:
@@ -34,9 +26,6 @@ linters-settings:
check-shadowing: true
enable-all: true
- gofmt:
- simplify: true
-
staticcheck:
checks: ["all"]
diff --git a/.pre-commit-setup.md b/.pre-commit-setup.md
deleted file mode 100644
index 2f6d514..0000000
--- a/.pre-commit-setup.md
+++ /dev/null
@@ -1,139 +0,0 @@
-# Pre-commit Hooks Setup
-
-This document explains how to set up and use pre-commit hooks for kfunc development.
-
-## Installation
-
-### 1. Install pre-commit
-
-```bash
-# Using pip
-pip install pre-commit
-
-# Or using homebrew (macOS)
-brew install pre-commit
-```
-
-### 2. Install the hooks
-
-```bash
-cd /Users/ken/dev/Kubernetes/kfunc
-pre-commit install
-```
-
-This will install the git hook scripts that run automatically on `git commit`.
-
-## Usage
-
-### Automatic execution
-
-Once installed, pre-commit hooks will run automatically when you commit:
-
-```bash
-git add .
-git commit -m "Your commit message"
-# Hooks run automatically
-```
-
-### Manual execution
-
-Run all hooks on all files:
-
-```bash
-pre-commit run --all-files
-```
-
-Run specific hook:
-
-```bash
-pre-commit run golangci-lint --all-files
-pre-commit run go-fmt --all-files
-```
-
-Run on staged files only:
-
-```bash
-pre-commit run
-```
-
-## Configured Hooks
-
-### Go-specific hooks
-- **go-fmt**: Format Go code with `gofmt`
-- **go-vet**: Run `go vet` for code examination
-- **go-imports**: Organize and format imports
-- **go-mod-tidy**: Tidy go.mod and go.sum
-- **go-build**: Build all commands in cmd/
-- **go-unit-tests**: Run short unit tests
-- **golangci-lint**: Comprehensive Go linting
-
-### File quality hooks
-- **trailing-whitespace**: Remove trailing whitespace
-- **end-of-file-fixer**: Ensure files end with newline
-- **check-yaml**: Validate YAML syntax
-- **check-added-large-files**: Prevent large files (>1MB)
-- **check-merge-conflict**: Detect merge conflict markers
-- **mixed-line-ending**: Enforce LF line endings
-
-### Additional linters
-- **yamllint**: YAML linting (excludes CRDs and specs)
-- **markdownlint**: Markdown formatting (excludes specs)
-- **hadolint**: Dockerfile linting
-- **codespell**: Spell checking
-
-## Skipping hooks
-
-If you need to skip hooks (use sparingly):
-
-```bash
-git commit --no-verify -m "Emergency fix"
-```
-
-## Configuration files
-
-- `.pre-commit-config.yaml` - Main pre-commit configuration
-- `.golangci.yml` - golangci-lint settings
-- `.yamllint` - YAML linting rules
-- `.markdownlint.json` - Markdown linting rules
-- `.codespell-ignore` - Words to ignore in spell check
-
-## Updating hooks
-
-Update hook versions:
-
-```bash
-pre-commit autoupdate
-```
-
-## Troubleshooting
-
-### Hooks failing
-
-If hooks fail, review the output and fix the issues:
-
-```bash
-# See what failed
-pre-commit run --all-files
-
-# Fix Go formatting
-go fmt ./...
-
-# Fix imports
-goimports -w .
-
-# Run linter manually
-golangci-lint run
-```
-
-### Hook installation issues
-
-If hooks don't run:
-
-```bash
-# Reinstall hooks
-pre-commit uninstall
-pre-commit install
-
-# Verify installation
-pre-commit run --all-files
-```
diff --git a/CLAUDE.md b/CLAUDE.md
index ef39778..6cd35fa 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -34,10 +34,13 @@ All feature work happens in dedicated branches with numbered specs in the `specs
### Common Commands
#### Starting a New Feature
+
```bash
/speckit.specify Add user authentication with OAuth2
```
+
This will:
+
- Generate a short name (e.g., "user-auth")
- Find the next available number (e.g., 001)
- Create branch `001-user-auth`
@@ -45,10 +48,13 @@ This will:
- Run quality validation with checklist
#### Planning Implementation
+
```bash
/speckit.plan
```
+
This will:
+
- Analyze the feature spec
- Generate `research.md` (technology decisions)
- Generate `data-model.md` (entities and relationships)
@@ -57,20 +63,26 @@ This will:
- Update agent context files
#### Generating Tasks
+
```bash
/speckit.tasks
```
+
This will:
+
- Create `tasks.md` with dependency-ordered task list
- Organize tasks by user story priority
- Mark parallel-executable tasks with [P]
- Include test tasks (if specified in constitution)
#### Implementing Features
+
```bash
/speckit.implement
```
+
This will:
+
- Verify all checklists are complete
- Create/verify ignore files (.gitignore, etc.)
- Execute tasks phase-by-phase
@@ -78,15 +90,19 @@ This will:
- Mark completed tasks in tasks.md
#### Clarifying Specifications
+
```bash
/speckit.clarify
```
+
Use when spec.md has [NEEDS CLARIFICATION] markers or underspecified areas.
#### Quality Analysis
+
```bash
/speckit.analyze
```
+
Validates consistency across spec.md, plan.md, and tasks.md after task generation.
## Architecture Principles
@@ -116,6 +132,7 @@ Always check constitution compliance during planning phase. Any complexity viola
### Specification Quality Requirements
All specs must be:
+
- **Technology-agnostic**: No implementation details (languages, frameworks)
- **User-focused**: Describe WHAT and WHY, not HOW
- **Testable**: Every requirement has acceptance criteria
@@ -127,12 +144,14 @@ Maximum 3 [NEEDS CLARIFICATION] markers per spec - use informed defaults for oth
### Task Organization
Tasks are grouped by user story to enable:
+
- **Independent implementation**: Each story can be built separately
- **Independent testing**: Each story can be validated independently
- **MVP delivery**: P1 stories can ship without P2/P3
- **Parallel execution**: Different team members work on different stories
Task format: `[ID] [P?] [Story] Description`
+
- `[P]`: Parallel-executable (different files, no dependencies)
- `[Story]`: User story tag (US1, US2, US3)
@@ -158,6 +177,7 @@ Always use `--json` flag to get structured output and parse JSON for file paths.
### Checklist Validation
Before `/speckit.implement`, all checklists in `specs/NNN-feature/checklists/` must be complete:
+
- Specification quality checklist (requirements.md)
- Custom feature checklists (generated by /speckit.checklist)
@@ -173,6 +193,7 @@ If incomplete, implementation will halt and ask for confirmation.
### Constitution Check Gates
During planning phase, validate against constitution:
+
- Technology choices must align with principles
- Complexity must be justified (record in plan.md Complexity Tracking table)
- Breaking constitution rules requires documented rationale
@@ -210,17 +231,20 @@ This project uses the SpecKit framework, which means:
**Language**: Go (idiomatic Go, prefer standard library)
**Core Dependencies**:
+
- Kubernetes client-go (operator framework)
- controller-runtime (Kubernetes controller patterns)
- Traefik (Docker/Podman mode HTTP proxy)
**Deployment Targets**:
+
- Kubernetes 1.24+ (primary)
- OpenShift 4.10+ (primary)
- Docker 20.10+ (development only)
- Podman 4.0+ (development only)
**Development Tools**:
+
- golangci-lint (linting)
- gofmt (formatting)
- go test (testing)
@@ -228,10 +252,12 @@ This project uses the SpecKit framework, which means:
### kfunc Quality Standards
**Performance Targets**:
+
- Cold start: <5 seconds for simple containers
- Routing overhead: <10ms p95 latency
**Code Quality**:
+
- Clear, actionable error messages with context
- Comprehensive structured logging (request IDs, timestamps, function names)
- Graceful degradation (failed functions don't crash operator)
@@ -239,6 +265,7 @@ This project uses the SpecKit framework, which means:
- Exported functions must have godoc comments
**Testing Gates**:
+
- Pre-commit: golangci-lint passes, unit tests pass, gofmt formatted
- Pre-merge: Integration tests pass, E2E tests pass, docs updated
@@ -251,8 +278,10 @@ This project uses the SpecKit framework, which means:
- **Language agnostic**: Functions are just containers with HTTP endpoints
## Active Technologies
+
- Go 1.21+ + Kubernetes client-go, controller-runtime (operator framework), HTTP router library (Gin or chi), Prometheus client library (001-serverless-operator)
- Kubernetes API (etcd) - no external databases (001-serverless-operator)
## Recent Changes
+
- 001-serverless-operator: Added Go 1.21+ + Kubernetes client-go, controller-runtime (operator framework), HTTP router library (Gin or chi), Prometheus client library
diff --git a/cmd/cli/main.go b/cmd/cli/main.go
index 327332f..5334868 100644
--- a/cmd/cli/main.go
+++ b/cmd/cli/main.go
@@ -1,26 +1,295 @@
package main
import (
+ "context"
"fmt"
"os"
+ "text/tabwriter"
+ "time"
+
+ corev1 "k8s.io/api/core/v1"
+ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ "k8s.io/apimachinery/pkg/runtime"
+ "k8s.io/client-go/kubernetes"
+ "k8s.io/client-go/tools/clientcmd"
+ "sigs.k8s.io/controller-runtime/pkg/client"
+
+ kfuncv1alpha1 "github.com/kfunc-io/kfunc/pkg/apis/kfunc/v1alpha1"
)
func main() {
+ if len(os.Args) < 2 {
+ printUsage()
+ os.Exit(0)
+ }
+
+ command := os.Args[1]
+
+ // Load kubeconfig
+ kubeconfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
+ clientcmd.NewDefaultClientConfigLoadingRules(),
+ &clientcmd.ConfigOverrides{},
+ )
+
+ config, err := kubeconfig.ClientConfig()
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "Error loading kubeconfig: %v\n", err)
+ os.Exit(1)
+ }
+
+ namespace, _, err := kubeconfig.Namespace()
+ if err != nil {
+ namespace = "default"
+ }
+
+ // Create scheme and client
+ scheme := runtime.NewScheme()
+ _ = kfuncv1alpha1.AddToScheme(scheme)
+
+ k8sClient, err := client.New(config, client.Options{Scheme: scheme})
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "Error creating client: %v\n", err)
+ os.Exit(1)
+ }
+
+ clientset, err := kubernetes.NewForConfig(config)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "Error creating clientset: %v\n", err)
+ os.Exit(1)
+ }
+
+ ctx := context.Background()
+
+ switch command {
+ case "list", "ls":
+ if err := listFunctions(ctx, k8sClient, namespace); err != nil {
+ fmt.Fprintf(os.Stderr, "Error: %v\n", err)
+ os.Exit(1)
+ }
+ case "describe", "get":
+ if len(os.Args) < 3 {
+ fmt.Fprintf(os.Stderr, "Usage: kfunc describe <function-name>\n")
+ os.Exit(1)
+ }
+ if err := describeFunction(ctx, k8sClient, namespace, os.Args[2]); err != nil {
+ fmt.Fprintf(os.Stderr, "Error: %v\n", err)
+ os.Exit(1)
+ }
+ case "logs":
+ if len(os.Args) < 3 {
+ fmt.Fprintf(os.Stderr, "Usage: kfunc logs <function-name>\n")
+ os.Exit(1)
+ }
+ if err := getFunctionLogs(ctx, clientset, namespace, os.Args[2]); err != nil {
+ fmt.Fprintf(os.Stderr, "Error: %v\n", err)
+ os.Exit(1)
+ }
+ case "delete", "rm":
+ if len(os.Args) < 3 {
+ fmt.Fprintf(os.Stderr, "Usage: kfunc delete <function-name>\n")
+ os.Exit(1)
+ }
+ if err := deleteFunction(ctx, k8sClient, namespace, os.Args[2]); err != nil {
+ fmt.Fprintf(os.Stderr, "Error: %v\n", err)
+ os.Exit(1)
+ }
+ case "help", "-h", "--help":
+ printUsage()
+ default:
+ fmt.Fprintf(os.Stderr, "Unknown command: %s\n\n", command)
+ printUsage()
+ os.Exit(1)
+ }
+}
+
+func printUsage() {
fmt.Println("kfunc CLI v0.1.0")
- fmt.Println("Usage: kfunc [command]")
+ fmt.Println()
+ fmt.Println("Usage: kfunc <command> [arguments]")
fmt.Println()
fmt.Println("Commands:")
- fmt.Println(" list List all functions")
- fmt.Println(" logs View function logs")
- fmt.Println(" delete Delete a function")
+ fmt.Println(" list, ls List all functions")
+ fmt.Println(" describe, get <name> Show detailed information about a function")
+ fmt.Println(" logs <name> View function logs")
+ fmt.Println(" delete, rm <name> Delete a function")
+ fmt.Println(" help Show this help message")
fmt.Println()
- fmt.Println("TODO: Implement CLI commands (Phase 5: User Story 3)")
+}
- if len(os.Args) < 2 {
- os.Exit(0)
+func listFunctions(ctx context.Context, k8sClient client.Client, namespace string) error {
+ functionList := &kfuncv1alpha1.FunctionList{}
+
+ listOpts := []client.ListOption{}
+ if namespace != "" {
+ listOpts = append(listOpts, client.InNamespace(namespace))
}
- command := os.Args[1]
- fmt.Printf("Command '%s' not yet implemented\n", command)
- os.Exit(1)
+ if err := k8sClient.List(ctx, functionList, listOpts...); err != nil {
+ return err
+ }
+
+ if len(functionList.Items) == 0 {
+ fmt.Println("No functions found")
+ return nil
+ }
+
+ w := tabwriter.NewWriter(os.Stdout, 0, 0, 3, ' ', 0)
+ fmt.Fprintln(w, "NAME\tNAMESPACE\tPHASE\tREPLICAS\tIMAGE\tAGE")
+
+ for _, fn := range functionList.Items {
+ age := time.Since(fn.CreationTimestamp.Time).Round(time.Second)
+ image := fn.Spec.Image
+ if len(image) > 40 {
+ image = image[:37] + "..."
+ }
+ fmt.Fprintf(w, "%s\t%s\t%s\t%d\t%s\t%s\n",
+ fn.Name,
+ fn.Namespace,
+ fn.Status.Phase,
+ fn.Status.Replicas,
+ image,
+ formatDuration(age),
+ )
+ }
+
+ w.Flush()
+ return nil
+}
+
+func describeFunction(ctx context.Context, k8sClient client.Client, namespace, name string) error {
+ function := &kfuncv1alpha1.Function{}
+ if err := k8sClient.Get(ctx, client.ObjectKey{Namespace: namespace, Name: name}, function); err != nil {
+ return err
+ }
+
+ fmt.Printf("Name: %s\n", function.Name)
+ fmt.Printf("Namespace: %s\n", function.Namespace)
+ fmt.Printf("Phase: %s\n", function.Status.Phase)
+ fmt.Printf("Replicas: %d\n", function.Status.Replicas)
+ fmt.Printf("Image: %s\n", function.Spec.Image)
+
+ if function.Spec.Port != nil {
+ fmt.Printf("Port: %d\n", *function.Spec.Port)
+ }
+
+ if function.Spec.MinReplicas != nil {
+ fmt.Printf("Min Replicas: %d\n", *function.Spec.MinReplicas)
+ }
+
+ if function.Spec.MaxReplicas != nil {
+ fmt.Printf("Max Replicas: %d\n", *function.Spec.MaxReplicas)
+ }
+
+ if function.Spec.IdleTimeout != "" {
+ fmt.Printf("Idle Timeout: %s\n", function.Spec.IdleTimeout)
+ }
+
+ if function.Spec.RequestTimeout != "" {
+ fmt.Printf("Request Timeout: %s\n", function.Spec.RequestTimeout)
+ }
+
+ if len(function.Spec.Env) > 0 {
+ fmt.Printf("\nEnvironment Variables:\n")
+ for _, env := range function.Spec.Env {
+ fmt.Printf(" %s=%s\n", env.Name, env.Value)
+ }
+ }
+
+ if len(function.Spec.Secrets) > 0 {
+ fmt.Printf("\nSecrets:\n")
+ for _, secret := range function.Spec.Secrets {
+ if secret.Key != "" {
+ fmt.Printf(" %s (key: %s → env: %s)\n", secret.Name, secret.Key, secret.Env)
+ } else {
+ fmt.Printf(" %s (%s)\n", secret.Name, secret.MountAs)
+ }
+ }
+ }
+
+ if function.Spec.HealthCheck != nil {
+ fmt.Printf("\nHealth Check:\n")
+ fmt.Printf(" Path: %s\n", function.Spec.HealthCheck.Path)
+ fmt.Printf(" Interval: %s\n", function.Spec.HealthCheck.Interval)
+ fmt.Printf(" Timeout: %s\n", function.Spec.HealthCheck.Timeout)
+ }
+
+ if !function.Status.LastInvocationTime.IsZero() {
+ fmt.Printf("\nLast Invocation: %s ago\n", time.Since(function.Status.LastInvocationTime.Time).Round(time.Second))
+ }
+
+ fmt.Printf("\nCreated: %s ago\n", time.Since(function.CreationTimestamp.Time).Round(time.Second))
+
+ return nil
+}
+
+func getFunctionLogs(ctx context.Context, clientset *kubernetes.Clientset, namespace, functionName string) error {
+ // Find pods for this function
+ labelSelector := fmt.Sprintf("kfunc.io/function=%s", functionName)
+
+ pods, err := clientset.CoreV1().Pods(namespace).List(ctx, metav1.ListOptions{
+ LabelSelector: labelSelector,
+ })
+ if err != nil {
+ return err
+ }
+
+ if len(pods.Items) == 0 {
+ return fmt.Errorf("no pods found for function %s", functionName)
+ }
+
+ // Get logs from first pod
+ pod := pods.Items[0]
+ req := clientset.CoreV1().Pods(namespace).GetLogs(pod.Name, &corev1.PodLogOptions{
+ Container: "function",
+ TailLines: int64Ptr(50),
+ })
+
+ logs, err := req.Stream(ctx)
+ if err != nil {
+ return err
+ }
+ defer logs.Close()
+
+ fmt.Printf("Logs from pod %s:\n\n", pod.Name)
+
+ buf := make([]byte, 2048)
+ for {
+ n, err := logs.Read(buf)
+ if n > 0 {
+ fmt.Print(string(buf[:n]))
+ }
+ if err != nil {
+ break
+ }
+ }
+
+ return nil
+}
+
+func deleteFunction(ctx context.Context, k8sClient client.Client, namespace, name string) error {
+ function := &kfuncv1alpha1.Function{}
+ function.Name = name
+ function.Namespace = namespace
+
+ if err := k8sClient.Delete(ctx, function); err != nil {
+ return err
+ }
+
+ fmt.Printf("Function '%s' deleted\n", name)
+ return nil
+}
+
+func formatDuration(d time.Duration) string {
+ if d < time.Minute {
+ return fmt.Sprintf("%ds", int(d.Seconds()))
+ } else if d < time.Hour {
+ return fmt.Sprintf("%dm", int(d.Minutes()))
+ } else if d < 24*time.Hour {
+ return fmt.Sprintf("%dh", int(d.Hours()))
+ }
+ return fmt.Sprintf("%dd", int(d.Hours()/24))
+}
+
+func int64Ptr(i int64) *int64 {
+ return &i
}
diff --git a/cmd/gateway/main.go b/cmd/gateway/main.go
index d9ff591..818b44b 100644
--- a/cmd/gateway/main.go
+++ b/cmd/gateway/main.go
@@ -70,17 +70,21 @@ func main() {
// Initialize router
router := gateway.NewRouter(k8sClient, logger, scaler)
+ // Initialize auth middleware (needs router for namespace lookup)
+ authMiddleware := gateway.NewAuthMiddleware(k8sClient, logger, router)
+
// Start background workers
go router.StartWatcher(ctx)
go scaler.StartIdleChecker(ctx)
+ go authMiddleware.StartWatcher(ctx)
// Initial route update
if err := router.UpdateRoutes(ctx); err != nil {
logger.Error("Failed to initialize routes", zap.Error(err))
}
- // Setup HTTP server
- handler := router.SetupRoutes()
+ // Setup HTTP server with auth middleware
+ handler := authMiddleware.Middleware(router.SetupRoutes())
server := &http.Server{
Addr: fmt.Sprintf(":%d", port),
Handler: handler,
diff --git a/config/crd/kfunc.io_functions.yaml b/config/crd/kfunc.io_functions.yaml
index 58f259f..7f4fcf2 100644
--- a/config/crd/kfunc.io_functions.yaml
+++ b/config/crd/kfunc.io_functions.yaml
@@ -313,6 +313,12 @@ spec:
maximum: 65535
minimum: 1
type: integer
+ requestTimeout:
+ default: 30s
+ description: RequestTimeout is the timeout for HTTP requests to the
+ function
+ pattern: ^[0-9]+[sm]$
+ type: string
resources:
description: Resources define CPU/memory requests and limits
properties:
@@ -378,6 +384,14 @@ spec:
items:
description: SecretReference defines how to mount a Kubernetes secret
properties:
+ env:
+ description: Env is the environment variable name to use when
+ mounting a specific key
+ type: string
+ key:
+ description: Key is the specific key in the secret to reference
+ (optional, if not set all keys are mounted)
+ type: string
mountAs:
default: env
description: 'MountAs specifies how to mount the secret: "env"
diff --git a/pkg/apis/kfunc/v1alpha1/function_types.go b/pkg/apis/kfunc/v1alpha1/function_types.go
index 350b569..2b90e0e 100644
--- a/pkg/apis/kfunc/v1alpha1/function_types.go
+++ b/pkg/apis/kfunc/v1alpha1/function_types.go
@@ -32,6 +32,12 @@ type FunctionSpec struct {
// +optional
IdleTimeout string `json:"idleTimeout,omitempty"`
+ // RequestTimeout is the timeout for HTTP requests to the function
+ // +kubebuilder:validation:Pattern=`^[0-9]+[sm]$`
+ // +kubebuilder:default="30s"
+ // +optional
+ RequestTimeout string `json:"requestTimeout,omitempty"`
+
// Port is the HTTP port the function container listens on
// +kubebuilder:validation:Minimum=1
// +kubebuilder:validation:Maximum=65535
@@ -70,6 +76,14 @@ type SecretReference struct {
// +kubebuilder:validation:Required
Name string `json:"name"`
+ // Key is the specific key in the secret to reference (optional, if not set all keys are mounted)
+ // +optional
+ Key string `json:"key,omitempty"`
+
+ // Env is the environment variable name to use when mounting a specific key
+ // +optional
+ Env string `json:"env,omitempty"`
+
// MountAs specifies how to mount the secret: "env" or "volume"
// +kubebuilder:validation:Enum=env;volume
// +kubebuilder:default=env
diff --git a/pkg/controller/function_controller.go b/pkg/controller/function_controller.go
index b0c9400..d412107 100644
--- a/pkg/controller/function_controller.go
+++ b/pkg/controller/function_controller.go
@@ -32,6 +32,7 @@ type FunctionReconciler struct {
// +kubebuilder:rbac:groups=kfunc.io,resources=functions/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=apps,resources=deployments,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups="",resources=services,verbs=get;list;watch;create;update;patch;delete
+// +kubebuilder:rbac:groups="",resources=secrets,verbs=get;list;watch
// Reconcile implements the reconciliation loop
func (r *FunctionReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
@@ -58,14 +59,30 @@ func (r *FunctionReconciler) Reconcile(ctx context.Context, req ctrl.Request) (c
logger.Info("Reconciling function", zap.Int64("generation", function.Generation))
// Handle deletion with finalizer
- if !function.ObjectMeta.DeletionTimestamp.IsZero() {
+ if !function.DeletionTimestamp.IsZero() {
if controllerutil.ContainsFinalizer(function, functionFinalizerName) {
- // Perform cleanup (currently handled by OwnerReferences)
+ // Perform explicit cleanup
logger.Info("Cleaning up function resources")
+
+ // Delete Deployment
+ if err := r.cleanupDeployment(ctx, function); err != nil {
+ logger.Error("Failed to cleanup Deployment", zap.Error(err))
+ return ctrl.Result{}, err
+ }
+
+ // Delete Service
+ if err := r.cleanupService(ctx, function); err != nil {
+ logger.Error("Failed to cleanup Service", zap.Error(err))
+ return ctrl.Result{}, err
+ }
+
+ // Remove finalizer
controllerutil.RemoveFinalizer(function, functionFinalizerName)
if err := r.Update(ctx, function); err != nil {
return ctrl.Result{}, err
}
+
+ logger.Info("Function cleanup complete")
}
return ctrl.Result{}, nil
}
@@ -113,7 +130,8 @@ func (r *FunctionReconciler) Reconcile(ctx context.Context, req ctrl.Request) (c
metrics.OperatorReconcileTotal.WithLabelValues(req.Name, "success").Inc()
metrics.OperatorReconcileDuration.WithLabelValues(req.Name, "success").Observe(time.Since(startTime).Seconds())
- metrics.OperatorFunctionCount.WithLabelValues(phase).Inc()
+ // Note: OperatorFunctionCount is updated separately via periodic aggregation
+ // to avoid double-counting on every reconciliation
logger.Info("Reconciliation complete",
zap.String("phase", phase),
@@ -133,5 +151,59 @@ func (r *FunctionReconciler) SetupWithManager(mgr ctrl.Manager) error {
Complete(r)
}
+// cleanupDeployment deletes the Deployment for a Function
+func (r *FunctionReconciler) cleanupDeployment(ctx context.Context, function *kfuncv1alpha1.Function) error {
+ deploymentName := "function-" + function.Name
+ deployment := &appsv1.Deployment{}
+
+ err := r.Get(ctx, client.ObjectKey{
+ Name: deploymentName,
+ Namespace: function.Namespace,
+ }, deployment)
+
+ if err != nil {
+ if errors.IsNotFound(err) {
+ // Already deleted
+ return nil
+ }
+ return err
+ }
+
+ // Delete the Deployment
+ if err := r.Delete(ctx, deployment); err != nil && !errors.IsNotFound(err) {
+ return err
+ }
+
+ r.Logger.Info("Deleted Deployment", zap.String("name", deploymentName))
+ return nil
+}
+
+// cleanupService deletes the Service for a Function
+func (r *FunctionReconciler) cleanupService(ctx context.Context, function *kfuncv1alpha1.Function) error {
+ serviceName := "function-" + function.Name
+ service := &corev1.Service{}
+
+ err := r.Get(ctx, client.ObjectKey{
+ Name: serviceName,
+ Namespace: function.Namespace,
+ }, service)
+
+ if err != nil {
+ if errors.IsNotFound(err) {
+ // Already deleted
+ return nil
+ }
+ return err
+ }
+
+ // Delete the Service
+ if err := r.Delete(ctx, service); err != nil && !errors.IsNotFound(err) {
+ return err
+ }
+
+ r.Logger.Info("Deleted Service", zap.String("name", serviceName))
+ return nil
+}
+
// Helper methods will be in separate files to keep this focused
// (see function_deployment.go, function_service.go, function_validation.go)
diff --git a/pkg/controller/function_deployment.go b/pkg/controller/function_deployment.go
index f4f1a10..4fa2a26 100644
--- a/pkg/controller/function_deployment.go
+++ b/pkg/controller/function_deployment.go
@@ -3,6 +3,7 @@ package controller
import (
"context"
"fmt"
+ "time"
"go.uber.org/zap"
appsv1 "k8s.io/api/apps/v1"
@@ -73,11 +74,27 @@ func (r *FunctionReconciler) generateDeployment(function *kfuncv1alpha1.Function
"kfunc.io/managed-by": "kfunc-operator",
}
+ // Build annotations for timeout and replica configuration
+ annotations := map[string]string{}
+ if function.Spec.RequestTimeout != "" {
+ annotations["kfunc.io/request-timeout"] = function.Spec.RequestTimeout
+ }
+ if function.Spec.IdleTimeout != "" {
+ annotations["kfunc.io/idle-timeout"] = function.Spec.IdleTimeout
+ }
+ if function.Spec.MinReplicas != nil {
+ annotations["kfunc.io/min-replicas"] = fmt.Sprintf("%d", *function.Spec.MinReplicas)
+ }
+ if function.Spec.MaxReplicas != nil {
+ annotations["kfunc.io/max-replicas"] = fmt.Sprintf("%d", *function.Spec.MaxReplicas)
+ }
+
deployment := &appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{
- Name: fmt.Sprintf("function-%s", function.Name),
- Namespace: function.Namespace,
- Labels: labels,
+ Name: fmt.Sprintf("function-%s", function.Name),
+ Namespace: function.Namespace,
+ Labels: labels,
+ Annotations: annotations,
},
Spec: appsv1.DeploymentSpec{
Replicas: replicas,
@@ -135,8 +152,24 @@ func (r *FunctionReconciler) generateDeployment(function *kfuncv1alpha1.Function
ReadOnly: true,
},
)
+ } else if secretRef.Key != "" && secretRef.Env != "" {
+ // Mount specific key as individual env var
+ deployment.Spec.Template.Spec.Containers[0].Env = append(
+ deployment.Spec.Template.Spec.Containers[0].Env,
+ corev1.EnvVar{
+ Name: secretRef.Env,
+ ValueFrom: &corev1.EnvVarSource{
+ SecretKeyRef: &corev1.SecretKeySelector{
+ LocalObjectReference: corev1.LocalObjectReference{
+ Name: secretRef.Name,
+ },
+ Key: secretRef.Key,
+ },
+ },
+ },
+ )
} else {
- // Mount as env (default)
+ // Mount all keys from secret as env (default)
deployment.Spec.Template.Spec.Containers[0].EnvFrom = append(
deployment.Spec.Template.Spec.Containers[0].EnvFrom,
corev1.EnvFromSource{
@@ -153,16 +186,58 @@ func (r *FunctionReconciler) generateDeployment(function *kfuncv1alpha1.Function
// Add health check if specified
if function.Spec.HealthCheck != nil {
- probe := &corev1.Probe{
+ // Parse interval from spec, with default
+ interval := 10 * time.Second
+ if function.Spec.HealthCheck.Interval != "" {
+ if parsed, err := time.ParseDuration(function.Spec.HealthCheck.Interval); err == nil {
+ interval = parsed
+ }
+ }
+
+ // Parse timeout from spec, with default
+ timeout := 3 * time.Second
+ if function.Spec.HealthCheck.Timeout != "" {
+ if parsed, err := time.ParseDuration(function.Spec.HealthCheck.Timeout); err == nil {
+ timeout = parsed
+ }
+ }
+
+ // Get failure threshold from spec, with default
+ failureThreshold := int32(3)
+ if function.Spec.HealthCheck.FailureThreshold != nil {
+ failureThreshold = *function.Spec.HealthCheck.FailureThreshold
+ }
+
+ // Create separate probe instances for liveness and readiness
+ // Liveness probe is more lenient to avoid restart loops
+ livenessProbe := &corev1.Probe{
+ ProbeHandler: corev1.ProbeHandler{
+ HTTPGet: &corev1.HTTPGetAction{
+ Path: function.Spec.HealthCheck.Path,
+ Port: intstr.FromInt(int(*port)),
+ },
+ },
+ InitialDelaySeconds: 10,
+ PeriodSeconds: int32(interval.Seconds() * 1.5), // Liveness less frequent
+ TimeoutSeconds: int32(timeout.Seconds()),
+ FailureThreshold: failureThreshold + 2, // More tolerant
+ }
+
+ readinessProbe := &corev1.Probe{
ProbeHandler: corev1.ProbeHandler{
HTTPGet: &corev1.HTTPGetAction{
Path: function.Spec.HealthCheck.Path,
Port: intstr.FromInt(int(*port)),
},
},
+ InitialDelaySeconds: 5,
+ PeriodSeconds: int32(interval.Seconds()),
+ TimeoutSeconds: int32(timeout.Seconds()),
+ FailureThreshold: failureThreshold,
}
- deployment.Spec.Template.Spec.Containers[0].LivenessProbe = probe