forked from argoproj/argo-workflows
/
install.go
464 lines (435 loc) · 15.4 KB
/
install.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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
package commands
import (
"fmt"
"reflect"
"strconv"
"github.com/argoproj/argo"
wfv1 "github.com/argoproj/argo/api/workflow/v1alpha1"
"github.com/argoproj/argo/errors"
workflowclient "github.com/argoproj/argo/workflow/client"
"github.com/argoproj/argo/workflow/common"
"github.com/argoproj/argo/workflow/controller"
"github.com/ghodss/yaml"
goversion "github.com/hashicorp/go-version"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
appsv1beta2 "k8s.io/api/apps/v1beta2"
apiv1 "k8s.io/api/core/v1"
rbacv1beta1 "k8s.io/api/rbac/v1beta1"
apiextensionsclient "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
apierr "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/client-go/kubernetes"
)
const clusterAdmin = "cluster-admin"
var (
// These values may be overridden by the link flags during build
// (e.g. imageTag will use the official release tag on tagged builds)
imageNamespace = "argoproj"
imageTag = "latest"
// These are the default image names which `argo install` uses during install
DefaultControllerImage = imageNamespace + "/workflow-controller:" + imageTag
DefaultExecutorImage = imageNamespace + "/argoexec:" + imageTag
DefaultUiImage = imageNamespace + "/argoui:" + imageTag
)
func init() {
RootCmd.AddCommand(installCmd)
installCmd.Flags().StringVar(&installArgs.ControllerName, "controller-name", common.DefaultControllerDeploymentName, "name of controller deployment")
installCmd.Flags().StringVar(&installArgs.InstanceID, "instanceid", "", "optional instance id to use for the controller (for multi-controller environments)")
installCmd.Flags().StringVar(&installArgs.UIName, "ui-name", common.DefaultUiDeploymentName, "name of ui deployment")
installCmd.Flags().StringVar(&installArgs.Namespace, "install-namespace", common.DefaultControllerNamespace, "install into a specific Namespace")
installCmd.Flags().StringVar(&installArgs.ConfigMap, "configmap", common.DefaultConfigMapName(common.DefaultControllerDeploymentName), "install controller using preconfigured configmap")
installCmd.Flags().StringVar(&installArgs.ControllerImage, "controller-image", DefaultControllerImage, "use a specified controller image")
installCmd.Flags().StringVar(&installArgs.UIImage, "ui-image", DefaultUiImage, "use a specified ui image")
installCmd.Flags().StringVar(&installArgs.ExecutorImage, "executor-image", DefaultExecutorImage, "use a specified executor image")
installCmd.Flags().StringVar(&installArgs.ServiceAccount, "service-account", "", "use a specified service account for the workflow-controller deployment")
installCmd.Flags().BoolVar(&installArgs.Upgrade, "upgrade", false, "upgrade controller/ui deployments and configmap if already installed")
installCmd.Flags().BoolVar(&installArgs.EnableWebConsole, "enable-web-console", false, "allows to ssh into running step container using Argo UI")
}
// InstallFlags has all the required parameters for installing Argo.
type InstallFlags struct {
ControllerName string // --controller-name
InstanceID string // --instanceid
UIName string // --ui-name
Namespace string // --install-namespace
ConfigMap string // --configmap
ControllerImage string // --controller-image
UIImage string // --ui-image
ExecutorImage string // --executor-image
ServiceAccount string // --service-account
Upgrade bool // --upgrade
EnableWebConsole bool // --enable-web-console
}
var installArgs InstallFlags
var installCmd = &cobra.Command{
Use: "install",
Short: "install Argo",
Run: install,
}
// Install installs the Argo controller and UI in the given Namespace
func Install(cmd *cobra.Command, args InstallFlags) {
fmt.Printf("Installing Argo %s into namespace '%s'\n", argo.GetVersion(), args.Namespace)
clientset = initKubeClient()
kubernetesVersionCheck(clientset)
installCRD(clientset)
if args.ServiceAccount == "" {
if clusterAdminExists(clientset) {
seviceAccountName := ArgoServiceAccount
createServiceAccount(clientset, seviceAccountName, args)
createClusterRoleBinding(clientset, seviceAccountName, args)
args.ServiceAccount = seviceAccountName
}
}
installConfigMap(clientset, args)
if args.ServiceAccount == "" {
fmt.Printf("Using default service account for deployments\n")
} else {
fmt.Printf("Using service account '%s' for deployments\n", args.ServiceAccount)
}
installController(clientset, args)
installUI(clientset, args)
installUIService(clientset, args)
}
func install(cmd *cobra.Command, args []string) {
Install(cmd, installArgs)
}
func clusterAdminExists(clientset *kubernetes.Clientset) bool {
clusterRoles := clientset.RbacV1beta1().ClusterRoles()
_, err := clusterRoles.Get(clusterAdmin, metav1.GetOptions{})
if err != nil {
if apierr.IsNotFound(err) {
return false
}
log.Fatalf("Failed to lookup 'cluster-admin' role: %v", err)
}
return true
}
func createServiceAccount(clientset *kubernetes.Clientset, serviceAccountName string, args InstallFlags) {
serviceAccount := apiv1.ServiceAccount{
TypeMeta: metav1.TypeMeta{
APIVersion: "v1",
Kind: "ServiceAccount",
},
ObjectMeta: metav1.ObjectMeta{
Name: serviceAccountName,
Namespace: args.Namespace,
},
}
_, err := clientset.CoreV1().ServiceAccounts(args.Namespace).Create(&serviceAccount)
if err != nil {
if !apierr.IsAlreadyExists(err) {
log.Fatalf("Failed to create service account '%s': %v\n", serviceAccountName, err)
}
fmt.Printf("ServiceAccount '%s' already exists\n", serviceAccountName)
return
}
fmt.Printf("ServiceAccount '%s' created\n", serviceAccountName)
}
func createClusterRoleBinding(clientset *kubernetes.Clientset, serviceAccountName string, args InstallFlags) {
roleBinding := rbacv1beta1.ClusterRoleBinding{
TypeMeta: metav1.TypeMeta{
APIVersion: "rbac.authorization.k8s.io/v1beta1",
Kind: "ClusterRoleBinding",
},
ObjectMeta: metav1.ObjectMeta{
Name: ArgoClusterRole,
},
RoleRef: rbacv1beta1.RoleRef{
APIGroup: "rbac.authorization.k8s.io",
Kind: "ClusterRole",
Name: clusterAdmin,
},
Subjects: []rbacv1beta1.Subject{
{
Kind: rbacv1beta1.ServiceAccountKind,
Name: serviceAccountName,
Namespace: args.Namespace,
},
},
}
_, err := clientset.RbacV1beta1().ClusterRoleBindings().Create(&roleBinding)
if err != nil {
if !apierr.IsAlreadyExists(err) {
log.Fatalf("Failed to create ClusterRoleBinding %s: %v\n", ArgoClusterRole, err)
}
fmt.Printf("ClusterRoleBinding '%s' already exists\n", ArgoClusterRole)
return
}
fmt.Printf("ClusterRoleBinding '%s' created, bound '%s' to '%s'\n", ArgoClusterRole, serviceAccountName, clusterAdmin)
}
func kubernetesVersionCheck(clientset *kubernetes.Clientset) {
// Check if the Kubernetes version is >= 1.8
versionInfo, err := clientset.ServerVersion()
if err != nil {
log.Fatalf("Failed to get Kubernetes version: %v", err)
}
serverVersion, err := goversion.NewVersion(versionInfo.String())
if err != nil {
log.Fatalf("Failed to create version: %v", err)
}
minVersion, err := goversion.NewVersion("1.8")
if err != nil {
log.Fatalf("Failed to create minimum version: %v", err)
}
if serverVersion.LessThan(minVersion) {
log.Fatalf("Server version %v < %v. Installation won't proceed...\n", serverVersion, minVersion)
}
fmt.Printf("Proceeding with Kubernetes version %v\n", serverVersion)
}
func installConfigMap(clientset *kubernetes.Clientset, args InstallFlags) {
cmClient := clientset.CoreV1().ConfigMaps(args.Namespace)
var wfConfig controller.WorkflowControllerConfig
// install ConfigMap if non-existent
wfConfigMap, err := cmClient.Get(args.ConfigMap, metav1.GetOptions{})
if err != nil {
if !apierr.IsNotFound(err) {
log.Fatalf("Failed lookup of ConfigMap '%s' in namespace '%s': %v", args.ConfigMap, args.Namespace, err)
}
// Create the config map
wfConfig.ExecutorImage = args.ExecutorImage
wfConfig.InstanceID = args.InstanceID
configBytes, err := yaml.Marshal(wfConfig)
if err != nil {
log.Fatalf("%+v", errors.InternalWrapError(err))
}
wfConfigMap.ObjectMeta.Name = args.ConfigMap
wfConfigMap.Data = map[string]string{
common.WorkflowControllerConfigMapKey: string(configBytes),
}
wfConfigMap, err = cmClient.Create(wfConfigMap)
if err != nil {
log.Fatalf("Failed to create ConfigMap '%s' in namespace '%s': %v", args.ConfigMap, args.Namespace, err)
}
fmt.Printf("ConfigMap '%s' created\n", args.ConfigMap)
} else {
// Check if existing configmap needs upgrade to a new executor image
configStr, ok := wfConfigMap.Data[common.WorkflowControllerConfigMapKey]
if !ok {
log.Fatalf("ConfigMap '%s' missing key '%s'", args.ConfigMap, common.WorkflowControllerConfigMapKey)
}
err = yaml.Unmarshal([]byte(configStr), &wfConfig)
if err != nil {
log.Fatalf("Failed to load controller configuration: %v", err)
}
if wfConfig.ExecutorImage != args.ExecutorImage {
if !args.Upgrade {
log.Fatalf("ConfigMap '%s' requires upgrade. Rerun with --upgrade to update the configuration", args.ConfigMap)
}
wfConfig.ExecutorImage = args.ExecutorImage
configBytes, err := yaml.Marshal(wfConfig)
if err != nil {
log.Fatalf("%+v", errors.InternalWrapError(err))
}
wfConfigMap.Data = map[string]string{
common.WorkflowControllerConfigMapKey: string(configBytes),
}
_, err = cmClient.Update(wfConfigMap)
if err != nil {
log.Fatalf("Failed to update ConfigMap '%s' in namespace '%s': %v", args.ConfigMap, args.Namespace, err)
}
fmt.Printf("ConfigMap '%s' updated\n", args.ConfigMap)
} else {
fmt.Printf("Existing ConfigMap '%s' up-to-date\n", args.ConfigMap)
}
}
}
func installController(clientset *kubernetes.Clientset, args InstallFlags) {
controllerDeployment := appsv1beta2.Deployment{
ObjectMeta: metav1.ObjectMeta{
Name: args.ControllerName,
},
Spec: appsv1beta2.DeploymentSpec{
Selector: &metav1.LabelSelector{
MatchLabels: map[string]string{
"app": args.ControllerName,
},
},
Template: apiv1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
"app": args.ControllerName,
},
},
Spec: apiv1.PodSpec{
ServiceAccountName: args.ServiceAccount,
Containers: []apiv1.Container{
{
Name: args.ControllerName,
Image: args.ControllerImage,
Command: []string{"workflow-controller"},
Args: []string{"--configmap", args.ConfigMap},
Env: []apiv1.EnvVar{
{
Name: common.EnvVarNamespace,
ValueFrom: &apiv1.EnvVarSource{
FieldRef: &apiv1.ObjectFieldSelector{
APIVersion: "v1",
FieldPath: "metadata.namespace",
},
},
},
},
},
},
},
},
},
}
createDeploymentHelper(&controllerDeployment, args)
}
func installUI(clientset *kubernetes.Clientset, args InstallFlags) {
uiDeployment := appsv1beta2.Deployment{
ObjectMeta: metav1.ObjectMeta{
Name: args.UIName,
},
Spec: appsv1beta2.DeploymentSpec{
Selector: &metav1.LabelSelector{
MatchLabels: map[string]string{
"app": args.UIName,
},
},
Template: apiv1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
"app": args.UIName,
},
},
Spec: apiv1.PodSpec{
ServiceAccountName: args.ServiceAccount,
Containers: []apiv1.Container{
{
Name: args.UIName,
Image: args.UIImage,
Env: []apiv1.EnvVar{
{
Name: common.EnvVarNamespace,
ValueFrom: &apiv1.EnvVarSource{
FieldRef: &apiv1.ObjectFieldSelector{
APIVersion: "v1",
FieldPath: "metadata.namespace",
},
},
},
{
Name: "IN_CLUSTER",
Value: "true",
},
{
Name: "ENABLE_WEB_CONSOLE",
Value: strconv.FormatBool(args.EnableWebConsole),
},
},
},
},
},
},
},
}
createDeploymentHelper(&uiDeployment, args)
}
// createDeploymentHelper is helper to create or update an existing deployment (if --upgrade was supplied)
func createDeploymentHelper(deployment *appsv1beta2.Deployment, args InstallFlags) {
depClient := clientset.AppsV1beta2().Deployments(args.Namespace)
var result *appsv1beta2.Deployment
var err error
result, err = depClient.Create(deployment)
if err != nil {
if !apierr.IsAlreadyExists(err) {
log.Fatal(err)
}
// deployment already exists
existing, err := depClient.Get(deployment.ObjectMeta.Name, metav1.GetOptions{})
if err != nil {
log.Fatalf("Failed to get existing deployment: %v", err)
}
if upgradeNeeded(deployment, existing) {
if !args.Upgrade {
log.Fatalf("Deployment '%s' requires upgrade. Rerun with --upgrade to upgrade the deployment", deployment.ObjectMeta.Name)
}
existing, err = depClient.Update(deployment)
if err != nil {
log.Fatalf("Failed to update deployment: %v", err)
}
fmt.Printf("Existing deployment '%s' updated\n", existing.GetObjectMeta().GetName())
} else {
fmt.Printf("Existing deployment '%s' up-to-date\n", existing.GetObjectMeta().GetName())
}
} else {
fmt.Printf("Deployment '%s' created\n", result.GetObjectMeta().GetName())
}
}
// upgradeNeeded checks two deployments and returns whether or not there are obvious
// differences in a few deployment/container spec fields that would warrant an
// upgrade. WARNING: This is not intended to be comprehensive -- its primary purpose
// is to check if the controller/UI image is out of date with this version of argo.
func upgradeNeeded(dep1, dep2 *appsv1beta2.Deployment) bool {
if len(dep1.Spec.Template.Spec.Containers) != len(dep2.Spec.Template.Spec.Containers) {
return true
}
for i := 0; i < len(dep1.Spec.Template.Spec.Containers); i++ {
ctr1 := dep1.Spec.Template.Spec.Containers[i]
ctr2 := dep2.Spec.Template.Spec.Containers[i]
if ctr1.Name != ctr2.Name {
return true
}
if ctr1.Image != ctr2.Image {
return true
}
if !reflect.DeepEqual(ctr1.Env, ctr2.Env) {
return true
}
if !reflect.DeepEqual(ctr1.Command, ctr2.Command) {
return true
}
if !reflect.DeepEqual(ctr1.Args, ctr2.Args) {
return true
}
}
return false
}
func installUIService(clientset *kubernetes.Clientset, args InstallFlags) {
svcName := ArgoServiceName
svcClient := clientset.CoreV1().Services(args.Namespace)
uiSvc := apiv1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: svcName,
},
Spec: apiv1.ServiceSpec{
Ports: []apiv1.ServicePort{
{
Port: 80,
TargetPort: intstr.FromInt(8001),
},
},
Selector: map[string]string{
"app": args.UIName,
},
},
}
_, err := svcClient.Create(&uiSvc)
if err != nil {
if !apierr.IsAlreadyExists(err) {
log.Fatal(err)
}
fmt.Printf("Service '%s' already exists\n", svcName)
} else {
fmt.Printf("Service '%s' created\n", svcName)
}
}
func installCRD(clientset *kubernetes.Clientset) {
apiextensionsclientset, err := apiextensionsclient.NewForConfig(restConfig)
if err != nil {
log.Fatalf("Failed to create CustomResourceDefinition '%s': %v", wfv1.CRDFullName, err)
}
// initialize custom resource using a CustomResourceDefinition if it does not exist
result, err := workflowclient.CreateCustomResourceDefinition(apiextensionsclientset)
if err != nil {
if !apierr.IsAlreadyExists(err) {
log.Fatalf("Failed to create CustomResourceDefinition: %v", err)
}
fmt.Printf("CustomResourceDefinition '%s' already exists\n", wfv1.CRDFullName)
} else {
fmt.Printf("CustomResourceDefinition '%s' created\n", result.GetObjectMeta().GetName())
}
}