-
Notifications
You must be signed in to change notification settings - Fork 162
/
create_workflow.go
270 lines (219 loc) · 7.39 KB
/
create_workflow.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
// Copyright © 2019 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"
"time"
"go.uber.org/cadence"
"go.uber.org/cadence/activity"
"go.uber.org/cadence/workflow"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/kubernetes"
"github.com/banzaicloud/pipeline/internal/cluster/clustersetup"
pkgCadence "github.com/banzaicloud/pipeline/pkg/cadence"
pkgCluster "github.com/banzaicloud/pipeline/pkg/cluster"
pkgCommon "github.com/banzaicloud/pipeline/pkg/common"
"github.com/banzaicloud/pipeline/pkg/sdk/brn"
)
// ClientFactory returns a Kubernetes client.
type ClientFactory interface {
// FromSecret creates a Kubernetes client for a cluster from a secret.
FromSecret(ctx context.Context, secretID string) (kubernetes.Interface, error)
}
const CreateClusterWorkflowName = "create-cluster-legacy"
type CreateClusterWorkflowInput struct {
ClusterID uint
ClusterUID string
ClusterName string
OrganizationID uint
OrganizationName string
Distribution string
NodePoolLabels map[string]map[string]string
PostHooks pkgCluster.PostHooks
Cloud string
}
func CreateClusterWorkflow(ctx workflow.Context, input CreateClusterWorkflowInput) error {
// Download k8s config (where applicable)
var configSecretID string
{
ao := workflow.ActivityOptions{
ScheduleToStartTimeout: 10 * time.Minute,
StartToCloseTimeout: 20 * time.Minute,
WaitForCancellation: true,
RetryPolicy: &cadence.RetryPolicy{
InitialInterval: 15 * time.Second,
BackoffCoefficient: 1.0,
MaximumAttempts: 30,
NonRetriableErrorReasons: []string{"cadenceInternal:Panic", pkgCadence.ClientErrorReason},
},
}
ctx := workflow.WithActivityOptions(ctx, ao)
activityInput := DownloadK8sConfigActivityInput{
ClusterID: input.ClusterID,
}
err := workflow.ExecuteActivity(ctx, DownloadK8sConfigActivityName, activityInput).Get(ctx, &configSecretID)
if err != nil {
return pkgCadence.UnwrapError(err)
}
}
{
restoreBackupParams, err := pkgCluster.GetRestoreBackupParams(input.PostHooks)
if err != nil {
return err
}
workflowInput := clustersetup.WorkflowInput{
ConfigSecretID: brn.New(input.OrganizationID, brn.SecretResourceType, configSecretID).String(),
Cluster: clustersetup.Cluster{
ID: input.ClusterID,
UID: input.ClusterUID,
Name: input.ClusterName,
Distribution: input.Distribution,
Cloud: input.Cloud,
},
Organization: clustersetup.Organization{
ID: input.OrganizationID,
Name: input.OrganizationName,
},
NodePoolLabels: input.NodePoolLabels,
RestoreBackupParams: restoreBackupParams,
}
cwo := workflow.ChildWorkflowOptions{
ExecutionStartToCloseTimeout: 30 * time.Minute,
TaskStartToCloseTimeout: 40 * time.Minute,
}
ctx := workflow.WithChildOptions(ctx, cwo)
future := workflow.ExecuteChildWorkflow(ctx, clustersetup.WorkflowName, workflowInput)
if err := future.Get(ctx, nil); err != nil {
return err
}
}
return nil
}
const DownloadK8sConfigActivityName = "download-k8s-config-legacy"
type DownloadK8sConfigActivityInput struct {
ClusterID uint
}
type DownloadK8sConfigActivity struct {
manager *Manager
}
func NewDownloadK8sConfigActivity(manager *Manager) DownloadK8sConfigActivity {
return DownloadK8sConfigActivity{
manager: manager,
}
}
// K8sConfigDownloader can download a cluster config.
type K8sConfigDownloader interface {
DownloadK8sConfig() ([]byte, error)
}
func (a DownloadK8sConfigActivity) Execute(ctx context.Context, input DownloadK8sConfigActivityInput) (string, error) {
logger := activity.GetLogger(ctx).Sugar().With("clusterId", input.ClusterID)
cluster, err := a.manager.GetClusterByIDOnly(ctx, input.ClusterID)
if err != nil {
return "", err
}
if secretID := cluster.GetConfigSecretId(); secretID != "" {
logger.Info("config is already present in Vault")
return secretID, nil
}
activityInfo := activity.GetInfo(ctx)
// On the first attempt try to get an existing config
if activityInfo.Attempt == 0 {
logger.Info("trying to get config for the first time")
config, err := cluster.GetK8sConfig()
if err == nil && len(config) > 0 {
logger.Info("saving existing config")
if err := StoreKubernetesConfig(cluster, config); err != nil {
return "", err
}
return cluster.GetConfigSecretId(), nil
}
}
if downloader, ok := cluster.(K8sConfigDownloader); ok {
logger.Info("attempting to download config")
config, err := downloader.DownloadK8sConfig()
if err != nil {
if strings.Contains(err.Error(), "PermissionDenied") {
return "", pkgCadence.NewClientError(err)
}
return "", err
}
logger.Info("saving config")
if err := StoreKubernetesConfig(cluster, config); err != nil {
return "", err
}
return cluster.GetConfigSecretId(), nil
}
return cluster.GetConfigSecretId(), nil
}
const LabelNodesWithNodepoolNameActivityName = "label-nodes-with-nodepool-name-legacy"
type LabelNodesWithNodepoolNameActivityInput struct {
ClusterID uint
SecretID string
}
type LabelNodesWithNodepoolNameActivity struct {
clientFactory ClientFactory
manager *Manager
}
func NewLabelNodesWithNodepoolNameActivity(clientFactory ClientFactory, manager *Manager) LabelNodesWithNodepoolNameActivity {
return LabelNodesWithNodepoolNameActivity{
clientFactory: clientFactory,
manager: manager,
}
}
type nodeNameLister interface {
ListNodeNames() (map[string][]string, error)
}
func (a LabelNodesWithNodepoolNameActivity) Execute(ctx context.Context, input LabelNodesWithNodepoolNameActivityInput) error {
logger := activity.GetLogger(ctx).Sugar().With("clusterId", input.ClusterID)
cluster, err := a.manager.GetClusterByIDOnly(ctx, input.ClusterID)
if err != nil {
return err
}
nodeNameLister, ok := cluster.(nodeNameLister)
if !ok {
logger.Warn("cluster does not expose node lists")
return nil
}
client, err := a.clientFactory.FromSecret(ctx, input.SecretID)
if err != nil {
return err
}
nodeNames, err := nodeNameLister.ListNodeNames()
if err != nil {
return err
}
for poolName, nodes := range nodeNames {
logger := logger.With("nodepool", poolName)
logger.Debug("labeling nodepool")
for _, nodeName := range nodes {
logger := logger.With("node", nodeName)
logger.Debug("labeling node")
labels := map[string]string{pkgCommon.LabelKey: poolName}
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{})
if err != nil {
logger.Warnf("error during adding label to node: %s", err.Error())
}
}
}
return nil
}