1
0
mirror of https://github.com/rancher/steve.git synced 2025-06-24 14:02:04 +00:00
steve/pkg/client/factory.go

76 lines
1.9 KiB
Go
Raw Normal View History

2019-08-04 17:41:32 +00:00
package client
import (
2020-02-03 21:28:25 +00:00
"fmt"
2020-02-02 05:13:32 +00:00
"time"
2019-09-11 21:05:00 +00:00
"github.com/rancher/steve/pkg/attributes"
2020-01-31 05:37:59 +00:00
"github.com/rancher/steve/pkg/schemaserver/types"
2020-02-03 21:28:25 +00:00
"k8s.io/apiserver/pkg/endpoints/request"
2019-08-04 17:41:32 +00:00
"k8s.io/client-go/dynamic"
"k8s.io/client-go/rest"
)
type Factory struct {
2020-02-03 21:28:25 +00:00
impersonate bool
clientCfg *rest.Config
watchClientCfg *rest.Config
client dynamic.Interface
Config *rest.Config
2019-08-04 17:41:32 +00:00
}
2020-02-03 21:28:25 +00:00
func NewFactory(cfg *rest.Config, impersonate bool) (*Factory, error) {
clientCfg := rest.CopyConfig(cfg)
clientCfg.QPS = 10000
clientCfg.Burst = 100
watchClientCfg := rest.CopyConfig(cfg)
watchClientCfg.Timeout = 30 * time.Minute
2020-02-02 05:13:32 +00:00
2020-02-03 21:28:25 +00:00
dc, err := dynamic.NewForConfig(watchClientCfg)
2020-02-02 05:13:32 +00:00
if err != nil {
return nil, err
}
2020-02-03 21:28:25 +00:00
2019-08-04 17:41:32 +00:00
return &Factory{
2020-02-03 21:28:25 +00:00
client: dc,
impersonate: impersonate,
clientCfg: clientCfg,
watchClientCfg: watchClientCfg,
Config: watchClientCfg,
2019-08-04 17:41:32 +00:00
}, nil
}
2019-09-09 21:28:55 +00:00
func (p *Factory) DynamicClient() dynamic.Interface {
return p.client
}
2020-01-31 05:37:59 +00:00
func (p *Factory) Client(ctx *types.APIRequest, s *types.APISchema, namespace string) (dynamic.ResourceInterface, error) {
2020-02-03 21:28:25 +00:00
return p.newClient(ctx, p.clientCfg, s, namespace)
2019-08-04 17:41:32 +00:00
}
2020-02-02 05:13:32 +00:00
func (p *Factory) ClientForWatch(ctx *types.APIRequest, s *types.APISchema, namespace string) (dynamic.ResourceInterface, error) {
2020-02-03 21:28:25 +00:00
return p.newClient(ctx, p.watchClientCfg, s, namespace)
}
func (p *Factory) newClient(ctx *types.APIRequest, cfg *rest.Config, s *types.APISchema, namespace string) (dynamic.ResourceInterface, error) {
if p.impersonate {
user, ok := request.UserFrom(ctx.Context())
if !ok {
return nil, fmt.Errorf("user not found for impersonation")
}
cfg = rest.CopyConfig(cfg)
cfg.Impersonate.UserName = user.GetName()
cfg.Impersonate.Groups = user.GetGroups()
cfg.Impersonate.Extra = user.GetExtra()
}
client, err := dynamic.NewForConfig(cfg)
if err != nil {
return nil, err
}
2020-02-02 05:13:32 +00:00
gvr := attributes.GVR(s)
2020-02-03 21:28:25 +00:00
return client.Resource(gvr).Namespace(namespace), nil
2020-02-02 05:13:32 +00:00
}