forked from rancher/rancher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
factory.go
77 lines (63 loc) · 1.93 KB
/
factory.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package clusterrouter
import (
"net/http"
"sync"
"github.com/docker/docker/pkg/locker"
"github.com/rancher/rancher/pkg/clusterrouter/proxy"
"github.com/rancher/types/apis/management.cattle.io/v3"
"github.com/rancher/types/config/dialer"
"k8s.io/client-go/rest"
)
type factory struct {
dialerFactory dialer.Factory
clusterLookup ClusterLookup
clusterLister v3.ClusterLister
clusters sync.Map
serverLock *locker.Locker
servers sync.Map
localConfig *rest.Config
}
func newFactory(localConfig *rest.Config, dialer dialer.Factory, lookup ClusterLookup, clusterLister v3.ClusterLister) *factory {
return &factory{
dialerFactory: dialer,
serverLock: locker.New(),
clusterLookup: lookup,
clusterLister: clusterLister,
localConfig: localConfig,
}
}
func (s *factory) lookupCluster(clusterID string) (*v3.Cluster, http.Handler) {
srv, ok := s.servers.Load(clusterID)
if ok {
if cluster, ok := s.clusters.Load(clusterID); ok {
return cluster.(*v3.Cluster), srv.(server).Handler()
}
}
return nil, nil
}
func (s *factory) get(req *http.Request) (*v3.Cluster, http.Handler, error) {
cluster, err := s.clusterLookup.Lookup(req)
if err != nil || cluster == nil {
return nil, nil, err
}
clusterID := cluster.Name
if newCluster, handler := s.lookupCluster(clusterID); newCluster != nil {
return newCluster, handler, nil
}
s.serverLock.Lock("cluster." + clusterID)
defer s.serverLock.Unlock("cluster." + clusterID)
if newCluster, handler := s.lookupCluster(clusterID); newCluster != nil {
return newCluster, handler, nil
}
var srv interface{}
srv, err = s.newServer(cluster)
if err != nil || srv == nil {
return nil, nil, err
}
srv, _ = s.servers.LoadOrStore(cluster.Name, srv)
s.clusters.LoadOrStore(cluster.Name, cluster)
return cluster, srv.(server).Handler(), nil
}
func (s *factory) newServer(c *v3.Cluster) (server, error) {
return proxy.New(s.localConfig, c, s.clusterLister, s.dialerFactory)
}