/
cluster.go
294 lines (261 loc) · 10.8 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
/*
Copyright 2019 The Knative Authors
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 pkg
import (
"flag"
"fmt"
"log"
"strings"
"sync"
"google.golang.org/api/option"
"knative.dev/test-infra/pkg/gke"
"knative.dev/test-infra/pkg/helpers"
container "google.golang.org/api/container/v1beta1"
)
const (
// the maximum retry times if there is an error in cluster operation
retryTimes = 3
// known cluster status
// TODO(chizhg): move these status constants to gke package
statusProvisioning = "PROVISIONING"
statusRunning = "RUNNING"
statusStopping = "STOPPING"
)
// Extra configurations we want to support for cluster creation request.
var (
enableWorkloadIdentity = flag.Bool("enable-workload-identity", false, "whether to enable Workload Identity")
serviceAccount = flag.String("service-account", "", "service account that will be used on this cluster")
)
// Client is defined for perf tests operations.
type Client struct {
ops gke.SDKOperations
}
// NewClient will create a new Client.
func NewClient(environment string) (*Client, error) {
endpoint, err := gke.ServiceEndpoint(environment)
if err != nil {
return nil, err
}
endpointOption := option.WithEndpoint(endpoint)
operations, err := gke.NewSDKClient(endpointOption)
if err != nil {
return nil, fmt.Errorf("failed to set up GKE client: %w", err)
}
client := &Client{
ops: operations,
}
return client, nil
}
// RecreateClusters will delete and recreate the existing clusters, it will also create the clusters if they do
// not exist for the corresponding benchmarks.
func (gc *Client) RecreateClusters(gcpProject, repo, benchmarkRoot string) error {
handleExistingCluster := func(cluster container.Cluster, configExists bool, config ClusterConfig) error {
// always delete the cluster, even if the cluster config is unchanged
return gc.handleExistingClusterHelper(gcpProject, cluster, configExists, config, false)
}
handleNewClusterConfig := func(clusterName string, clusterConfig ClusterConfig) error {
// create a new cluster with the new cluster config
return gc.createClusterWithRetries(gcpProject, clusterName, clusterConfig)
}
return gc.processClusters(gcpProject, repo, benchmarkRoot, handleExistingCluster, handleNewClusterConfig)
}
// ReconcileClusters will reconcile all clusters to make them consistent with the benchmarks' cluster configs.
//
// There can be 4 scenarios:
// 1. If the benchmark's cluster config is unchanged, do nothing
// 2. If the benchmark's config is changed, delete the old cluster and create a new one with the new config
// 3. If the benchmark is renamed, delete the old cluster and create a new one with the new name
// 4. If the benchmark is deleted, delete the corresponding cluster
func (gc *Client) ReconcileClusters(gcpProject, repo, benchmarkRoot string) error {
handleExistingCluster := func(cluster container.Cluster, configExists bool, config ClusterConfig) error {
// retain the cluster, if the cluster config is unchanged
return gc.handleExistingClusterHelper(gcpProject, cluster, configExists, config, true)
}
handleNewClusterConfig := func(clusterName string, clusterConfig ClusterConfig) error {
// create a new cluster with the new cluster config
return gc.createClusterWithRetries(gcpProject, clusterName, clusterConfig)
}
return gc.processClusters(gcpProject, repo, benchmarkRoot, handleExistingCluster, handleNewClusterConfig)
}
// DeleteClusters will delete all existing clusters.
func (gc *Client) DeleteClusters(gcpProject, repo, benchmarkRoot string) error {
handleExistingCluster := func(cluster container.Cluster, configExists bool, config ClusterConfig) error {
// retain the cluster, if the cluster config is unchanged
return gc.deleteClusterWithRetries(gcpProject, cluster)
}
handleNewClusterConfig := func(clusterName string, clusterConfig ClusterConfig) error {
// do nothing
return nil
}
return gc.processClusters(gcpProject, repo, benchmarkRoot, handleExistingCluster, handleNewClusterConfig)
}
// processClusters will process existing clusters and configs for new clusters,
// with the corresponding functions provided by callers.
func (gc *Client) processClusters(
gcpProject, repo, benchmarkRoot string,
handleExistingCluster func(cluster container.Cluster, configExists bool, config ClusterConfig) error,
handleNewClusterConfig func(name string, config ClusterConfig) error,
) error {
curtClusters, err := gc.listClustersForRepo(gcpProject, repo)
if err != nil {
return fmt.Errorf("failed getting clusters for the repo %q: %w", repo, err)
}
clusterConfigs, err := benchmarkClusters(repo, benchmarkRoot)
if err != nil {
return fmt.Errorf("failed getting cluster configs for benchmarks in repo %q: %w", repo, err)
}
errCh := make(chan error, len(curtClusters)+len(clusterConfigs))
wg := sync.WaitGroup{}
// handle all existing clusters
for i := range curtClusters {
wg.Add(1)
cluster := curtClusters[i]
config, configExists := clusterConfigs[cluster.Name]
go func() {
defer wg.Done()
if err := handleExistingCluster(cluster, configExists, config); err != nil {
errCh <- fmt.Errorf("failed handling cluster %v: %w", cluster, err)
}
}()
// remove the cluster from clusterConfigs as it's already been handled
delete(clusterConfigs, cluster.Name)
}
// handle all other cluster configs
for name, config := range clusterConfigs {
wg.Add(1)
// recreate them to avoid the issue with iterations of multiple Go routines
name, config := name, config
go func() {
defer wg.Done()
if err := handleNewClusterConfig(name, config); err != nil {
errCh <- fmt.Errorf("failed handling new cluster config %v: %w", config, err)
}
}()
}
wg.Wait()
close(errCh)
errs := make([]error, len(errCh))
for err := range errCh {
errs = append(errs, err)
}
return helpers.CombineErrors(errs)
}
// handleExistingClusterHelper is a helper function for handling an existing cluster.
func (gc *Client) handleExistingClusterHelper(
gcpProject string,
cluster container.Cluster, configExists bool, config ClusterConfig,
retainIfUnchanged bool,
) error {
// if the cluster is currently being created or deleted, return directly as that job will handle it properly
if cluster.Status == statusProvisioning || cluster.Status == statusStopping {
log.Printf("Cluster %q is being handled by another job, skip it", cluster.Name)
return nil
}
curtNodeCount := cluster.CurrentNodeCount
// if it's a regional cluster, the nodes will be in 3 zones. The CurrentNodeCount we get here is
// the total node count, so we'll need to divide with 3 to get the actual regional node count
if _, zone := gke.RegionZoneFromLoc(cluster.Location); zone == "" {
curtNodeCount /= 3
}
// if retainIfUnchanged is set to true, and the cluster config does not change, do nothing
// TODO(chizhg): also check the addons config
if configExists && retainIfUnchanged &&
curtNodeCount == config.NodeCount && cluster.Location == config.Location {
log.Printf("Cluster config is unchanged for %q, skip it", cluster.Name)
return nil
}
if err := gc.deleteClusterWithRetries(gcpProject, cluster); err != nil {
return fmt.Errorf("failed deleting cluster %q in %q: %w", cluster.Name, cluster.Location, err)
}
if configExists {
return gc.createClusterWithRetries(gcpProject, cluster.Name, config)
}
return nil
}
// listClustersForRepo will list all the clusters under the gcpProject that belong to the given repo.
func (gc *Client) listClustersForRepo(gcpProject, repo string) ([]container.Cluster, error) {
allClusters, err := gc.ops.ListClustersInProject(gcpProject)
if err != nil {
return nil, fmt.Errorf("failed listing clusters in project %q: %w", gcpProject, err)
}
clusters := make([]container.Cluster, 0)
for _, cluster := range allClusters {
if clusterBelongsToRepo(cluster.Name, repo) {
clusters = append(clusters, *cluster)
}
}
return clusters, nil
}
// deleteClusterWithRetries will delete the given cluster,
// and retry for a maximum of retryTimes if there is an error.
// TODO(chizhg): maybe move it to clustermanager library.
func (gc *Client) deleteClusterWithRetries(gcpProject string, cluster container.Cluster) error {
log.Printf("Deleting cluster %q under project %q", cluster.Name, gcpProject)
region, zone := gke.RegionZoneFromLoc(cluster.Location)
var err error
for i := 0; i < retryTimes; i++ {
if err = gc.ops.DeleteCluster(gcpProject, region, zone, cluster.Name); err == nil {
break
}
}
if err != nil {
return fmt.Errorf(
"failed deleting cluster %q in %q after retrying %d times: %w",
cluster.Name, cluster.Location, retryTimes, err)
}
return nil
}
// createClusterWithRetries will create a new cluster with the given config,
// and retry for a maximum of retryTimes if there is an error.
// TODO(chizhg): maybe move it to clustermanager library.
func (gc *Client) createClusterWithRetries(gcpProject, name string, config ClusterConfig) error {
log.Printf("Creating cluster %q under project %q with config %v", name, gcpProject, config)
var addons []string
if strings.TrimSpace(config.Addons) != "" {
addons = strings.Split(config.Addons, ",")
}
req := &gke.Request{
Project: gcpProject,
ClusterName: name,
MinNodes: config.NodeCount,
MaxNodes: config.NodeCount,
NodeType: config.NodeType,
Addons: addons,
EnableWorkloadIdentity: *enableWorkloadIdentity,
ServiceAccount: *serviceAccount,
}
creq, err := gke.NewCreateClusterRequest(req)
if err != nil {
return fmt.Errorf("cannot create cluster with request %v: %w", req, err)
}
region, zone := gke.RegionZoneFromLoc(config.Location)
for i := 0; i < retryTimes; i++ {
// TODO(chizhg): retry with different requests, based on the error type
if err = gc.ops.CreateCluster(gcpProject, region, zone, creq); err != nil {
// If the cluster is actually created in the end, recreating it with the same name will fail again for sure,
// so we need to delete the broken cluster before retry.
// It is a best-effort delete, and won't throw any errors if the deletion fails.
if cluster, _ := gc.ops.GetCluster(gcpProject, region, zone, name); cluster != nil {
gc.deleteClusterWithRetries(gcpProject, *cluster)
}
} else {
break
}
}
if err != nil {
return fmt.Errorf(
"failed creating cluster %q in %q after retrying %d times: %w",
name, config.Location, retryTimes, err)
}
return nil
}