Skip to content

Commit 3e22a25

Browse files
committed
Add file provider
1 parent 5a71e2a commit 3e22a25

File tree

9 files changed

+984
-1
lines changed

9 files changed

+984
-1
lines changed

examples/file/README.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# file
2+
3+
The file provider reads kubeconfig files from the local filesystem.
4+
5+
It provides clusters named after the context name in the kubeconfig file.
6+
7+
This example reads kubeconfig files at the specified paths and lists the
8+
collected clusters.
9+
10+
## Example
11+
12+
With a single kind cluster defined in `~/.kube/config`:
13+
14+
```bash
15+
$ go run . -paths ~/.kube/config
16+
Clusters:
17+
- kind-kind
18+
```

examples/file/go.mod

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
module sigs.k8s.io/multicluster-runtime/examples/file
2+
3+
go 1.24.0
4+
5+
replace sigs.k8s.io/multicluster-runtime => ../..
6+
7+
require sigs.k8s.io/multicluster-runtime v0.0.0-00010101000000-000000000000
8+
9+
require (
10+
github.com/davecgh/go-spew v1.1.1 // indirect
11+
github.com/emicklei/go-restful/v3 v3.11.0 // indirect
12+
github.com/evanphx/json-patch/v5 v5.9.11 // indirect
13+
github.com/fxamacker/cbor/v2 v2.7.0 // indirect
14+
github.com/go-logr/logr v1.4.2 // indirect
15+
github.com/go-openapi/jsonpointer v0.21.0 // indirect
16+
github.com/go-openapi/jsonreference v0.20.2 // indirect
17+
github.com/go-openapi/swag v0.23.0 // indirect
18+
github.com/gogo/protobuf v1.3.2 // indirect
19+
github.com/google/gnostic-models v0.6.9 // indirect
20+
github.com/google/go-cmp v0.7.0 // indirect
21+
github.com/google/uuid v1.6.0 // indirect
22+
github.com/josharian/intern v1.0.0 // indirect
23+
github.com/json-iterator/go v1.1.12 // indirect
24+
github.com/mailru/easyjson v0.7.7 // indirect
25+
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
26+
github.com/modern-go/reflect2 v1.0.2 // indirect
27+
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
28+
github.com/pkg/errors v0.9.1 // indirect
29+
github.com/spf13/pflag v1.0.5 // indirect
30+
github.com/x448/float16 v0.8.4 // indirect
31+
golang.org/x/net v0.38.0 // indirect
32+
golang.org/x/oauth2 v0.27.0 // indirect
33+
golang.org/x/sys v0.31.0 // indirect
34+
golang.org/x/term v0.30.0 // indirect
35+
golang.org/x/text v0.23.0 // indirect
36+
golang.org/x/time v0.9.0 // indirect
37+
google.golang.org/protobuf v1.36.5 // indirect
38+
gopkg.in/evanphx/json-patch.v4 v4.12.0 // indirect
39+
gopkg.in/inf.v0 v0.9.1 // indirect
40+
gopkg.in/yaml.v3 v3.0.1 // indirect
41+
k8s.io/api v0.33.0 // indirect
42+
k8s.io/apimachinery v0.33.0 // indirect
43+
k8s.io/client-go v0.33.0 // indirect
44+
k8s.io/klog/v2 v2.130.1 // indirect
45+
k8s.io/kube-openapi v0.0.0-20250318190949-c8a335a9a2ff // indirect
46+
k8s.io/utils v0.0.0-20241104100929-3ea5e8cea738 // indirect
47+
sigs.k8s.io/controller-runtime v0.21.0 // indirect
48+
sigs.k8s.io/json v0.0.0-20241010143419-9aa6b5e7a4b3 // indirect
49+
sigs.k8s.io/randfill v1.0.0 // indirect
50+
sigs.k8s.io/structured-merge-diff/v4 v4.6.0 // indirect
51+
sigs.k8s.io/yaml v1.4.0 // indirect
52+
)

examples/file/go.sum

Lines changed: 191 additions & 0 deletions
Large diffs are not rendered by default.

examples/file/main.go

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
/*
2+
Copyright 2025 The Kubernetes Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package main
18+
19+
import (
20+
"context"
21+
"flag"
22+
"fmt"
23+
"os/signal"
24+
"strings"
25+
"syscall"
26+
"time"
27+
28+
"sigs.k8s.io/multicluster-runtime/providers/file"
29+
)
30+
31+
var (
32+
fPaths = flag.String("paths", "", "Comma-separated list of file paths to process (can be files or directories), defaults to current directory")
33+
fGlobs = flag.String("globs", "", "Comma-separated list of glob patterns to match files")
34+
fContinue = flag.Bool("continue", false, "Continue processing and listing files until cancelled")
35+
)
36+
37+
func printClusters(clusters []string) {
38+
if len(clusters) == 0 {
39+
fmt.Println("No clusters found.")
40+
return
41+
}
42+
fmt.Println("Clusters:")
43+
for _, cluster := range clusters {
44+
fmt.Printf("- %s\n", cluster)
45+
}
46+
}
47+
48+
func main() {
49+
flag.Parse()
50+
51+
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
52+
defer cancel()
53+
54+
provider, err := file.New(file.Options{
55+
Paths: strings.Split(*fPaths, ","),
56+
KubeconfigGlobs: strings.Split(*fGlobs, ","),
57+
})
58+
if err != nil {
59+
fmt.Printf("Error creating provider: %v\n", err)
60+
return
61+
}
62+
63+
if err := provider.RunOnce(ctx); err != nil {
64+
fmt.Printf("Error running provider once: %v\n", err)
65+
return
66+
}
67+
68+
printClusters(provider.ClusterNames())
69+
70+
if *fContinue {
71+
go func() {
72+
if err := provider.Run(ctx); err != nil {
73+
fmt.Printf("Error running provider continuously: %v\n", err)
74+
return
75+
}
76+
}()
77+
78+
for range time.Tick(1 * time.Second) {
79+
if ctx.Err() != nil {
80+
fmt.Println("Context cancelled, stopping...")
81+
break
82+
}
83+
84+
printClusters(provider.ClusterNames())
85+
}
86+
}
87+
}

go.mod

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ require (
1818
k8s.io/klog/v2 v2.130.1
1919
k8s.io/utils v0.0.0-20241104100929-3ea5e8cea738
2020
sigs.k8s.io/controller-runtime v0.21.0
21+
sigs.k8s.io/randfill v1.0.0
2122
sigs.k8s.io/yaml v1.4.0
2223
)
2324

@@ -67,6 +68,5 @@ require (
6768
gopkg.in/yaml.v3 v3.0.1 // indirect
6869
k8s.io/kube-openapi v0.0.0-20250318190949-c8a335a9a2ff // indirect
6970
sigs.k8s.io/json v0.0.0-20241010143419-9aa6b5e7a4b3 // indirect
70-
sigs.k8s.io/randfill v1.0.0 // indirect
7171
sigs.k8s.io/structured-merge-diff/v4 v4.6.0 // indirect
7272
)

providers/file/clusters.go

Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
1+
/*
2+
Copyright 2025 The Kubernetes Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package file
18+
19+
import (
20+
"fmt"
21+
"os"
22+
"path/filepath"
23+
24+
"k8s.io/client-go/rest"
25+
"k8s.io/client-go/tools/clientcmd"
26+
27+
"sigs.k8s.io/controller-runtime/pkg/cluster"
28+
)
29+
30+
type clusters map[string]cluster.Cluster
31+
32+
func (p *Provider) loadClusters() (clusters, error) {
33+
filepaths, err := p.collectPaths(p.opts.Paths)
34+
if err != nil {
35+
return nil, err
36+
}
37+
38+
kubeCtxs := map[string]*rest.Config{}
39+
for _, filepath := range filepaths {
40+
fileKubeCtxs, err := readFile(filepath)
41+
if err != nil {
42+
p.log.Error(err, "failed to read kubeconfig file", "file", filepath)
43+
continue
44+
}
45+
for name, kubeCtx := range fileKubeCtxs {
46+
if _, exists := kubeCtxs[name]; exists {
47+
p.log.Error(nil, "duplicate context name found", "context", name, "file", filepath)
48+
continue
49+
}
50+
kubeCtxs[name] = kubeCtx
51+
}
52+
}
53+
54+
return p.fromContexts(kubeCtxs), nil
55+
}
56+
57+
func (p *Provider) collectPaths(paths []string) ([]string, error) {
58+
filepaths := make([]string, 0, len(paths))
59+
60+
for _, path := range paths {
61+
if path == "" {
62+
continue
63+
}
64+
65+
stat, err := os.Stat(path)
66+
if err != nil {
67+
if os.IsNotExist(err) {
68+
p.log.Info("path does not exist, skipping", "path", path)
69+
continue
70+
}
71+
return nil, fmt.Errorf("failed to stat path %q: %w", path, err)
72+
}
73+
74+
if !stat.IsDir() {
75+
filepaths = append(filepaths, path)
76+
continue
77+
}
78+
79+
filepaths = append(filepaths, p.matchKubeconfigGlobs(path)...)
80+
}
81+
82+
return filepaths, nil
83+
}
84+
85+
func (p *Provider) matchKubeconfigGlobs(dirpath string) []string {
86+
matches := []string{}
87+
88+
for _, glob := range p.opts.KubeconfigGlobs {
89+
globMatches, err := filepath.Glob(filepath.Join(dirpath, glob))
90+
if err != nil {
91+
p.log.Error(err, "failed to glob files", "dirpath", dirpath, "glob", glob)
92+
continue
93+
}
94+
matches = append(matches, globMatches...)
95+
}
96+
97+
return matches
98+
}
99+
100+
func readFile(filepath string) (map[string]*rest.Config, error) {
101+
config, err := clientcmd.LoadFromFile(filepath)
102+
if err != nil {
103+
return nil, fmt.Errorf("failed to load kubeconfig from file %q: %w", filepath, err)
104+
}
105+
106+
ret := make(map[string]*rest.Config, len(config.Contexts))
107+
for name := range config.Contexts {
108+
restConfig, err := clientcmd.NewNonInteractiveClientConfig(*config, name, &clientcmd.ConfigOverrides{}, nil).ClientConfig()
109+
if err != nil {
110+
return nil, fmt.Errorf("failed to create rest config for context %q: %w", name, err)
111+
}
112+
ret[name] = restConfig
113+
}
114+
115+
return ret, nil
116+
}
117+
118+
func (p *Provider) fromContexts(kubeCtxs map[string]*rest.Config) clusters {
119+
c := make(map[string]cluster.Cluster, len(kubeCtxs))
120+
121+
for name, kubeCtx := range kubeCtxs {
122+
cl, err := cluster.New(kubeCtx)
123+
if err != nil {
124+
p.log.Error(err, "failed to create cluster", "context", name)
125+
continue
126+
}
127+
if _, ok := c[name]; ok {
128+
p.log.Error(nil, "duplicate context name found", "context", name)
129+
continue
130+
}
131+
c[name] = cl
132+
}
133+
134+
return c
135+
}

providers/file/file_suite_test.go

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/*
2+
Copyright 2025 The Kubernetes Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package file
18+
19+
import (
20+
"testing"
21+
22+
logf "sigs.k8s.io/controller-runtime/pkg/log"
23+
"sigs.k8s.io/controller-runtime/pkg/log/zap"
24+
metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server"
25+
26+
. "github.com/onsi/ginkgo/v2"
27+
. "github.com/onsi/gomega"
28+
)
29+
30+
func TestBuilder(t *testing.T) {
31+
RegisterFailHandler(Fail)
32+
RunSpecs(t, "File Provider Suite")
33+
}
34+
35+
var _ = BeforeSuite(func() {
36+
logf.SetLogger(zap.New(zap.WriteTo(GinkgoWriter), zap.UseDevMode(true)))
37+
38+
// The file provider is designed to work with local files and
39+
// directories, so we don't need envtest.
40+
41+
// Prevent the metrics listener being created
42+
metricsserver.DefaultBindAddress = "0"
43+
})
44+
45+
var _ = AfterSuite(func() {
46+
metricsserver.DefaultBindAddress = ":8080"
47+
})

0 commit comments

Comments
 (0)