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
package kcpclients
import (
"errors"
"fmt"
"sync"
"k8s.io/client-go/rest"
"github.com/johnandersen777/socialweb-computer-kcp/internal/component"
"github.com/johnandersen777/socialweb-computer-kcp/internal/kcplibs/common/ref"
"github.com/johnandersen777/socialweb-computer-kcp/internal/kcplibs/impl/kcpstore"
"github.com/johnandersen777/socialweb-computer-kcp/internal/kcpserver"
)
type Set struct {
mu sync.RWMutex
base *rest.Config
configs map[string]*rest.Config
}
var _ component.KCPClients = (*Set)(nil)
func New(cfg *rest.Config) (*Set, error) {
base, err := kcpConfig(cfg)
if err != nil {
return nil, err
}
return &Set{base: base, configs: map[string]*rest.Config{}}, nil
}
func FromStore(store *kcpstore.Store) (*Set, error) {
if store == nil {
return nil, errors.New("kcpclients: the kcp clients need a kcp store")
}
return New(store.Config())
}
func FromKubeconfig(kubeconfig string) (*Set, error) {
if kubeconfig == "" {
return nil, errors.New("kcpclients: the kcp clients need a kubeconfig")
}
cfg, err := kcpserver.FrontRestConfig(kubeconfig)
if err != nil {
return nil, fmt.Errorf("kcpclients: the kcp front rest config: %w", err)
}
return New(cfg)
}
func (s *Set) Set(workspace string, cfg *rest.Config) error {
if s == nil {
return errors.New("kcpclients: the kcp client set is nil")
}
normalized, err := kcpConfig(cfg)
if err != nil {
return err
}
workspace = kcpWorkspace(workspace)
s.mu.Lock()
defer s.mu.Unlock()
if s.configs == nil {
s.configs = map[string]*rest.Config{}
}
s.configs[workspace] = normalized
return nil
}
func (s *Set) Client(workspace string) (component.KCPClient, error) {
if s == nil {
return nil, errors.New("kcpclients: the kcp client set is nil")
}
workspace = kcpWorkspace(workspace)
s.mu.RLock()
cfg := s.configs[workspace]
base := s.base
s.mu.RUnlock()
if cfg == nil {
cfg = base
}
if cfg == nil {
return nil, errors.New("kcpclients: the kcp client set has no rest config")
}
return &kcpClient{workspace: workspace, cfg: rest.CopyConfig(cfg)}, nil
}
type kcpClient struct {
workspace string
cfg *rest.Config
}
func (c *kcpClient) Workspace() string { return c.workspace }
func (c *kcpClient) RESTConfig() *rest.Config { return rest.CopyConfig(c.cfg) }
func kcpConfig(cfg *rest.Config) (*rest.Config, error) {
if cfg == nil {
return nil, errors.New("kcpclients: the kcp clients need a rest config")
}
out := rest.CopyConfig(cfg)
out.Host = ref.BaseHost(out.Host)
if out.Host == "" {
return nil, errors.New("kcpclients: the kcp rest config has no host")
}
return out, nil
}
func kcpWorkspace(workspace string) string {
if workspace == "" {
return "root"
}
return workspace
}