/
client.go
62 lines (51 loc) · 1.56 KB
/
client.go
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
package proxy
import (
"fmt"
"github.com/rancher/norman/v2/pkg/httperror"
"github.com/rancher/norman/v2/pkg/types"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apiserver/pkg/endpoints/request"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/rest"
)
type ClientFactory struct {
cfg rest.Config
idToGVR map[string]schema.GroupVersionResource
}
func NewClientFactory(cfg *rest.Config) *ClientFactory {
return &ClientFactory{
cfg: *cfg,
idToGVR: map[string]schema.GroupVersionResource{},
}
}
func (p *ClientFactory) Register(schema *types.Schema, gvr schema.GroupVersionResource) {
p.idToGVR[schema.ID] = gvr
schema.Store = NewProxyStore(p)
schema.Mapper = AddAPIVersionKind{
APIVersion: fmt.Sprintf("%s/%s", gvr.Group, gvr.Version),
Kind: schema.CodeName,
Next: schema.Mapper,
}
}
func (p *ClientFactory) Client(ctx *types.APIRequest, schema *types.Schema) (dynamic.ResourceInterface, error) {
gvr, ok := p.idToGVR[schema.ID]
if !ok {
return nil, httperror.NewAPIError(httperror.NotFound, "Failed to find client for "+schema.ID)
}
user, ok := request.UserFrom(ctx.Request.Context())
if !ok {
return nil, fmt.Errorf("failed to find user context for client")
}
newCfg := p.cfg
newCfg.Impersonate.UserName = user.GetName()
newCfg.Impersonate.Groups = user.GetGroups()
newCfg.Impersonate.Extra = user.GetExtra()
client, err := dynamic.NewForConfig(&newCfg)
if err != nil {
return nil, err
}
if len(ctx.Namespaces) > 0 {
return client.Resource(gvr).Namespace(ctx.Namespaces[0]), nil
}
return client.Resource(gvr), nil
}