-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
cluster.go
417 lines (377 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
package cluster
import (
"net/url"
"time"
"context"
"github.com/argoproj/gitops-engine/pkg/utils/kube"
log "github.com/sirupsen/logrus"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/client-go/kubernetes"
"github.com/argoproj/argo-cd/v2/pkg/apiclient/cluster"
appv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
servercache "github.com/argoproj/argo-cd/v2/server/cache"
"github.com/argoproj/argo-cd/v2/server/rbacpolicy"
"github.com/argoproj/argo-cd/v2/util/argo"
"github.com/argoproj/argo-cd/v2/util/clusterauth"
"github.com/argoproj/argo-cd/v2/util/db"
"github.com/argoproj/argo-cd/v2/util/rbac"
)
// Server provides a Cluster service
type Server struct {
db db.ArgoDB
enf *rbac.Enforcer
cache *servercache.Cache
kubectl kube.Kubectl
}
// NewServer returns a new instance of the Cluster service
func NewServer(db db.ArgoDB, enf *rbac.Enforcer, cache *servercache.Cache, kubectl kube.Kubectl) *Server {
return &Server{
db: db,
enf: enf,
cache: cache,
kubectl: kubectl,
}
}
func createRBACObject(project string, server string) string {
if project != "" {
return project + "/" + server
}
return server
}
// List returns list of clusters
func (s *Server) List(ctx context.Context, q *cluster.ClusterQuery) (*appv1.ClusterList, error) {
clusterList, err := s.db.ListClusters(ctx)
if err != nil {
return nil, err
}
items := make([]appv1.Cluster, 0)
for _, clust := range clusterList.Items {
if s.enf.Enforce(ctx.Value("claims"), rbacpolicy.ResourceClusters, rbacpolicy.ActionGet, createRBACObject(clust.Project, clust.Server)) {
items = append(items, clust)
}
}
err = kube.RunAllAsync(len(items), func(i int) error {
items[i] = *s.toAPIResponse(&items[i])
return nil
})
if err != nil {
return nil, err
}
clusterList.Items = items
return clusterList, nil
}
// Create creates a cluster
func (s *Server) Create(ctx context.Context, q *cluster.ClusterCreateRequest) (*appv1.Cluster, error) {
if err := s.enf.EnforceErr(ctx.Value("claims"), rbacpolicy.ResourceClusters, rbacpolicy.ActionCreate, createRBACObject(q.Cluster.Project, q.Cluster.Server)); err != nil {
return nil, err
}
c := q.Cluster
serverVersion, err := s.kubectl.GetServerVersion(c.RESTConfig())
if err != nil {
return nil, err
}
clust, err := s.db.CreateCluster(ctx, c)
if err != nil {
if status.Convert(err).Code() == codes.AlreadyExists {
// act idempotent if existing spec matches new spec
existing, getErr := s.db.GetCluster(ctx, c.Server)
if getErr != nil {
return nil, status.Errorf(codes.Internal, "unable to check existing cluster details: %v", getErr)
}
if existing.Equals(c) {
clust = existing
} else if q.Upsert {
return s.Update(ctx, &cluster.ClusterUpdateRequest{Cluster: c})
} else {
return nil, status.Errorf(codes.InvalidArgument, argo.GenerateSpecIsDifferentErrorMessage("cluster", existing, c))
}
} else {
return nil, err
}
}
err = s.cache.SetClusterInfo(c.Server, &appv1.ClusterInfo{
ServerVersion: serverVersion,
ConnectionState: appv1.ConnectionState{
Status: appv1.ConnectionStatusSuccessful,
ModifiedAt: &v1.Time{Time: time.Now()},
},
})
if err != nil {
return nil, err
}
return s.toAPIResponse(clust), err
}
// Get returns a cluster from a query
func (s *Server) Get(ctx context.Context, q *cluster.ClusterQuery) (*appv1.Cluster, error) {
c, err := s.getClusterWith403IfNotExist(ctx, q)
if err != nil {
return nil, err
}
if err := s.enf.EnforceErr(ctx.Value("claims"), rbacpolicy.ResourceClusters, rbacpolicy.ActionGet, createRBACObject(c.Project, q.Server)); err != nil {
return nil, err
}
return s.toAPIResponse(c), nil
}
func (s *Server) getClusterWith403IfNotExist(ctx context.Context, q *cluster.ClusterQuery) (*appv1.Cluster, error) {
repo, err := s.getCluster(ctx, q)
if err != nil || repo == nil {
return nil, status.Error(codes.PermissionDenied, "permission denied")
}
return repo, nil
}
func (s *Server) getCluster(ctx context.Context, q *cluster.ClusterQuery) (*appv1.Cluster, error) {
if q.Id != nil {
q.Server = ""
q.Name = ""
if q.Id.Type == "name" {
q.Name = q.Id.Value
} else if q.Id.Type == "name_escaped" {
nameUnescaped, err := url.QueryUnescape(q.Id.Value)
if err != nil {
return nil, err
}
q.Name = nameUnescaped
} else {
q.Server = q.Id.Value
}
}
if q.Server != "" {
c, err := s.db.GetCluster(ctx, q.Server)
if err != nil {
return nil, err
}
return c, nil
}
//we only get the name when we specify Name in ApplicationDestination and next
//we want to find the server in order to populate ApplicationDestination.Server
if q.Name != "" {
clusterList, err := s.db.ListClusters(ctx)
if err != nil {
return nil, err
}
for _, c := range clusterList.Items {
if c.Name == q.Name {
return &c, nil
}
}
}
return nil, nil
}
var clusterFieldsByPath = map[string]func(updated *appv1.Cluster, existing *appv1.Cluster){
"name": func(updated *appv1.Cluster, existing *appv1.Cluster) {
updated.Name = existing.Name
},
"namespaces": func(updated *appv1.Cluster, existing *appv1.Cluster) {
updated.Namespaces = existing.Namespaces
},
"config": func(updated *appv1.Cluster, existing *appv1.Cluster) {
updated.Config = existing.Config
},
"shard": func(updated *appv1.Cluster, existing *appv1.Cluster) {
updated.Shard = existing.Shard
},
"clusterResources": func(updated *appv1.Cluster, existing *appv1.Cluster) {
updated.ClusterResources = existing.ClusterResources
},
"labels": func(updated *appv1.Cluster, existing *appv1.Cluster) {
updated.Labels = existing.Labels
},
"annotations": func(updated *appv1.Cluster, existing *appv1.Cluster) {
updated.Annotations = existing.Annotations
},
"project": func(updated *appv1.Cluster, existing *appv1.Cluster) {
updated.Project = existing.Project
},
}
// Update updates a cluster
func (s *Server) Update(ctx context.Context, q *cluster.ClusterUpdateRequest) (*appv1.Cluster, error) {
c, err := s.getClusterWith403IfNotExist(ctx, &cluster.ClusterQuery{
Server: q.Cluster.Server,
Name: q.Cluster.Name,
Id: q.Id,
})
if err != nil {
return nil, err
}
// verify that user can do update inside project where cluster is located
if err := s.enf.EnforceErr(ctx.Value("claims"), rbacpolicy.ResourceClusters, rbacpolicy.ActionUpdate, createRBACObject(c.Project, q.Cluster.Server)); err != nil {
return nil, err
}
if len(q.UpdatedFields) == 0 || sets.NewString(q.UpdatedFields...).Has("project") {
// verify that user can do update inside project where cluster will be located
if err := s.enf.EnforceErr(ctx.Value("claims"), rbacpolicy.ResourceClusters, rbacpolicy.ActionUpdate, createRBACObject(q.Cluster.Project, q.Cluster.Server)); err != nil {
return nil, err
}
}
if len(q.UpdatedFields) != 0 {
for _, path := range q.UpdatedFields {
if updater, ok := clusterFieldsByPath[path]; ok {
updater(c, q.Cluster)
}
}
q.Cluster = c
}
// Test the token we just created before persisting it
serverVersion, err := s.kubectl.GetServerVersion(q.Cluster.RESTConfig())
if err != nil {
return nil, err
}
clust, err := s.db.UpdateCluster(ctx, q.Cluster)
if err != nil {
return nil, err
}
err = s.cache.SetClusterInfo(clust.Server, &appv1.ClusterInfo{
ServerVersion: serverVersion,
ConnectionState: appv1.ConnectionState{
Status: appv1.ConnectionStatusSuccessful,
ModifiedAt: &v1.Time{Time: time.Now()},
},
})
if err != nil {
return nil, err
}
return s.toAPIResponse(clust), nil
}
// Delete deletes a cluster by server/name
func (s *Server) Delete(ctx context.Context, q *cluster.ClusterQuery) (*cluster.ClusterResponse, error) {
c, err := s.getClusterWith403IfNotExist(ctx, q)
if err != nil {
return nil, err
}
if q.Name != "" {
servers, err := s.db.GetClusterServersByName(ctx, q.Name)
if err != nil {
return nil, err
}
for _, server := range servers {
if err := enforceAndDelete(s, ctx, server, c.Project); err != nil {
return nil, err
}
}
} else {
if err := enforceAndDelete(s, ctx, q.Server, c.Project); err != nil {
return nil, err
}
}
return &cluster.ClusterResponse{}, nil
}
func enforceAndDelete(s *Server, ctx context.Context, server, project string) error {
if err := s.enf.EnforceErr(ctx.Value("claims"), rbacpolicy.ResourceClusters, rbacpolicy.ActionDelete, createRBACObject(project, server)); err != nil {
return err
}
if err := s.db.DeleteCluster(ctx, server); err != nil {
return err
}
return nil
}
// RotateAuth rotates the bearer token used for a cluster
func (s *Server) RotateAuth(ctx context.Context, q *cluster.ClusterQuery) (*cluster.ClusterResponse, error) {
clust, err := s.getClusterWith403IfNotExist(ctx, q)
if err != nil {
return nil, err
}
var servers []string
if q.Name != "" {
servers, err = s.db.GetClusterServersByName(ctx, q.Name)
if err != nil {
return nil, status.Errorf(codes.NotFound, "failed to get cluster servers by name: %v", err)
}
for _, server := range servers {
if err := s.enf.EnforceErr(ctx.Value("claims"), rbacpolicy.ResourceClusters, rbacpolicy.ActionUpdate, createRBACObject(clust.Project, server)); err != nil {
return nil, status.Errorf(codes.PermissionDenied, "encountered permissions issue while processing request: %v", err)
}
}
} else {
if err := s.enf.EnforceErr(ctx.Value("claims"), rbacpolicy.ResourceClusters, rbacpolicy.ActionUpdate, createRBACObject(clust.Project, q.Server)); err != nil {
return nil, status.Errorf(codes.PermissionDenied, "encountered permissions issue while processing request: %v", err)
}
servers = append(servers, q.Server)
}
for _, server := range servers {
logCtx := log.WithField("cluster", server)
logCtx.Info("Rotating auth")
restCfg := clust.RESTConfig()
if restCfg.BearerToken == "" {
return nil, status.Errorf(codes.InvalidArgument, "Cluster '%s' does not use bearer token authentication", server)
}
claims, err := clusterauth.ParseServiceAccountToken(restCfg.BearerToken)
if err != nil {
return nil, err
}
kubeclientset, err := kubernetes.NewForConfig(restCfg)
if err != nil {
return nil, err
}
newSecret, err := clusterauth.GenerateNewClusterManagerSecret(kubeclientset, claims)
if err != nil {
return nil, err
}
// we are using token auth, make sure we don't store client-cert information
clust.Config.KeyData = nil
clust.Config.CertData = nil
clust.Config.BearerToken = string(newSecret.Data["token"])
// Test the token we just created before persisting it
serverVersion, err := s.kubectl.GetServerVersion(clust.RESTConfig())
if err != nil {
return nil, err
}
_, err = s.db.UpdateCluster(ctx, clust)
if err != nil {
return nil, err
}
err = s.cache.SetClusterInfo(clust.Server, &appv1.ClusterInfo{
ServerVersion: serverVersion,
ConnectionState: appv1.ConnectionState{
Status: appv1.ConnectionStatusSuccessful,
ModifiedAt: &v1.Time{Time: time.Now()},
},
})
if err != nil {
return nil, err
}
err = clusterauth.RotateServiceAccountSecrets(kubeclientset, claims, newSecret)
if err != nil {
return nil, err
}
logCtx.Infof("Rotated auth (old: %s, new: %s)", claims.SecretName, newSecret.Name)
}
return &cluster.ClusterResponse{}, nil
}
func (s *Server) toAPIResponse(clust *appv1.Cluster) *appv1.Cluster {
_ = s.cache.GetClusterInfo(clust.Server, &clust.Info)
clust.Config.Password = ""
clust.Config.BearerToken = ""
clust.Config.TLSClientConfig.KeyData = nil
if clust.Config.ExecProviderConfig != nil {
// We can't know what the user has put into args or
// env vars on the exec provider that might be sensitive
// (e.g. --private-key=XXX, PASSWORD=XXX)
// Implicitly assumes the command executable name is non-sensitive
clust.Config.ExecProviderConfig.Env = make(map[string]string)
clust.Config.ExecProviderConfig.Args = nil
}
// populate deprecated fields for backward compatibility
clust.ServerVersion = clust.Info.ServerVersion
clust.ConnectionState = clust.Info.ConnectionState
return clust
}
// InvalidateCache invalidates cluster cache
func (s *Server) InvalidateCache(ctx context.Context, q *cluster.ClusterQuery) (*appv1.Cluster, error) {
cls, err := s.getClusterWith403IfNotExist(ctx, q)
if err != nil {
return nil, err
}
if err := s.enf.EnforceErr(ctx.Value("claims"), rbacpolicy.ResourceClusters, rbacpolicy.ActionUpdate, createRBACObject(cls.Project, q.Server)); err != nil {
return nil, err
}
now := v1.Now()
cls.RefreshRequestedAt = &now
cls, err = s.db.UpdateCluster(ctx, cls)
if err != nil {
return nil, err
}
return s.toAPIResponse(cls), nil
}