Skip to content

Commit 8088abe

Browse files
committed
Add KCP helpers for creating new managers/clients/caches
1 parent 3f3188c commit 8088abe

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

pkg/kcp/wrappers.go

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package kcp
2+
3+
import (
4+
"net/http"
5+
6+
"k8s.io/client-go/rest"
7+
8+
kcpcache "github.com/kcp-dev/apimachinery/pkg/cache"
9+
kcpclient "github.com/kcp-dev/apimachinery/pkg/client"
10+
11+
ctrl "sigs.k8s.io/controller-runtime"
12+
"sigs.k8s.io/controller-runtime/pkg/cache"
13+
"sigs.k8s.io/controller-runtime/pkg/client"
14+
"sigs.k8s.io/controller-runtime/pkg/cluster"
15+
"sigs.k8s.io/controller-runtime/pkg/manager"
16+
)
17+
18+
// NewClusterAwareManager returns a kcp-aware manager with appropriate defaults for cache and
19+
// client creation.
20+
func NewClusterAwareManager(cfg *rest.Config, options ctrl.Options) (manager.Manager, error) {
21+
if options.NewCache == nil {
22+
options.NewCache = NewClusterAwareCache
23+
}
24+
if options.NewClient == nil {
25+
options.NewClient = NewClusterAwareClient
26+
}
27+
28+
return ctrl.NewManager(cfg, options)
29+
}
30+
31+
// NewClusterAwareCache returns a cache.Cache that handles multi-cluster watches.
32+
func NewClusterAwareCache(config *rest.Config, opts cache.Options) (cache.Cache, error) {
33+
c := rest.CopyConfig(config)
34+
c.Host += "/clusters/*"
35+
opts.KeyFunction = kcpcache.ClusterAwareKeyFunc
36+
return cache.New(c, opts)
37+
}
38+
39+
// NewClusterAwareClient returns a client.Client that is configured to use the context
40+
// to scope requests to the proper cluster. To scope requests, pass the request context with the cluster set.
41+
// Example:
42+
// import (
43+
// "context"
44+
// kcpclient "github.com/kcp-dev/apimachinery/pkg/client"
45+
// ctrl "sigs.k8s.io/controller-runtime"
46+
// )
47+
// func (r *reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
48+
// ctx = kcpclient.WithCluster(ctx, req.ObjectKey.Cluster)
49+
// // from here on pass this context to all client calls
50+
// ...
51+
// }
52+
func NewClusterAwareClient(cache cache.Cache, config *rest.Config, opts client.Options, uncachedObjects ...client.Object) (client.Client, error) {
53+
httpClient, err := ClusterAwareHTTPClient(config)
54+
if err != nil {
55+
return nil, err
56+
}
57+
opts.HTTPClient = httpClient
58+
return cluster.DefaultNewClient(cache, config, opts, uncachedObjects...)
59+
}
60+
61+
// ClusterAwareHTTPClient returns an http.Client with a cluster aware round tripper.
62+
func ClusterAwareHTTPClient(config *rest.Config) (*http.Client, error) {
63+
httpClient, err := rest.HTTPClientFor(config)
64+
if err != nil {
65+
return nil, err
66+
}
67+
68+
httpClient.Transport = kcpclient.NewClusterRoundTripper(httpClient.Transport)
69+
return httpClient, nil
70+
}

0 commit comments

Comments
 (0)