forked from jenkins-x/jx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.go
635 lines (572 loc) · 17.4 KB
/
common.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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
package cmd
import (
"fmt"
"io"
"net/url"
"os"
"strings"
"time"
"github.com/jenkins-x/golang-jenkins"
"github.com/jenkins-x/jx/pkg/auth"
"github.com/jenkins-x/jx/pkg/client/clientset/versioned"
"github.com/jenkins-x/jx/pkg/log"
core_v1 "k8s.io/api/core/v1"
apiextensionsclientset "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
"github.com/jenkins-x/jx/pkg/config"
"github.com/jenkins-x/jx/pkg/jx/cmd/table"
cmdutil "github.com/jenkins-x/jx/pkg/jx/cmd/util"
"github.com/jenkins-x/jx/pkg/kube"
"github.com/jenkins-x/jx/pkg/util"
"github.com/spf13/cobra"
"gopkg.in/AlecAivazis/survey.v1"
gitcfg "gopkg.in/src-d/go-git.v4/config"
"gopkg.in/yaml.v2"
"k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
)
const (
optionServerName = "name"
optionServerURL = "url"
exposecontrollerVersion = "2.3.56"
exposecontroller = "exposecontroller"
exposecontrollerChart = "jenkins-x/exposecontroller"
)
// CommonOptions contains common options and helper methods
type CommonOptions struct {
Factory cmdutil.Factory
Out io.Writer
Err io.Writer
Cmd *cobra.Command
Args []string
BatchMode bool
Verbose bool
Headless bool
NoBrew bool
ServiceAccount string
// common cached clients
kubeClient kubernetes.Interface
apiExtensionsClient apiextensionsclientset.Interface
currentNamespace string
devNamespace string
jxClient versioned.Interface
jenkinsClient *gojenkins.Jenkins
}
type ServerFlags struct {
ServerName string
ServerURL string
}
func (f *ServerFlags) IsEmpty() bool {
return f.ServerName == "" && f.ServerURL == ""
}
func (c *CommonOptions) Stdout() io.Writer {
if c.Out != nil {
return c.Out
}
return os.Stdout
}
func (c *CommonOptions) CreateTable() table.Table {
return c.Factory.CreateTable(c.Stdout())
}
// Debugf outputs the given text to the console if verbose mode is enabled
func (c *CommonOptions) Debugf(format string, a ...interface{}) {
if c.Verbose {
log.Infof(format, a)
}
}
func (options *CommonOptions) addCommonFlags(cmd *cobra.Command) {
cmd.Flags().BoolVarP(&options.BatchMode, "batch-mode", "b", false, "In batch mode the command never prompts for user input")
cmd.Flags().BoolVarP(&options.Verbose, "verbose", "", false, "Enable verbose logging")
cmd.Flags().BoolVarP(&options.Headless, "headless", "", false, "Enable headless operation if using browser automation")
cmd.Flags().BoolVarP(&options.NoBrew, "no-brew", "", false, "Disables the use of brew on MacOS to install or upgrade command line dependencies")
options.Cmd = cmd
}
func (o *CommonOptions) CreateApiExtensionsClient() (apiextensionsclientset.Interface, error) {
var err error
if o.apiExtensionsClient == nil {
o.apiExtensionsClient, err = o.Factory.CreateApiExtensionsClient()
if err != nil {
return nil, err
}
}
return o.apiExtensionsClient, nil
}
func (o *CommonOptions) KubeClient() (kubernetes.Interface, string, error) {
if o.kubeClient == nil {
kubeClient, currentNs, err := o.Factory.CreateClient()
if err != nil {
return nil, "", err
}
o.kubeClient = kubeClient
o.currentNamespace = currentNs
}
return o.kubeClient, o.currentNamespace, nil
}
func (o *CommonOptions) JXClient() (versioned.Interface, string, error) {
if o.jxClient == nil {
jxClient, ns, err := o.Factory.CreateJXClient()
if err != nil {
return nil, ns, err
}
o.jxClient = jxClient
if o.currentNamespace == "" {
o.currentNamespace = ns
}
}
return o.jxClient, o.currentNamespace, nil
}
func (o *CommonOptions) JXClientAndDevNamespace() (versioned.Interface, string, error) {
if o.jxClient == nil {
jxClient, ns, err := o.JXClient()
if err != nil {
return nil, ns, err
}
o.jxClient = jxClient
if o.currentNamespace == "" {
o.currentNamespace = ns
}
}
if o.devNamespace == "" {
client, ns, err := o.KubeClient()
if err != nil {
return nil, "", err
}
devNs, _, err := kube.GetDevNamespace(client, ns)
if err != nil {
return nil, "", err
}
o.devNamespace = devNs
}
return o.jxClient, o.devNamespace, nil
}
func (o *CommonOptions) JenkinsClient() (*gojenkins.Jenkins, error) {
if o.jenkinsClient == nil {
kubeClient, ns, err := o.KubeClient()
if err != nil {
return nil, err
}
jenkins, err := o.Factory.CreateJenkinsClient(kubeClient, ns)
if err != nil {
return nil, err
}
o.jenkinsClient = jenkins
}
return o.jenkinsClient, nil
}
func (o *CommonOptions) GetJenkinsURL() (string, error) {
kubeClient, ns, err := o.KubeClient()
if err != nil {
return "", err
}
return o.Factory.GetJenkinsURL(kubeClient, ns)
}
func (o *CommonOptions) TeamAndEnvironmentNames() (string, string, error) {
kubeClient, currentNs, err := o.KubeClient()
if err != nil {
return "", "", err
}
return kube.GetDevNamespace(kubeClient, currentNs)
}
func (o *ServerFlags) addGitServerFlags(cmd *cobra.Command) {
cmd.Flags().StringVarP(&o.ServerName, optionServerName, "n", "", "The name of the git server to add a user")
cmd.Flags().StringVarP(&o.ServerURL, optionServerURL, "u", "", "The URL of the git server to add a user")
}
// findGitServer finds the git server from the given flags or returns an error
func (o *CommonOptions) findGitServer(config *auth.AuthConfig, serverFlags *ServerFlags) (*auth.AuthServer, error) {
return o.findServer(config, serverFlags, "git", "Try creating one via: jx create git server", false)
}
// findIssueTrackerServer finds the issue tracker server from the given flags or returns an error
func (o *CommonOptions) findIssueTrackerServer(config *auth.AuthConfig, serverFlags *ServerFlags) (*auth.AuthServer, error) {
return o.findServer(config, serverFlags, "issues", "Try creating one via: jx create tracker server", false)
}
// findChatServer finds the chat server from the given flags or returns an error
func (o *CommonOptions) findChatServer(config *auth.AuthConfig, serverFlags *ServerFlags) (*auth.AuthServer, error) {
return o.findServer(config, serverFlags, "chat", "Try creating one via: jx create chat server", false)
}
// findAddonServer finds the addon server from the given flags or returns an error
func (o *CommonOptions) findAddonServer(config *auth.AuthConfig, serverFlags *ServerFlags, kind string) (*auth.AuthServer, error) {
return o.findServer(config, serverFlags, kind, "Try creating one via: jx create addon", true)
}
func (o *CommonOptions) findServer(config *auth.AuthConfig, serverFlags *ServerFlags, defaultKind string, missingServerDescription string, lazyCreate bool) (*auth.AuthServer, error) {
kind := defaultKind
var server *auth.AuthServer
if serverFlags.ServerURL != "" {
server = config.GetServer(serverFlags.ServerURL)
if server == nil {
if lazyCreate {
return config.GetOrCreateServerName(serverFlags.ServerURL, serverFlags.ServerName, kind), nil
}
return nil, util.InvalidOption(optionServerURL, serverFlags.ServerURL, config.GetServerURLs())
}
}
if server == nil && serverFlags.ServerName != "" {
name := serverFlags.ServerName
if lazyCreate {
server = config.GetOrCreateServerName(serverFlags.ServerURL, name, kind)
} else {
server = config.GetServerByName(name)
}
if server == nil {
return nil, util.InvalidOption(optionServerName, name, config.GetServerNames())
}
}
if server == nil {
name := config.CurrentServer
if name != "" && o.BatchMode {
server = config.GetServerByName(name)
if server == nil {
log.Warnf("Current server %s no longer exists\n", name)
}
}
}
if server == nil && len(config.Servers) == 1 {
server = config.Servers[0]
}
if server == nil && len(config.Servers) > 1 {
if o.BatchMode {
return nil, fmt.Errorf("Multiple servers found. Please specify one via the %s option", optionServerName)
}
defaultServerName := ""
if config.CurrentServer != "" {
s := config.GetServer(config.CurrentServer)
if s != nil {
defaultServerName = s.Name
}
}
name, err := util.PickNameWithDefault(config.GetServerNames(), "Pick server to use: ", defaultServerName)
if err != nil {
return nil, err
}
server = config.GetServerByName(name)
if server == nil {
return nil, fmt.Errorf("Could not find the server for name %s", name)
}
}
if server == nil {
return nil, fmt.Errorf("Could not find a %s. %s", kind, missingServerDescription)
}
return server, nil
}
func (o *CommonOptions) findService(name string) (string, error) {
client, ns, err := o.KubeClient()
if err != nil {
return "", err
}
devNs, _, err := kube.GetDevNamespace(client, ns)
if err != nil {
return "", err
}
url, err := kube.FindServiceURL(client, ns, name)
if url == "" {
url, err = kube.FindServiceURL(client, devNs, name)
}
if url == "" {
names, err := kube.GetServiceNames(client, ns, name)
if err != nil {
return "", err
}
if len(names) > 1 {
name, err = util.PickName(names, "Pick service to open: ")
if err != nil {
return "", err
}
if name != "" {
url, err = kube.FindServiceURL(client, ns, name)
}
} else if len(names) == 1 {
// must have been a filter
url, err = kube.FindServiceURL(client, ns, names[0])
}
if url == "" {
return "", fmt.Errorf("Could not find URL for service %s in namespace %s", name, ns)
}
}
return url, nil
}
func (o *CommonOptions) findEnvironmentNamespace(envName string) (string, error) {
client, ns, err := o.KubeClient()
if err != nil {
return "", err
}
jxClient, _, err := o.JXClient()
if err != nil {
return "", err
}
devNs, _, err := kube.GetDevNamespace(client, ns)
if err != nil {
return "", err
}
envMap, envNames, err := kube.GetEnvironments(jxClient, devNs)
if err != nil {
return "", err
}
env := envMap[envName]
if env == nil {
return "", util.InvalidOption(optionEnvironment, envName, envNames)
}
answer := env.Spec.Namespace
if answer == "" {
return "", fmt.Errorf("Environment %s does not have a Namespace!", envName)
}
return answer, nil
}
func (o *CommonOptions) findServiceInNamespace(name string, ns string) (string, error) {
client, curNs, err := o.KubeClient()
if err != nil {
return "", err
}
if ns == "" {
ns = curNs
}
url, err := kube.FindServiceURL(client, ns, name)
if url == "" {
names, err := kube.GetServiceNames(client, ns, name)
if err != nil {
return "", err
}
if len(names) > 1 {
name, err = util.PickName(names, "Pick service to open: ")
if err != nil {
return "", err
}
if name != "" {
url, err = kube.FindServiceURL(client, ns, name)
}
} else if len(names) == 1 {
// must have been a filter
url, err = kube.FindServiceURL(client, ns, names[0])
}
if url == "" {
return "", fmt.Errorf("Could not find URL for service %s in namespace %s", name, ns)
}
}
return url, nil
}
func (o *CommonOptions) retry(attempts int, sleep time.Duration, call func() error) (err error) {
for i := 0; ; i++ {
err = call()
if err == nil {
return
}
if i >= (attempts - 1) {
break
}
time.Sleep(sleep)
log.Infof("retrying after error:%s\n", err)
}
return fmt.Errorf("after %d attempts, last error: %s", attempts, err)
}
func (o *CommonOptions) retryQuiet(attempts int, sleep time.Duration, call func() error) (err error) {
lastMessage := ""
dot := false
for i := 0; ; i++ {
err = call()
if err == nil {
if dot {
log.Blank()
}
return
}
if i >= (attempts - 1) {
break
}
time.Sleep(sleep)
message := fmt.Sprintf("retrying after error: %s", err)
if lastMessage == message {
log.Info(".")
dot = true
} else {
lastMessage = message
if dot {
dot = false
log.Blank()
}
log.Infof("%s\n", lastMessage)
}
}
return fmt.Errorf("after %d attempts, last error: %s", attempts, err)
}
func (o *CommonOptions) retryQuietlyUntilTimeout(timeout time.Duration, sleep time.Duration, call func() error) (err error) {
timeoutTime := time.Now().Add(timeout)
lastMessage := ""
dot := false
for i := 0; ; i++ {
err = call()
if err == nil {
if dot {
log.Blank()
}
return
}
if time.Now().After(timeoutTime) {
return fmt.Errorf("Timed out after %s, last error: %s", timeout.String(), err)
}
time.Sleep(sleep)
message := fmt.Sprintf("retrying after error: %s", err)
if lastMessage == message {
log.Info(".")
dot = true
} else {
lastMessage = message
if dot {
dot = false
log.Blank()
}
log.Infof("%s\n", lastMessage)
}
}
}
func (o *CommonOptions) getJobMap(filter string) (map[string]gojenkins.Job, error) {
jobMap := map[string]gojenkins.Job{}
jenkins, err := o.JenkinsClient()
if err != nil {
return jobMap, err
}
jobs, err := jenkins.GetJobs()
if err != nil {
return jobMap, err
}
o.addJobs(&jobMap, filter, "", jobs)
return jobMap, nil
}
func (o *CommonOptions) addJobs(jobMap *map[string]gojenkins.Job, filter string, prefix string, jobs []gojenkins.Job) {
jenkins, err := o.JenkinsClient()
if err != nil {
return
}
for _, j := range jobs {
name := jobName(prefix, &j)
if IsPipeline(&j) {
if filter == "" || strings.Contains(name, filter) {
(*jobMap)[name] = j
continue
}
}
if j.Jobs != nil {
o.addJobs(jobMap, filter, name, j.Jobs)
} else {
job, err := jenkins.GetJob(name)
if err == nil && job.Jobs != nil {
o.addJobs(jobMap, filter, name, job.Jobs)
}
}
}
}
func (o *CommonOptions) tailBuild(jobName string, build *gojenkins.Build) error {
jenkins, err := o.JenkinsClient()
if err != nil {
return nil
}
u, err := url.Parse(build.Url)
if err != nil {
return err
}
buildPath := u.Path
log.Infof("%s %s\n", "tailing the log of", fmt.Sprintf("%s #%d", jobName, build.Number))
return jenkins.TailLog(buildPath, o.Out, time.Second, time.Hour*100)
}
func (o *CommonOptions) pickRemoteURL(config *gitcfg.Config) (string, error) {
urls := []string{}
if config.Remotes != nil {
for _, r := range config.Remotes {
if r.URLs != nil {
for _, u := range r.URLs {
urls = append(urls, u)
}
}
}
}
if len(urls) == 1 {
return urls[0], nil
}
url := ""
if len(urls) > 1 {
prompt := &survey.Select{
Message: "Choose a remote git URL:",
Options: urls,
}
err := survey.AskOne(prompt, &url, nil)
if err != nil {
return "", err
}
}
return url, nil
}
// todo switch to using exposecontroller as a jx plugin
// get existing config from the devNamespace and run exposecontroller in the target environment
func (o *CommonOptions) expose(devNamespace, targetNamespace, releaseName, password string) error {
_, err := o.kubeClient.CoreV1().Secrets(targetNamespace).Get(kube.SecretBasicAuth, v1.GetOptions{})
if err != nil {
data := make(map[string][]byte)
if password != "" {
hash := config.HashSha(password)
data[kube.AUTH] = []byte(fmt.Sprintf("admin:{SHA}%s", hash))
} else {
basicAuth, err := o.kubeClient.CoreV1().Secrets(devNamespace).Get(kube.SecretBasicAuth, v1.GetOptions{})
if err != nil {
return fmt.Errorf("cannot find secret %s in namespace %s: %v", kube.SecretBasicAuth, devNamespace, err)
}
data = basicAuth.Data
}
sec := &core_v1.Secret{
Data: data,
ObjectMeta: v1.ObjectMeta{
Name: kube.SecretBasicAuth,
},
}
_, err := o.kubeClient.CoreV1().Secrets(targetNamespace).Create(sec)
if err != nil {
return fmt.Errorf("cannot create secret %s in target namespace %s: %v", kube.SecretBasicAuth, targetNamespace, err)
}
}
exposecontrollerConfig, err := kube.GetTeamExposecontrollerConfig(o.kubeClient, devNamespace)
if err != nil {
return fmt.Errorf("cannot get existing team exposecontroller config from namespace %s: %v", devNamespace, err)
}
var exValues []string
if targetNamespace != devNamespace {
// run exposecontroller using existing team config
exValues = []string{
"config.exposer=" + exposecontrollerConfig["exposer"],
"config.domain=" + exposecontrollerConfig["domain"],
"config.http=" + exposecontrollerConfig["http"],
"config.tls-acme=" + exposecontrollerConfig["tls-acme"],
}
}
err = o.installChart("expose"+releaseName, exposecontrollerChart, exposecontrollerVersion, targetNamespace, true, exValues)
if err != nil {
return fmt.Errorf("exposecontroller deployment failed: %v", err)
}
err = kube.WaitForJobToSucceeded(o.kubeClient, targetNamespace, exposecontroller, 5*time.Minute)
if err != nil {
return fmt.Errorf("failed waiting for exposecontroller job to succeed: %v", err)
}
return kube.DeleteJob(o.kubeClient, targetNamespace, exposecontroller)
}
func (o *CommonOptions) getDefaultAdminPassword(devNamespace string) (string, error) {
basicAuth, err := o.kubeClient.CoreV1().Secrets(devNamespace).Get(JXInstallConfig, v1.GetOptions{})
if err != nil {
return "", fmt.Errorf("cannot find secret %s in namespace %s: %v", kube.SecretBasicAuth, devNamespace, err)
}
adminSecrets := basicAuth.Data[AdminSecretsFile]
adminConfig := config.AdminSecretsConfig{}
err = yaml.Unmarshal(adminSecrets, &adminConfig)
if err != nil {
return "", err
}
return adminConfig.Jenkins.JenkinsSecret.Password, nil
}
func (o *CommonOptions) ensureAddonServiceAvailable(serviceName string) (string, error) {
present, err := kube.IsServicePresent(o.kubeClient, serviceName, o.currentNamespace)
if err != nil {
return "", fmt.Errorf("no %s provider service found, are you in your teams dev environment? Type `jx ns` to switch.", serviceName)
}
if present {
url, err := kube.GetServiceURLFromName(o.kubeClient, serviceName, o.currentNamespace)
if err != nil {
return "", fmt.Errorf("no %s provider service found, are you in your teams dev environment? Type `jx ns` to switch.", serviceName)
}
return url, nil
}
// todo ask if user wants to install addon?
return "", nil
}