-
Notifications
You must be signed in to change notification settings - Fork 5.3k
/
cluster.go
425 lines (386 loc) · 12.5 KB
/
cluster.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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
package db
import (
"context"
"encoding/json"
"fmt"
"strconv"
"strings"
"sync"
"time"
log "github.com/sirupsen/logrus"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
apiv1 "k8s.io/api/core/v1"
apierr "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/utils/pointer"
"github.com/argoproj/argo-cd/v2/common"
appv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
"github.com/argoproj/argo-cd/v2/util/collections"
"github.com/argoproj/argo-cd/v2/util/settings"
)
var (
localCluster = appv1.Cluster{
Name: "in-cluster",
Server: appv1.KubernetesInternalAPIServerAddr,
ConnectionState: appv1.ConnectionState{Status: appv1.ConnectionStatusSuccessful},
}
initLocalCluster sync.Once
)
func (db *db) getLocalCluster() *appv1.Cluster {
initLocalCluster.Do(func() {
info, err := db.kubeclientset.Discovery().ServerVersion()
if err == nil {
localCluster.ServerVersion = fmt.Sprintf("%s.%s", info.Major, info.Minor)
localCluster.ConnectionState = appv1.ConnectionState{Status: appv1.ConnectionStatusSuccessful}
} else {
localCluster.ConnectionState = appv1.ConnectionState{
Status: appv1.ConnectionStatusFailed,
Message: err.Error(),
}
}
})
cluster := localCluster.DeepCopy()
now := metav1.Now()
cluster.ConnectionState.ModifiedAt = &now
return cluster
}
// ListClusters returns list of clusters
func (db *db) ListClusters(ctx context.Context) (*appv1.ClusterList, error) {
clusterSecrets, err := db.listSecretsByType(common.LabelValueSecretTypeCluster)
if err != nil {
return nil, err
}
clusterList := appv1.ClusterList{
Items: make([]appv1.Cluster, 0),
}
settings, err := db.settingsMgr.GetSettings()
if err != nil {
return nil, err
}
inClusterEnabled := settings.InClusterEnabled
hasInClusterCredentials := false
for _, clusterSecret := range clusterSecrets {
cluster, err := secretToCluster(clusterSecret)
if err != nil {
log.Errorf("could not unmarshal cluster secret %s", clusterSecret.Name)
continue
}
if cluster.Server == appv1.KubernetesInternalAPIServerAddr {
if inClusterEnabled {
hasInClusterCredentials = true
clusterList.Items = append(clusterList.Items, *cluster)
} else {
log.Errorf("failed to add cluster %q to cluster list: in-cluster server address is disabled in Argo CD settings", cluster.Name)
}
} else {
clusterList.Items = append(clusterList.Items, *cluster)
}
}
if inClusterEnabled && !hasInClusterCredentials {
clusterList.Items = append(clusterList.Items, *db.getLocalCluster())
}
return &clusterList, nil
}
// CreateCluster creates a cluster
func (db *db) CreateCluster(ctx context.Context, c *appv1.Cluster) (*appv1.Cluster, error) {
settings, err := db.settingsMgr.GetSettings()
if err != nil {
return nil, err
}
if c.Server == appv1.KubernetesInternalAPIServerAddr && !settings.InClusterEnabled {
return nil, status.Errorf(codes.InvalidArgument, "cannot register cluster: in-cluster has been disabled")
}
secName, err := URIToSecretName("cluster", c.Server)
if err != nil {
return nil, err
}
clusterSecret := &apiv1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: secName,
},
}
if err = clusterToSecret(c, clusterSecret); err != nil {
return nil, err
}
clusterSecret, err = db.createSecret(ctx, clusterSecret)
if err != nil {
if apierr.IsAlreadyExists(err) {
return nil, status.Errorf(codes.AlreadyExists, "cluster %q already exists", c.Server)
}
return nil, err
}
cluster, err := secretToCluster(clusterSecret)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "could not unmarshal cluster secret %s", clusterSecret.Name)
}
return cluster, db.settingsMgr.ResyncInformers()
}
// ClusterEvent contains information about cluster event
type ClusterEvent struct {
Type watch.EventType
Cluster *appv1.Cluster
}
func (db *db) WatchClusters(ctx context.Context,
handleAddEvent func(cluster *appv1.Cluster),
handleModEvent func(oldCluster *appv1.Cluster, newCluster *appv1.Cluster),
handleDeleteEvent func(clusterServer string)) error {
localCls, err := db.GetCluster(ctx, appv1.KubernetesInternalAPIServerAddr)
if err != nil {
return err
}
handleAddEvent(localCls)
db.watchSecrets(
ctx,
common.LabelValueSecretTypeCluster,
func(secret *apiv1.Secret) {
cluster, err := secretToCluster(secret)
if err != nil {
log.Errorf("could not unmarshal cluster secret %s", secret.Name)
return
}
if cluster.Server == appv1.KubernetesInternalAPIServerAddr {
// change local cluster event to modified or deleted, since it cannot be re-added or deleted
handleModEvent(localCls, cluster)
localCls = cluster
return
}
handleAddEvent(cluster)
},
func(oldSecret *apiv1.Secret, newSecret *apiv1.Secret) {
oldCluster, err := secretToCluster(oldSecret)
if err != nil {
log.Errorf("could not unmarshal cluster secret %s", oldSecret.Name)
return
}
newCluster, err := secretToCluster(newSecret)
if err != nil {
log.Errorf("could not unmarshal cluster secret %s", newSecret.Name)
return
}
if newCluster.Server == appv1.KubernetesInternalAPIServerAddr {
localCls = newCluster
}
handleModEvent(oldCluster, newCluster)
},
func(secret *apiv1.Secret) {
if string(secret.Data["server"]) == appv1.KubernetesInternalAPIServerAddr {
// change local cluster event to modified or deleted, since it cannot be re-added or deleted
handleModEvent(localCls, db.getLocalCluster())
localCls = db.getLocalCluster()
} else {
handleDeleteEvent(string(secret.Data["server"]))
}
},
)
return err
}
func (db *db) getClusterSecret(server string) (*apiv1.Secret, error) {
clusterSecrets, err := db.listSecretsByType(common.LabelValueSecretTypeCluster)
if err != nil {
return nil, err
}
srv := strings.TrimRight(server, "/")
for _, clusterSecret := range clusterSecrets {
if strings.TrimRight(string(clusterSecret.Data["server"]), "/") == srv {
return clusterSecret, nil
}
}
return nil, status.Errorf(codes.NotFound, "cluster %q not found", server)
}
// GetCluster returns a cluster from a query
func (db *db) GetCluster(_ context.Context, server string) (*appv1.Cluster, error) {
informer, err := db.settingsMgr.GetSecretsInformer()
if err != nil {
return nil, err
}
res, err := informer.GetIndexer().ByIndex(settings.ByClusterURLIndexer, server)
if err != nil {
return nil, err
}
if len(res) > 0 {
return secretToCluster(res[0].(*apiv1.Secret))
}
if server == appv1.KubernetesInternalAPIServerAddr {
return db.getLocalCluster(), nil
}
return nil, status.Errorf(codes.NotFound, "cluster %q not found", server)
}
// GetProjectClusters return project scoped clusters by given project name
func (db *db) GetProjectClusters(ctx context.Context, project string) ([]*appv1.Cluster, error) {
informer, err := db.settingsMgr.GetSecretsInformer()
if err != nil {
return nil, fmt.Errorf("failed to get secrets informer: %w", err)
}
secrets, err := informer.GetIndexer().ByIndex(settings.ByProjectClusterIndexer, project)
if err != nil {
return nil, fmt.Errorf("failed to get index by project cluster indexer for project %q: %w", project, err)
}
var res []*appv1.Cluster
for i := range secrets {
cluster, err := secretToCluster(secrets[i].(*apiv1.Secret))
if err != nil {
return nil, fmt.Errorf("failed to convert secret to cluster: %w", err)
}
res = append(res, cluster)
}
return res, nil
}
func (db *db) GetClusterServersByName(ctx context.Context, name string) ([]string, error) {
informer, err := db.settingsMgr.GetSecretsInformer()
if err != nil {
return nil, err
}
// if local cluster name is not overridden and specified name is local cluster name, return local cluster server
localClusterSecrets, err := informer.GetIndexer().ByIndex(settings.ByClusterURLIndexer, appv1.KubernetesInternalAPIServerAddr)
if err != nil {
return nil, err
}
if len(localClusterSecrets) == 0 && db.getLocalCluster().Name == name {
return []string{appv1.KubernetesInternalAPIServerAddr}, nil
}
secrets, err := informer.GetIndexer().ByIndex(settings.ByClusterNameIndexer, name)
if err != nil {
return nil, err
}
var res []string
for i := range secrets {
s := secrets[i].(*apiv1.Secret)
res = append(res, strings.TrimRight(string(s.Data["server"]), "/"))
}
return res, nil
}
// UpdateCluster updates a cluster
func (db *db) UpdateCluster(ctx context.Context, c *appv1.Cluster) (*appv1.Cluster, error) {
clusterSecret, err := db.getClusterSecret(c.Server)
if err != nil {
if status.Code(err) == codes.NotFound {
return db.CreateCluster(ctx, c)
}
return nil, err
}
if err := clusterToSecret(c, clusterSecret); err != nil {
return nil, err
}
clusterSecret, err = db.kubeclientset.CoreV1().Secrets(db.ns).Update(ctx, clusterSecret, metav1.UpdateOptions{})
if err != nil {
return nil, err
}
cluster, err := secretToCluster(clusterSecret)
if err != nil {
log.Errorf("could not unmarshal cluster secret %s", clusterSecret.Name)
return nil, err
}
return cluster, db.settingsMgr.ResyncInformers()
}
// DeleteCluster deletes a cluster by name
func (db *db) DeleteCluster(ctx context.Context, server string) error {
secret, err := db.getClusterSecret(server)
if err != nil {
return err
}
err = db.deleteSecret(ctx, secret)
if err != nil {
return err
}
return db.settingsMgr.ResyncInformers()
}
// clusterToData converts a cluster object to string data for serialization to a secret
func clusterToSecret(c *appv1.Cluster, secret *apiv1.Secret) error {
data := make(map[string][]byte)
data["server"] = []byte(strings.TrimRight(c.Server, "/"))
if c.Name == "" {
data["name"] = []byte(c.Server)
} else {
data["name"] = []byte(c.Name)
}
if len(c.Namespaces) != 0 {
data["namespaces"] = []byte(strings.Join(c.Namespaces, ","))
}
configBytes, err := json.Marshal(c.Config)
if err != nil {
return err
}
data["config"] = configBytes
if c.Shard != nil {
data["shard"] = []byte(strconv.Itoa(int(*c.Shard)))
}
if c.ClusterResources {
data["clusterResources"] = []byte("true")
}
if c.Project != "" {
data["project"] = []byte(c.Project)
}
secret.Data = data
secret.Labels = c.Labels
secret.Annotations = c.Annotations
if secret.Annotations == nil {
secret.Annotations = make(map[string]string)
}
if c.RefreshRequestedAt != nil {
secret.Annotations[appv1.AnnotationKeyRefresh] = c.RefreshRequestedAt.Format(time.RFC3339)
} else {
delete(secret.Annotations, appv1.AnnotationKeyRefresh)
}
addSecretMetadata(secret, common.LabelValueSecretTypeCluster)
return nil
}
// secretToCluster converts a secret into a Cluster object
func secretToCluster(s *apiv1.Secret) (*appv1.Cluster, error) {
var config appv1.ClusterConfig
if len(s.Data["config"]) > 0 {
err := json.Unmarshal(s.Data["config"], &config)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal cluster config: %w", err)
}
}
var namespaces []string
for _, ns := range strings.Split(string(s.Data["namespaces"]), ",") {
if ns = strings.TrimSpace(ns); ns != "" {
namespaces = append(namespaces, ns)
}
}
var refreshRequestedAt *metav1.Time
if v, found := s.Annotations[appv1.AnnotationKeyRefresh]; found {
requestedAt, err := time.Parse(time.RFC3339, v)
if err != nil {
log.Warnf("Error while parsing date in cluster secret '%s': %v", s.Name, err)
} else {
refreshRequestedAt = &metav1.Time{Time: requestedAt}
}
}
var shard *int64
if shardStr := s.Data["shard"]; shardStr != nil {
if val, err := strconv.Atoi(string(shardStr)); err != nil {
log.Warnf("Error while parsing shard in cluster secret '%s': %v", s.Name, err)
} else {
shard = pointer.Int64Ptr(int64(val))
}
}
// copy labels and annotations excluding system ones
labels := map[string]string{}
if s.Labels != nil {
labels = collections.CopyStringMap(s.Labels)
delete(labels, common.LabelKeySecretType)
}
annotations := map[string]string{}
if s.Annotations != nil {
annotations = collections.CopyStringMap(s.Annotations)
delete(annotations, common.AnnotationKeyManagedBy)
}
cluster := appv1.Cluster{
ID: string(s.UID),
Server: strings.TrimRight(string(s.Data["server"]), "/"),
Name: string(s.Data["name"]),
Namespaces: namespaces,
ClusterResources: string(s.Data["clusterResources"]) == "true",
Config: config,
RefreshRequestedAt: refreshRequestedAt,
Shard: shard,
Project: string(s.Data["project"]),
Labels: labels,
Annotations: annotations,
}
return &cluster, nil
}