forked from jenkins-x/jx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
env.go
865 lines (818 loc) · 24.2 KB
/
env.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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
package kube
import (
"fmt"
"io"
"io/ioutil"
"os"
"os/user"
"path/filepath"
"regexp"
"sort"
"strings"
"github.com/jenkins-x/jx/pkg/apis/jenkins.io/v1"
"github.com/jenkins-x/jx/pkg/auth"
"github.com/jenkins-x/jx/pkg/client/clientset/versioned"
"github.com/jenkins-x/jx/pkg/config"
"github.com/jenkins-x/jx/pkg/gits"
"github.com/jenkins-x/jx/pkg/log"
"github.com/jenkins-x/jx/pkg/util"
"gopkg.in/AlecAivazis/survey.v1"
"gopkg.in/AlecAivazis/survey.v1/terminal"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
)
var useForkForEnvGitRepo = false
// CreateEnvironmentSurvey creates a Survey on the given environment using the default options
// from the CLI
func CreateEnvironmentSurvey(batchMode bool, authConfigSvc auth.AuthConfigService, devEnv *v1.Environment, data *v1.Environment,
config *v1.Environment, forkEnvGitURL string, ns string, jxClient versioned.Interface, kubeClient kubernetes.Interface, envDir string,
gitRepoOptions *gits.GitRepositoryOptions, helmValues config.HelmValuesConfig, prefix string, git gits.Gitter, in terminal.FileReader, out terminal.FileWriter, errOut io.Writer) (gits.GitProvider, error) {
var gitProvider gits.GitProvider
surveyOpts := survey.WithStdio(in, out, errOut)
name := data.Name
createMode := name == ""
if createMode {
if config.Name != "" {
err := ValidNameOption(OptionName, config.Name)
if err != nil {
return nil, err
}
err = ValidateEnvironmentDoesNotExist(jxClient, ns, config.Name)
if err != nil {
return nil, err
}
data.Name = config.Name
} else {
validator := func(val interface{}) error {
err := ValidateName(val)
if err != nil {
return err
}
str, ok := val.(string)
if !ok {
return fmt.Errorf("Expected string value")
}
v := ValidateEnvironmentDoesNotExist(jxClient, ns, str)
return v
}
q := &survey.Input{
Message: "Name:",
Help: "The Environment name must be unique, lower case and a valid DNS name",
}
err := survey.AskOne(q, &data.Name, validator, surveyOpts)
if err != nil {
return nil, err
}
}
}
if string(config.Spec.Kind) != "" {
data.Spec.Kind = config.Spec.Kind
} else {
if string(data.Spec.Kind) == "" {
data.Spec.Kind = v1.EnvironmentKindTypePermanent
}
}
if config.Spec.Label != "" {
data.Spec.Label = config.Spec.Label
} else {
defaultValue := data.Spec.Label
if defaultValue == "" {
defaultValue = strings.Title(data.Name)
}
q := &survey.Input{
Message: "Label:",
Default: defaultValue,
Help: "The Environment label is a person friendly descriptive text like 'Staging' or 'Production'",
}
err := survey.AskOne(q, &data.Spec.Label, survey.Required, surveyOpts)
if err != nil {
return nil, err
}
}
if config.Spec.Namespace != "" {
err := ValidNameOption(OptionNamespace, config.Spec.Namespace)
if err != nil {
return nil, err
}
data.Spec.Namespace = config.Spec.Namespace
} else {
defaultValue := data.Spec.Namespace
if defaultValue == "" {
// lets use the namespace as a team name
defaultValue = data.Namespace
if defaultValue == "" {
defaultValue = ns
}
if data.Name != "" {
if defaultValue == "" {
defaultValue = data.Name
} else {
defaultValue += "-" + data.Name
}
}
}
if batchMode {
data.Spec.Namespace = defaultValue
} else {
q := &survey.Input{
Message: "Namespace:",
Default: defaultValue,
Help: "The Kubernetes namespace name to use for this Environment",
}
err := survey.AskOne(q, &data.Spec.Namespace, ValidateName, surveyOpts)
if err != nil {
return nil, err
}
}
}
if helmValues.ExposeController.Config.Domain == "" {
ic, err := GetIngressConfig(kubeClient, ns)
if err != nil {
return nil, err
}
if batchMode {
log.Infof("Running in batch mode and no domain flag used so defaulting to team domain %s\n", ic.Domain)
helmValues.ExposeController.Config.Domain = ic.Domain
} else {
q := &survey.Input{
Message: "Domain:",
Default: ic.Domain,
Help: "Domain to expose ingress endpoints. Example: jenkinsx.io, leave blank if no appplications are to be exposed via ingress rules",
}
err := survey.AskOne(q, &helmValues.ExposeController.Config.Domain, nil, surveyOpts)
if err != nil {
return nil, err
}
}
}
if config.Spec.Cluster != "" {
data.Spec.Cluster = config.Spec.Cluster
} else {
// lets not show the UI for this if users specify the namespace via arguments
if !createMode || config.Spec.Namespace == "" {
defaultValue := data.Spec.Cluster
if batchMode {
data.Spec.Cluster = defaultValue
} else {
q := &survey.Input{
Message: "Cluster URL:",
Default: defaultValue,
Help: "The Kubernetes cluster URL to use to host this Environment",
}
// TODO validate/transform to match valid kubnernetes cluster syntax
err := survey.AskOne(q, &data.Spec.Cluster, nil, surveyOpts)
if err != nil {
return nil, err
}
}
}
}
if string(config.Spec.PromotionStrategy) != "" {
data.Spec.PromotionStrategy = config.Spec.PromotionStrategy
} else {
promoteValues := []string{
string(v1.PromotionStrategyTypeAutomatic),
string(v1.PromotionStrategyTypeManual),
string(v1.PromotionStrategyTypeNever),
}
defaultValue := string(data.Spec.PromotionStrategy)
if defaultValue == "" {
defaultValue = string(v1.PromotionStrategyTypeAutomatic)
}
q := &survey.Select{
Message: "Promotion Strategy:",
Options: promoteValues,
Default: defaultValue,
Help: "Whether we promote to this Environment automatically, manually or never",
}
textValue := ""
err := survey.AskOne(q, &textValue, survey.Required, surveyOpts)
if err != nil {
return nil, err
}
if textValue != "" {
data.Spec.PromotionStrategy = v1.PromotionStrategyType(textValue)
}
}
if string(data.Spec.PromotionStrategy) == "" {
data.Spec.PromotionStrategy = v1.PromotionStrategyTypeAutomatic
}
if config.Spec.Order != 0 {
data.Spec.Order = config.Spec.Order
} else {
order := data.Spec.Order
if order == 0 {
// TODO should we generate an order to default to last one?
order = 100
}
defaultValue := util.Int32ToA(order)
q := &survey.Input{
Message: "Order:",
Default: defaultValue,
Help: "This number is used to sort Environments in sequential order, lowest first",
}
textValue := ""
err := survey.AskOne(q, &textValue, survey.Required, surveyOpts)
if err != nil {
return nil, err
}
if textValue != "" {
i, err := util.AtoInt32(textValue)
if err != nil {
return nil, fmt.Errorf("Failed to convert input '%s' to number: %s", textValue, err)
}
data.Spec.Order = i
}
}
createRepo := false
if config.Spec.Source.URL != "" {
data.Spec.Source.URL = config.Spec.Source.URL
} else {
showUrlEdit := devEnv.Spec.TeamSettings.UseGitOPs
if data.Spec.Source.URL == "" {
if devEnv.Spec.TeamSettings.AskOnCreate {
confirm := &survey.Confirm{
Message: "Would you like to use GitOps to manage this environment? :",
Default: false,
}
err := survey.AskOne(confirm, &showUrlEdit, nil, surveyOpts)
if err != nil {
return nil, err
}
} else {
showUrlEdit = true
}
}
if showUrlEdit {
if data.Spec.Source.URL == "" {
if batchMode {
createRepo = true
} else {
confirm := &survey.Confirm{
Message: fmt.Sprintf("We will now create a Git repository to store your %s environment, ok? :", data.Name),
Default: true,
}
err := survey.AskOne(confirm, &createRepo, nil, surveyOpts)
if err != nil {
return nil, err
}
}
if createRepo {
showUrlEdit = false
url, p, err := createEnvironmentGitRepo(batchMode, authConfigSvc, data, forkEnvGitURL, envDir, gitRepoOptions, helmValues, prefix, git, in, out, errOut)
if err != nil {
return nil, err
}
gitProvider = p
data.Spec.Source.URL = url
}
} else {
showUrlEdit = true
}
if showUrlEdit {
q := &survey.Input{
Message: "Git URL for the Environment source code:",
Default: data.Spec.Source.URL,
Help: "The git clone URL for the Environment's Helm charts source code and custom configuration",
}
err := survey.AskOne(q, &data.Spec.Source.URL, survey.Required, surveyOpts)
if err != nil {
return nil, err
}
}
}
}
if config.Spec.Source.Ref != "" {
data.Spec.Source.Ref = config.Spec.Source.Ref
} else {
if data.Spec.Source.URL != "" || data.Spec.Source.Ref != "" {
if batchMode {
createRepo = true
} else {
defaultBranch := data.Spec.Source.Ref
if defaultBranch == "" {
defaultBranch = "master"
}
q := &survey.Input{
Message: "Git branch for the Environment source code:",
Default: defaultBranch,
Help: "The Git release branch in the Environments Git repository used to store Helm charts source code and custom configuration",
}
err := survey.AskOne(q, &data.Spec.Source.Ref, nil, surveyOpts)
if err != nil {
return nil, err
}
}
}
}
return gitProvider, nil
}
func createEnvironmentGitRepo(batchMode bool, authConfigSvc auth.AuthConfigService, env *v1.Environment, forkEnvGitURL string,
environmentsDir string, gitRepoOptions *gits.GitRepositoryOptions, helmValues config.HelmValuesConfig, prefix string, git gits.Gitter, in terminal.FileReader, out terminal.FileWriter, outErr io.Writer) (string, gits.GitProvider, error) {
defaultRepoName := fmt.Sprintf("environment-%s-%s", prefix, env.Name)
details, err := gits.PickNewGitRepository(batchMode, authConfigSvc, defaultRepoName, gitRepoOptions, nil, nil, git, in, out, outErr)
if err != nil {
return "", nil, err
}
org := details.Organisation
repoName := details.RepoName
owner := org
if owner == "" {
owner = details.User.Username
}
envDir := filepath.Join(environmentsDir, owner)
provider := details.GitProvider
repo, err := provider.GetRepository(owner, repoName)
if err == nil {
fmt.Fprintf(out, "Git repository %s/%s already exists\n", util.ColorInfo(owner), util.ColorInfo(repoName))
// if the repo already exists then lets just modify it if required
dir, err := util.CreateUniqueDirectory(envDir, details.RepoName, util.MaximumNewDirectoryAttempts)
if err != nil {
return "", nil, err
}
pushGitURL, err := git.CreatePushURL(repo.CloneURL, details.User)
if err != nil {
return "", nil, err
}
err = git.Clone(pushGitURL, dir)
if err != nil {
return "", nil, err
}
err = ModifyNamespace(out, dir, env, git)
if err != nil {
return "", nil, err
}
err = addValues(out, dir, helmValues, git)
if err != nil {
return "", nil, err
}
err = git.PushMaster(dir)
if err != nil {
return "", nil, err
}
fmt.Fprintf(out, "Pushed Git repository to %s\n\n", util.ColorInfo(repo.HTMLURL))
} else {
fmt.Fprintf(out, "Creating Git repository %s/%s\n", util.ColorInfo(owner), util.ColorInfo(repoName))
if forkEnvGitURL != "" {
gitInfo, err := gits.ParseGitURL(forkEnvGitURL)
if err != nil {
return "", nil, err
}
originalOrg := gitInfo.Organisation
originalRepo := gitInfo.Name
if useForkForEnvGitRepo && gitInfo.IsGitHub() && provider.IsGitHub() && originalOrg != "" && originalRepo != "" {
// lets try fork the repository and rename it
repo, err := provider.ForkRepository(originalOrg, originalRepo, org)
if err != nil {
return "", nil, fmt.Errorf("Failed to fork GitHub repo %s/%s to organisation %s due to %s", originalOrg, originalRepo, org, err)
}
if repoName != originalRepo {
repo, err = provider.RenameRepository(owner, originalRepo, repoName)
if err != nil {
return "", nil, fmt.Errorf("Failed to rename GitHub repo %s/%s to organisation %s due to %s", originalOrg, originalRepo, repoName, err)
}
}
fmt.Fprintf(out, "Forked Git repository to %s\n\n", util.ColorInfo(repo.HTMLURL))
dir, err := util.CreateUniqueDirectory(envDir, repoName, util.MaximumNewDirectoryAttempts)
if err != nil {
return "", nil, err
}
err = git.Clone(repo.CloneURL, dir)
if err != nil {
return "", nil, err
}
err = git.SetRemoteURL(dir, "upstream", forkEnvGitURL)
if err != nil {
return "", nil, err
}
err = git.PullUpstream(dir)
if err != nil {
return "", nil, err
}
err = ModifyNamespace(out, dir, env, git)
if err != nil {
return "", nil, err
}
err = addValues(out, dir, helmValues, git)
if err != nil {
return "", nil, err
}
err = git.Push(dir)
if err != nil {
return "", nil, err
}
return repo.CloneURL, provider, nil
}
}
// default to forking the URL if possible...
repo, err = details.CreateRepository()
if err != nil {
return "", nil, err
}
if forkEnvGitURL != "" {
// now lets clone the fork and push it...
dir, err := util.CreateUniqueDirectory(envDir, details.RepoName, util.MaximumNewDirectoryAttempts)
if err != nil {
return "", nil, err
}
err = git.Clone(forkEnvGitURL, dir)
if err != nil {
return "", nil, err
}
pushGitURL, err := git.CreatePushURL(repo.CloneURL, details.User)
if err != nil {
return "", nil, err
}
err = git.AddRemote(dir, "upstream", forkEnvGitURL)
if err != nil {
return "", nil, err
}
err = git.UpdateRemote(dir, pushGitURL)
if err != nil {
return "", nil, err
}
err = ModifyNamespace(out, dir, env, git)
if err != nil {
return "", nil, err
}
err = addValues(out, dir, helmValues, git)
if err != nil {
return "", nil, err
}
err = git.PushMaster(dir)
if err != nil {
return "", nil, err
}
fmt.Fprintf(out, "Pushed Git repository to %s\n\n", util.ColorInfo(repo.HTMLURL))
}
}
return repo.CloneURL, provider, nil
}
// ModifyNamespace modifies the namespace
func ModifyNamespace(out io.Writer, dir string, env *v1.Environment, git gits.Gitter) error {
ns := env.Spec.Namespace
if ns == "" {
return fmt.Errorf("No Namespace is defined for Environment %s", env.Name)
}
// makefile changes
file := filepath.Join(dir, "Makefile")
exists, err := util.FileExists(file)
if err != nil {
return err
}
if !exists {
log.Warnf("WARNING: Could not find a Makefile in %s\n", dir)
return nil
}
input, err := ioutil.ReadFile(file)
if err != nil {
return err
}
lines := strings.Split(string(input), "\n")
err = ReplaceMakeVariable(lines, "NAMESPACE", "\""+ns+"\"")
if err != nil {
return err
}
output := strings.Join(lines, "\n")
err = ioutil.WriteFile(file, []byte(output), 0644)
if err != nil {
return err
}
// Jenkinsfile changes
file = filepath.Join(dir, "Jenkinsfile")
exists, err = util.FileExists(file)
if err != nil {
return err
}
if !exists {
log.Warnf("WARNING: Could not find a Jenkinsfile in %s\n", dir)
} else {
input, err := ioutil.ReadFile(file)
if err != nil {
return err
}
lines := strings.Split(string(input), "\n")
err = replaceEnvVar(lines, "DEPLOY_NAMESPACE", ns)
if err != nil {
return err
}
output := strings.Join(lines, "\n")
err = ioutil.WriteFile(file, []byte(output), 0644)
if err != nil {
return err
}
}
err = git.Add(dir, "*")
if err != nil {
return err
}
changes, err := git.HasChanges(dir)
if err != nil {
return err
}
if changes {
return git.CommitDir(dir, "Use correct namespace for environment")
}
return nil
}
func addValues(out io.Writer, dir string, values config.HelmValuesConfig, git gits.Gitter) error {
file := filepath.Join(dir, "env", "values.yaml")
exists, err := util.FileExists(file)
if err != nil {
return err
}
if !exists {
return fmt.Errorf("could not find a values.yaml in %s\n", dir)
}
f, err := os.OpenFile(file, os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
return err
}
text, err := values.String()
if err != nil {
return err
}
_, err = f.WriteString(text)
if err != nil {
return err
}
f.Close()
err = git.Add(dir, "*")
if err != nil {
return err
}
changes, err := git.HasChanges(dir)
if err != nil {
return err
}
if changes {
return git.CommitDir(dir, "Add environment configuration")
}
return nil
}
// ReplaceMakeVariable needs a description
func ReplaceMakeVariable(lines []string, name string, value string) error {
re, err := regexp.Compile(name + "\\s*:?=\\s*(.*)")
if err != nil {
return err
}
replaceValue := name + " := " + value
for i, line := range lines {
lines[i] = re.ReplaceAllString(line, replaceValue)
}
return nil
}
func replaceEnvVar(lines []string, name string, value string) error {
for i, line := range lines {
trimmed := strings.TrimSpace(line)
if strings.HasPrefix(trimmed, name) {
remain := strings.TrimSpace(strings.TrimPrefix(trimmed, name))
if strings.HasPrefix(remain, "=") {
// lets preserve whitespace
idx := strings.Index(line, name)
lines[i] = line[0:idx] + name + ` = "` + value + `"`
}
}
}
return nil
}
// GetEnvironmentNames returns the sorted list of environment names
func GetEnvironmentNames(jxClient versioned.Interface, ns string) ([]string, error) {
envNames := []string{}
envs, err := jxClient.JenkinsV1().Environments(ns).List(metav1.ListOptions{})
if err != nil {
return envNames, err
}
SortEnvironments(envs.Items)
for _, env := range envs.Items {
n := env.Name
if n != "" {
envNames = append(envNames, n)
}
}
sort.Strings(envNames)
return envNames, nil
}
func IsPreviewEnvironment(env *v1.Environment) bool {
return env != nil && env.Spec.Kind == v1.EnvironmentKindTypePreview
}
// GetFilteredEnvironmentNames returns the sorted list of environment names
func GetFilteredEnvironmentNames(jxClient versioned.Interface, ns string, fn func(environment *v1.Environment) bool) ([]string, error) {
envNames := []string{}
envs, err := jxClient.JenkinsV1().Environments(ns).List(metav1.ListOptions{})
if err != nil {
return envNames, err
}
SortEnvironments(envs.Items)
for _, env := range envs.Items {
n := env.Name
if n != "" && fn(&env) {
envNames = append(envNames, n)
}
}
sort.Strings(envNames)
return envNames, nil
}
// GetOrderedEnvironments returns a map of the environments along with the correctly ordered names
func GetOrderedEnvironments(jxClient versioned.Interface, ns string) (map[string]*v1.Environment, []string, error) {
m := map[string]*v1.Environment{}
envNames := []string{}
envs, err := jxClient.JenkinsV1().Environments(ns).List(metav1.ListOptions{})
if err != nil {
return m, envNames, err
}
SortEnvironments(envs.Items)
for _, env := range envs.Items {
n := env.Name
copy := env
m[n] = ©
if n != "" {
envNames = append(envNames, n)
}
}
return m, envNames, nil
}
// GetEnvironments returns a map of the environments along with a sorted list of names
func GetEnvironments(jxClient versioned.Interface, ns string) (map[string]*v1.Environment, []string, error) {
m := map[string]*v1.Environment{}
envNames := []string{}
envs, err := jxClient.JenkinsV1().Environments(ns).List(metav1.ListOptions{})
if err != nil {
return m, envNames, err
}
for _, env := range envs.Items {
n := env.Name
copy := env
m[n] = ©
if n != "" {
envNames = append(envNames, n)
}
}
sort.Strings(envNames)
return m, envNames, nil
}
// GetEnvironment find an environment by name
func GetEnvironment(jxClient versioned.Interface, ns string, name string) (*v1.Environment, error) {
envs, err := jxClient.JenkinsV1().Environments(ns).List(metav1.ListOptions{})
if err != nil {
return nil, err
}
for _, env := range envs.Items {
if env.GetName() == name {
return &env, nil
}
}
return nil, fmt.Errorf("no environment with name '%s' found", name)
}
// GetEnvironmentsByPrURL find an environment by a pull request URL
func GetEnvironmentsByPrURL(jxClient versioned.Interface, ns string, prURL string) (*v1.Environment, error) {
envs, err := jxClient.JenkinsV1().Environments(ns).List(metav1.ListOptions{})
if err != nil {
return nil, err
}
for _, env := range envs.Items {
if env.Spec.PullRequestURL == prURL {
return &env, nil
}
}
return nil, fmt.Errorf("no environment found for PR '%s'", prURL)
}
// GetEnvironments returns the namespace name for a given environment
func GetEnvironmentNamespace(jxClient versioned.Interface, ns, environment string) (string, error) {
env, err := jxClient.JenkinsV1().Environments(ns).Get(environment, metav1.GetOptions{})
if err != nil {
return "", err
}
if env == nil {
return "", fmt.Errorf("no environment found called %s, try running `jx get env`", environment)
}
return env.Spec.Namespace, nil
}
// GetEditEnvironmentNamespace returns the namespace of the current users edit environment
func GetEditEnvironmentNamespace(jxClient versioned.Interface, ns string) (string, error) {
envs, err := jxClient.JenkinsV1().Environments(ns).List(metav1.ListOptions{})
if err != nil {
return "", err
}
u, err := user.Current()
if err != nil {
return "", err
}
for _, env := range envs.Items {
if env.Spec.Kind == v1.EnvironmentKindTypeEdit && env.Spec.PreviewGitSpec.User.Username == u.Username {
return env.Spec.Namespace, nil
}
}
return "", fmt.Errorf("The user %s does not have an Edit environment in home namespace %s", u.Username, ns)
}
// GetDevNamespace returns the developer environment namespace
// which is the namespace that contains the Environments and the developer tools like Jenkins
func GetDevNamespace(kubeClient kubernetes.Interface, ns string) (string, string, error) {
env := ""
namespace, err := kubeClient.CoreV1().Namespaces().Get(ns, metav1.GetOptions{})
if err != nil {
return ns, env, err
}
if namespace == nil {
return ns, env, fmt.Errorf("No namespace found for %s", ns)
}
if namespace.Labels != nil {
answer := namespace.Labels[LabelTeam]
if answer != "" {
ns = answer
}
env = namespace.Labels[LabelEnvironment]
}
return ns, env, nil
}
// GetTeams returns the Teams the user is a member of
func GetTeams(kubeClient kubernetes.Interface) ([]*corev1.Namespace, []string, error) {
names := []string{}
answer := []*corev1.Namespace{}
namespaceList, err := kubeClient.CoreV1().Namespaces().List(metav1.ListOptions{})
if err != err {
return answer, names, err
}
for idx, namespace := range namespaceList.Items {
if namespace.Labels[LabelEnvironment] == LabelValueDevEnvironment {
answer = append(answer, &namespaceList.Items[idx])
names = append(names, namespace.Name)
}
}
sort.Strings(names)
return answer, names, nil
}
func PickEnvironment(envNames []string, defaultEnv string, in terminal.FileReader, out terminal.FileWriter, errOut io.Writer) (string, error) {
surveyOpts := survey.WithStdio(in, out, errOut)
name := ""
if len(envNames) == 0 {
return "", nil
} else if len(envNames) == 1 {
name = envNames[0]
} else {
prompt := &survey.Select{
Message: "Pick environment:",
Options: envNames,
Default: defaultEnv,
}
err := survey.AskOne(prompt, &name, nil, surveyOpts)
if err != nil {
return "", err
}
}
return name, nil
}
type ByOrder []v1.Environment
func (a ByOrder) Len() int { return len(a) }
func (a ByOrder) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByOrder) Less(i, j int) bool {
env1 := a[i]
env2 := a[j]
o1 := env1.Spec.Order
o2 := env2.Spec.Order
if o1 == o2 {
return env1.Name < env2.Name
}
return o1 < o2
}
func SortEnvironments(environments []v1.Environment) {
sort.Sort(ByOrder(environments))
}
// NewPermanentEnvironment creates a new permanent environment for testing
func NewPermanentEnvironment(name string) *v1.Environment {
return &v1.Environment{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: "jx",
},
Spec: v1.EnvironmentSpec{
Label: strings.Title(name),
Namespace: "jx-" + name,
PromotionStrategy: v1.PromotionStrategyTypeAutomatic,
Kind: v1.EnvironmentKindTypePermanent,
},
}
}
// NewPermanentEnvironment creates a new permanent environment for testing
func NewPermanentEnvironmentWithGit(name string, gitUrl string) *v1.Environment {
env := NewPermanentEnvironment(name)
env.Spec.Source.URL = gitUrl
env.Spec.Source.Ref = "master"
return env
}
// NewPreviewEnvironment creates a new preview environment for testing
func NewPreviewEnvironment(name string) *v1.Environment {
return &v1.Environment{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: "jx",
},
Spec: v1.EnvironmentSpec{
Label: strings.Title(name),
Namespace: "jx-preview-" + name,
PromotionStrategy: v1.PromotionStrategyTypeAutomatic,
Kind: v1.EnvironmentKindTypePreview,
},
}
}