/
connections.go
236 lines (216 loc) · 6.96 KB
/
connections.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
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
// Copyright 2024 SAP SE
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package clusters
import (
"context"
"fmt"
"sync"
"time"
"github.com/go-logr/logr"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/informers"
corev1_informers "k8s.io/client-go/informers/core/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"sigs.k8s.io/controller-runtime/pkg/client"
)
// The purpose of the Connection and ClusterConnections types is to manage
// connections to workload clusters, which are baked by expiring authentication.
// MakeClient creates a kubernetes client for the given workload cluster.
// The client is created using the kubeconfig secret of the workload cluster,
// which is fetched from the management cluster using client.
func MakeClient(ctx context.Context, client client.Client, cluster types.NamespacedName) (kubernetes.Interface, error) {
secretKey := types.NamespacedName{Namespace: cluster.Namespace, Name: cluster.Name + "-kubeconfig"}
var kubeConfigSecret corev1.Secret
if err := client.Get(ctx, secretKey, &kubeConfigSecret); err != nil {
return nil, err
}
kubeconfig, ok := kubeConfigSecret.Data["value"]
if !ok {
return nil, fmt.Errorf("secret %s has no value key", cluster.String())
}
restConfig, err := clientcmd.RESTConfigFromKubeConfig(kubeconfig)
if err != nil {
return nil, fmt.Errorf("failed to load workload cluster %s kubeconfig: %w", cluster.String(), err)
}
clientset, err := kubernetes.NewForConfig(restConfig)
if err != nil {
return nil, fmt.Errorf("failed to create clientset workload cluster %s: %w", cluster.String(), err)
}
return clientset, nil
}
// Connection is a connection to a workload cluster.
// A connection can be shared between multiple controllers.
type Connection struct {
client kubernetes.Interface
nodeInformer corev1_informers.NodeInformer
factory informers.SharedInformerFactory
nodeAttacher func(ni corev1_informers.NodeInformer)
cancel context.CancelFunc
}
// NewConnection creates a new connection to a workload cluster.
// The nodeAttacher function is called when the connection is started.
// It's purpose is to attach reconciliation loops to the node informer.
func NewConnection(client kubernetes.Interface, nodeAttacher func(ni corev1_informers.NodeInformer)) *Connection {
factory := informers.NewSharedInformerFactory(client, time.Minute)
informer := factory.Core().V1().Nodes()
return &Connection{
client: client,
nodeInformer: informer,
factory: factory,
nodeAttacher: nodeAttacher,
}
}
func (conn *Connection) Start(ctx context.Context) {
if conn.nodeAttacher != nil {
conn.nodeAttacher(conn.nodeInformer)
}
cancelable, cancel := context.WithCancel(ctx)
conn.cancel = cancel
conn.factory.Start(cancelable.Done())
conn.factory.WaitForCacheSync(cancelable.Done())
}
func (conn *Connection) Shutdown() {
conn.cancel()
conn.factory.Shutdown()
}
// Connections is a collection of connections to workload clusters.
// It providers wrappers for getting and patching nodes in workload clusters
// that automatically recreate connections when the authentication expires.
type Connections struct {
clusters map[types.NamespacedName]*Connection
mutex sync.Mutex
managementClient client.Client
makeContext func() context.Context
}
func NewConnections(client client.Client, contextFactory func() context.Context) *Connections {
return &Connections{
clusters: make(map[types.NamespacedName]*Connection),
mutex: sync.Mutex{},
managementClient: client,
makeContext: contextFactory,
}
}
func (cc *Connections) AddConn(ctx context.Context, log logr.Logger, cluster types.NamespacedName, conn *Connection) {
cc.mutex.Lock()
defer cc.mutex.Unlock()
if old, ok := cc.clusters[cluster]; ok {
log.Info("shutting done old connection")
old.Shutdown()
}
cc.clusters[cluster] = conn
log.Info("starting new connection")
conn.Start(ctx)
log.Info("started new connection")
}
func (cc *Connections) GetConn(cluster types.NamespacedName) *Connection {
cc.mutex.Lock()
defer cc.mutex.Unlock()
if conn, ok := cc.clusters[cluster]; ok {
return conn
}
return nil
}
func (cc *Connections) DeleteConn(log logr.Logger, cluster types.NamespacedName) {
cc.mutex.Lock()
defer cc.mutex.Unlock()
if old, ok := cc.clusters[cluster]; ok {
log.Info("shutting done old connection for deletion")
old.Shutdown()
}
delete(cc.clusters, cluster)
}
type ReauthParams struct {
Cluster types.NamespacedName
Log logr.Logger
}
func (cc *Connections) ReauthConn(ctx context.Context, params ReauthParams) error {
conn := cc.GetConn(params.Cluster)
params.Log.Info("trying reauth", "cluster", params.Cluster)
workloadClient, err := MakeClient(ctx, cc.managementClient, params.Cluster)
if err != nil {
return err
}
attacher := conn.nodeAttacher
conn = NewConnection(workloadClient, attacher)
cc.AddConn(cc.makeContext(), params.Log, params.Cluster, conn)
return nil
}
type GetNodeParams struct {
Log logr.Logger
Cluster types.NamespacedName
Name string
}
func (cc *Connections) GetNode(ctx context.Context, params GetNodeParams) (*corev1.Node, error) {
conn := cc.GetConn(params.Cluster)
if conn == nil {
return nil, fmt.Errorf("no connection for cluster %s", params.Cluster)
}
node, err := conn.nodeInformer.Lister().Get(params.Name)
if err == nil {
return node, nil
}
if !errors.IsUnauthorized(err) {
return nil, err
}
if err = cc.ReauthConn(ctx, ReauthParams{
Cluster: params.Cluster,
Log: params.Log,
}); err != nil {
return nil, err
}
return conn.nodeInformer.Lister().Get(params.Name)
}
type PatchNodeParams struct {
Log logr.Logger
Cluster types.NamespacedName
Name string
MergePatch []byte
}
func (cc *Connections) PatchNode(ctx context.Context, params PatchNodeParams) error {
conn := cc.GetConn(params.Cluster)
if conn == nil {
return fmt.Errorf("no connection for cluster %s", params.Cluster)
}
_, err := conn.client.CoreV1().Nodes().Patch(
ctx,
params.Name,
types.MergePatchType,
params.MergePatch,
v1.PatchOptions{},
)
if err == nil {
return nil
}
if !errors.IsUnauthorized(err) {
return err
}
if err = cc.ReauthConn(ctx, ReauthParams{
Cluster: params.Cluster,
Log: params.Log,
}); err != nil {
return err
}
_, err = conn.client.CoreV1().Nodes().Patch(
ctx,
params.Name,
types.MergePatchType,
params.MergePatch,
v1.PatchOptions{},
)
return err
}