/
manager_common_updater.go
333 lines (286 loc) · 9.42 KB
/
manager_common_updater.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
// Copyright © 2018 Banzai Cloud
//
// 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 cluster
import (
"context"
"fmt"
"strings"
"emperror.dev/errors"
"go.uber.org/cadence/client"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/kubernetes"
"github.com/banzaicloud/pipeline/internal/global"
"github.com/banzaicloud/pipeline/pkg/cluster"
pkgCommon "github.com/banzaicloud/pipeline/pkg/common"
"github.com/banzaicloud/pipeline/pkg/k8sclient"
"github.com/banzaicloud/pipeline/pkg/kubernetes/custom/npls"
"github.com/banzaicloud/pipeline/pkg/sdk/brn"
)
// DynamicClientFactory returns a dynamic Kubernetes client.
type DynamicClientFactory interface {
// FromSecret creates a Kubernetes client for a cluster from a secret.
FromSecret(ctx context.Context, secretID string) (dynamic.Interface, error)
}
type commonUpdater struct {
request *cluster.UpdateClusterRequest
clientFactory DynamicClientFactory
cluster CommonCluster
userID uint
clusterPropertiesChanged bool
workflowClient client.Client
externalBaseURL string
externalBaseURLInsecure bool
helmService HelmService
}
type commonUpdateValidationError struct {
msg string
invalidRequest bool
preconditionFailed bool
}
func (e *commonUpdateValidationError) Error() string {
return e.msg
}
func (e *commonUpdateValidationError) IsInvalid() bool {
return e.invalidRequest
}
func (e *commonUpdateValidationError) IsPreconditionFailed() bool {
return e.preconditionFailed
}
// NewCommonClusterUpdater returns a new cluster creator instance.
func NewCommonClusterUpdater(
request *cluster.UpdateClusterRequest,
clientFactory DynamicClientFactory,
cluster CommonCluster,
userID uint,
workflowClient client.Client,
externalBaseURL string,
externalBaseURLInsecure bool,
helmService HelmService,
) *commonUpdater {
return &commonUpdater{
request: request,
clientFactory: clientFactory,
cluster: cluster,
userID: userID,
workflowClient: workflowClient,
externalBaseURL: externalBaseURL,
externalBaseURLInsecure: externalBaseURLInsecure,
helmService: helmService,
}
}
// Validate implements the clusterUpdater interface.
func (c *commonUpdater) Validate(ctx context.Context) error {
if c.cluster.GetCloud() != c.request.Cloud {
return &commonUpdateValidationError{
msg: fmt.Sprintf("cloud provider [%s] does not match the cluster's cloud provider [%s]", c.request.Cloud, c.cluster.GetCloud()),
invalidRequest: true,
}
}
status, err := c.cluster.GetStatus()
if err != nil {
return errors.WrapIf(err, "could not get cluster status")
}
if status.Status != cluster.Running && status.Status != cluster.Warning {
return errors.WithDetails(
&commonUpdateValidationError{
msg: fmt.Sprintf("cluster is not in %s or %s state yet", cluster.Running, cluster.Warning),
preconditionFailed: true,
},
"status", status.Status,
)
}
return nil
}
// Prepare implements the clusterUpdater interface.
func (c *commonUpdater) Prepare(ctx context.Context) (CommonCluster, error) {
c.cluster.AddDefaultsToUpdate(c.request)
c.clusterPropertiesChanged = true
if err := c.cluster.CheckEqualityToUpdate(c.request); err != nil {
c.clusterPropertiesChanged = false
return nil, &commonUpdateValidationError{
msg: err.Error(),
invalidRequest: true,
}
}
if err := c.request.Validate(); err != nil {
return nil, &commonUpdateValidationError{
msg: err.Error(),
invalidRequest: true,
}
}
if err := c.cluster.SetStatus(cluster.Updating, cluster.UpdatingMessage); err != nil {
return nil, err
}
return c.cluster, c.cluster.Persist()
}
func buildNodePoolsLabelList(commonCluster CommonCluster, updateRequest *cluster.UpdateClusterRequest) ([]NodePoolLabels, error) {
// we need to retrieve existing node pools, as update request doesn't necessary contains instanceType, spot price etc.
clStatus, err := commonCluster.GetStatus()
if err != nil {
return nil, err
}
existingNodePoolMap := clStatus.NodePools
nodePools := make([]NodePoolLabels, 0)
cloudType := updateRequest.Cloud
if updateRequest.PKE != nil {
for name, np := range updateRequest.PKE.NodePools {
npls := NodePoolLabels{
NodePoolName: name,
Existing: false,
InstanceType: np.InstanceType,
SpotPrice: np.SpotPrice,
CustomLabels: np.Labels,
}
existingNodePool, ok := existingNodePoolMap[name]
if ok {
npls.Existing = true
npls.InstanceType = existingNodePool.InstanceType
npls.SpotPrice = existingNodePool.SpotPrice
}
nodePools = append(nodePools, npls)
}
return nodePools, nil
}
switch cloudType {
case cluster.Azure:
for name, np := range updateRequest.AKS.NodePools {
if np != nil {
npls := NodePoolLabels{
NodePoolName: name,
Existing: false,
CustomLabels: np.Labels,
}
existingNodePool, ok := existingNodePoolMap[name]
if ok {
npls.Existing = true
npls.InstanceType = existingNodePool.InstanceType
}
nodePools = append(nodePools, npls)
}
}
case cluster.Google:
for name, np := range updateRequest.GKE.NodePools {
if np != nil {
npls := NodePoolLabels{
NodePoolName: name,
Existing: false,
InstanceType: np.NodeInstanceType,
Preemptible: np.Preemptible,
CustomLabels: np.Labels,
}
existingNodePool, ok := existingNodePoolMap[name]
if ok {
npls.Existing = true
npls.InstanceType = existingNodePool.InstanceType
npls.Preemptible = existingNodePool.Preemptible
}
nodePools = append(nodePools, npls)
}
}
case cluster.Kubernetes:
}
return nodePools, nil
}
// Update implements the clusterUpdater interface.
func (c *commonUpdater) Update(ctx context.Context) error {
if !c.clusterPropertiesChanged {
return nil
}
// obtain desired set of labels for each node pool
nodePoolLabelsList, err := buildNodePoolsLabelList(c.cluster, c.request)
if err != nil {
return err
}
labelsMap, err := GetDesiredLabelsForCluster(ctx, c.cluster, nodePoolLabelsList)
if err != nil {
return err
}
secretID := brn.New(c.cluster.GetOrganizationId(), brn.SecretResourceType, c.cluster.GetConfigSecretId()).String()
dclient, err := c.clientFactory.FromSecret(ctx, secretID)
if err != nil {
return err
}
manager := npls.NewManager(dclient, global.Config.Cluster.Labels.Namespace)
if err = manager.Sync(ctx, labelsMap); err != nil {
return err
}
if updater, ok := c.cluster.(interface {
UpdatePKECluster(context.Context, *cluster.UpdateClusterRequest, uint, client.Client, string, bool) error
}); ok {
err = updater.UpdatePKECluster(ctx, c.request, c.userID, c.workflowClient, c.externalBaseURL, c.externalBaseURLInsecure)
} else {
err = c.cluster.UpdateCluster(c.request, c.userID)
}
if err != nil {
return err
}
// on certain clouds we still need to add node pool name labels
if err := labelNodesWithNodePoolName(ctx, c.cluster); err != nil {
return errors.WrapIf(err, "adding labels to nodes failed")
}
return nil
}
// labelNodesWithNodePoolName add node pool name labels for all nodes.
func labelNodesWithNodePoolName(ctx context.Context, commonCluster CommonCluster) error {
switch commonCluster.GetDistribution() {
case cluster.EKS, cluster.GKE, cluster.PKE, cluster.AKS:
log.Infof("nodes are already labelled on : %v", commonCluster.GetDistribution())
return nil
}
nodeNameLister, ok := commonCluster.(nodeNameLister)
if !ok {
log.Debug("cluster does not expose node names")
return nil
}
log.Debug("get K8S config")
kubeConfig, err := commonCluster.GetK8sConfig()
if err != nil {
return err
}
log.Debug("get K8S connection")
client, err := k8sclient.NewClientFromKubeConfig(kubeConfig)
if err != nil {
return err
}
log.Debug("list node names")
nodeNames, err := nodeNameLister.ListNodeNames()
if err != nil {
return err
}
for poolName, nodes := range nodeNames {
log.Debugf("nodepool: [%s]", poolName)
for _, nodeName := range nodes {
log.Infof("add label to node [%s]", nodeName)
labels := map[string]string{pkgCommon.LabelKey: poolName}
if err := addLabelsToNode(ctx, client, nodeName, labels); err != nil {
log.Warnf("error during adding label to node [%s]: %s", nodeName, err.Error())
}
}
}
log.Info("add labels finished")
return nil
}
// addLabelsToNode add label to the given node
func addLabelsToNode(ctx context.Context, client *kubernetes.Clientset, nodeName string, labels map[string]string) (err error) {
tokens := make([]string, 0, len(labels))
for k, v := range labels {
tokens = append(tokens, "\""+k+"\":\""+v+"\"")
}
labelString := "{" + strings.Join(tokens, ",") + "}"
patch := fmt.Sprintf(`{"metadata":{"labels":%v}}`, labelString)
_, err = client.CoreV1().Nodes().Patch(ctx, nodeName, types.MergePatchType, []byte(patch), metav1.PatchOptions{})
return
}