-
Notifications
You must be signed in to change notification settings - Fork 787
/
step_verify_environments.go
546 lines (476 loc) · 19 KB
/
step_verify_environments.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
package verify
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"github.com/jenkins-x/jx/pkg/boot"
"github.com/jenkins-x/jx/pkg/helm"
"sigs.k8s.io/yaml"
"github.com/jenkins-x/jx/pkg/cmd/opts/step"
v1 "github.com/jenkins-x/jx/pkg/apis/jenkins.io/v1"
"github.com/jenkins-x/jx/pkg/auth"
"github.com/jenkins-x/jx/pkg/cmd/helper"
"github.com/jenkins-x/jx/pkg/cmd/opts"
"github.com/jenkins-x/jx/pkg/config"
"github.com/jenkins-x/jx/pkg/gits"
"github.com/jenkins-x/jx/pkg/kube"
"github.com/jenkins-x/jx/pkg/log"
"github.com/jenkins-x/jx/pkg/util"
"github.com/pkg/errors"
"github.com/spf13/cobra"
corev1 "k8s.io/api/core/v1"
)
const (
jxInterpretPipelineEnvKey = "JX_INTERPRET_PIPELINE"
gitAuthorNameEnvKey = "GIT_AUTHOR_NAME"
gitAuthorEmailEnvKey = "GIT_AUTHOR_EMAIL"
gitCommitterNameEnvKey = "GIT_COMMITTER_NAME"
gitCommitterEmailEnvKey = "GIT_COMMITTER_EMAIL"
)
// StepVerifyEnvironmentsOptions contains the command line flags
type StepVerifyEnvironmentsOptions struct {
StepVerifyOptions
Dir string
}
// NewCmdStepVerifyEnvironments creates the `jx step verify pod` command
func NewCmdStepVerifyEnvironments(commonOpts *opts.CommonOptions) *cobra.Command {
options := &StepVerifyEnvironmentsOptions{
StepVerifyOptions: StepVerifyOptions{
StepOptions: step.StepOptions{
CommonOptions: commonOpts,
},
},
}
cmd := &cobra.Command{
Use: "environments",
Aliases: []string{"environment", "env"},
Short: "Verifies that the Environments have valid git repositories setup - lazily creating them if needed",
Run: func(cmd *cobra.Command, args []string) {
options.Cmd = cmd
options.Args = args
err := options.Run()
helper.CheckErr(err)
},
}
cmd.Flags().StringVarP(&options.Dir, "dir", "d", "", fmt.Sprintf("The directory to look for the %s file, by default the current working directory", config.RequirementsConfigFileName))
return cmd
}
// Run implements this command
func (o *StepVerifyEnvironmentsOptions) Run() error {
jxClient, ns, err := o.JXClientAndDevNamespace()
if err != nil {
return err
}
requirements, requirementsFileName, err := config.LoadRequirementsConfig(o.Dir)
if err != nil {
return err
}
info := util.ColorInfo
exists, err := util.FileExists(requirementsFileName)
if err != nil {
return err
}
envMap, names, err := kube.GetEnvironments(jxClient, ns)
if err != nil {
return errors.Wrapf(err, "failed to load Environments in namespace %s", ns)
}
if exists {
// lets store the requirements in the team settings now so that when we create the git auth provider
// we will be able to detect if we are using GitHub App secrets or not
err = o.storeRequirementsInTeamSettings(requirements)
if err != nil {
return err
}
} else {
devEnv := envMap[kube.LabelValueDevEnvironment]
if devEnv != nil {
requirements, err = config.GetRequirementsConfigFromTeamSettings(&devEnv.Spec.TeamSettings)
if err != nil {
return errors.Wrap(err, "failed to load requirements from team settings")
}
}
}
for _, name := range names {
env := envMap[name]
gitURL := env.Spec.Source.URL
if gitURL != "" && (env.Spec.Kind == v1.EnvironmentKindTypePermanent || (env.Spec.Kind == v1.EnvironmentKindTypeDevelopment && requirements.GitOps)) {
log.Logger().Infof("Validating git repository for %s environment at URL %s\n", info(name), info(gitURL))
err = o.updateEnvironmentIngressConfig(requirements, requirementsFileName, env)
if err != nil {
return errors.Wrapf(err, "updating the ingress config for environment %q", env.GetName())
}
err = o.validateGitRepository(name, requirements, env, gitURL)
if err != nil {
return err
}
}
}
log.Logger().Infof("Environment git repositories look good\n")
fmt.Println()
return nil
}
func (o *StepVerifyEnvironmentsOptions) prDevEnvironment(gitRepoName string, environmentsOrg string, privateRepo bool, user *auth.UserAuth, requirements *config.RequirementsConfig, server *auth.AuthServer, createPr bool) error {
fromGitURL := os.Getenv(boot.ConfigRepoURLEnvVarName)
gitRef := os.Getenv(boot.ConfigBaseRefEnvVarName)
log.Logger().Debugf("Defined %s env variable value: %s", boot.ConfigRepoURLEnvVarName, fromGitURL)
log.Logger().Debugf("Defined %s env variable value: %s", boot.ConfigBaseRefEnvVarName, gitRef)
_, err := gits.ParseGitURL(fromGitURL)
if err != nil {
return err
}
log.Logger().Infof("The environment git repositories look good\n")
fmt.Println()
return nil
}
func (o *StepVerifyEnvironmentsOptions) storeRequirementsInTeamSettings(requirements *config.RequirementsConfig) error {
log.Logger().Infof("Storing the requirements in team settings in the dev environment\n")
err := o.ModifyDevEnvironment(func(env *v1.Environment) error {
log.Logger().Debugf("Updating the TeamSettings with: %+v", requirements)
reqBytes, err := yaml.Marshal(requirements)
if err != nil {
return errors.Wrap(err, "there was a problem marshalling the requirements file to include it in the TeamSettings")
}
env.Spec.TeamSettings.BootRequirements = string(reqBytes)
return nil
})
if err != nil {
return errors.Wrap(err, "there was a problem saving the current state of the requirements.yaml file in TeamSettings in the dev environment")
}
return nil
}
// isJXBoot returns true if this code is executed as part of jx boot, false otherwise.
func (o *StepVerifyEnvironmentsOptions) isJXBoot() bool {
// sort of a hack to determine that `jx boot` is executed opposed to running as a pipeline build
// see step_create_task where JX_INTERPRET_PIPELINE is set when the pipeline is executed in interpret mode
// which in turn is set by `jx boot` (HF)
return os.Getenv(jxInterpretPipelineEnvKey) == "true"
}
// readEnvironment returns the repository URL as well as the git ref for original boot config repo.
// An error is returned in case any of the require environment variables needed to setup the environment repository
// is missing.
func (o *StepVerifyEnvironmentsOptions) readEnvironment() (string, string, error) {
var missingRepoURLErr, missingReoRefErr error
fromGitURL, foundURL := os.LookupEnv(boot.ConfigRepoURLEnvVarName)
if !foundURL {
missingRepoURLErr = errors.Errorf("the environment variable %s must be specified", boot.ConfigRepoURLEnvVarName)
}
gitRef, foundRef := os.LookupEnv(boot.ConfigBaseRefEnvVarName)
if !foundRef {
missingReoRefErr = errors.Errorf("the environment variable %s must be specified", boot.ConfigBaseRefEnvVarName)
}
err := util.CombineErrors(missingRepoURLErr, missingReoRefErr)
if err == nil {
log.Logger().Debugf("Defined %s env variable value: %s", boot.ConfigRepoURLEnvVarName, fromGitURL)
log.Logger().Debugf("Defined %s env variable value: %s", boot.ConfigBaseRefEnvVarName, gitRef)
}
return fromGitURL, gitRef, err
}
func (o *StepVerifyEnvironmentsOptions) modifyPipelineGitEnvVars(dir string) error {
parameterValues, err := helm.LoadParametersValuesFile(dir)
if err != nil {
return errors.Wrap(err, "failed to load parameters values file")
}
username := util.GetMapValueAsStringViaPath(parameterValues, "pipelineUser.username")
email := util.GetMapValueAsStringViaPath(parameterValues, "pipelineUser.email")
if username != "" && email != "" {
fileName := filepath.Join(dir, config.ProjectConfigFileName)
projectConf, err := config.LoadProjectConfigFile(fileName)
if err != nil {
return errors.Wrapf(err, "failed to load project config file %s", fileName)
}
envVars := projectConf.PipelineConfig.Pipelines.Release.Pipeline.Environment
envVars, err = o.setEnvVarInPipelineAndCurrentEnv(gitAuthorNameEnvKey, username, envVars)
if err != nil {
return err
}
envVars, err = o.setEnvVarInPipelineAndCurrentEnv(gitCommitterNameEnvKey, username, envVars)
if err != nil {
return err
}
envVars, err = o.setEnvVarInPipelineAndCurrentEnv(gitAuthorEmailEnvKey, email, envVars)
if err != nil {
return err
}
envVars, err = o.setEnvVarInPipelineAndCurrentEnv(gitCommitterEmailEnvKey, email, envVars)
if err != nil {
return err
}
projectConf.PipelineConfig.Pipelines.Release.Pipeline.Environment = envVars
err = projectConf.SaveConfig(fileName)
if err != nil {
return errors.Wrapf(err, "failed to write to %s", fileName)
}
}
return nil
}
func (o *StepVerifyEnvironmentsOptions) setEnvVarInPipelineAndCurrentEnv(envVarName string, envVarValue string, envVars []corev1.EnvVar) ([]corev1.EnvVar, error) {
if !o.envVarsHasEntry(envVars, envVarName) {
envVars = append(envVars, corev1.EnvVar{
Name: envVarName,
Value: envVarValue,
})
}
err := os.Setenv(envVarName, envVarValue)
if err != nil {
return nil, errors.Wrapf(err, "failed to set %s env variable", envVarName)
}
return envVars, nil
}
func (o *StepVerifyEnvironmentsOptions) envVarsHasEntry(envVars []corev1.EnvVar, key string) bool {
for _, entry := range envVars {
if entry.Name == key {
return true
}
}
return false
}
func (o *StepVerifyEnvironmentsOptions) validateGitRepository(name string, requirements *config.RequirementsConfig, environment *v1.Environment, gitURL string) error {
message := fmt.Sprintf("for environment %s", environment.Name)
envGitInfo, err := gits.ParseGitURL(gitURL)
if err != nil {
return errors.Wrapf(err, "failed to parse git URL %s and %s", gitURL, message)
}
authConfigSvc, err := o.CreatePipelineUserGitAuthConfigService()
if err != nil {
return err
}
return o.createEnvironmentRepository(name, requirements, authConfigSvc, environment, gitURL, envGitInfo)
}
func (o *StepVerifyEnvironmentsOptions) createEnvironmentRepository(name string, requirements *config.RequirementsConfig, authConfigSvc auth.ConfigService, environment *v1.Environment, gitURL string, envGitInfo *gits.GitRepository) error {
envDir, err := ioutil.TempDir("", "jx-env-repo-")
if err != nil {
return err
}
gha, err := o.IsGitHubAppMode()
if err != nil {
return err
}
gitOwner := envGitInfo.Organisation
// TODO - this is hard coded to GitHub and needs to be extended to support other git providers (HF)
gitKind := gits.KindGitHub
public := requirements.Cluster.EnvironmentGitPublic
prefix := ""
gitServerURL := envGitInfo.HostURL()
config := authConfigSvc.Config()
server, userAuth := config.GetPipelineAuth()
if gha {
userAuth = nil
if server == nil {
for _, s := range config.Servers {
if s.URL == gitServerURL {
server = s
break
}
}
}
if server != nil {
for _, u := range server.Users {
if gitOwner == u.GithubAppOwner {
userAuth = u
break
}
}
}
}
helmValues, err := o.createEnvironmentHelmValues(requirements, environment)
if err != nil {
return err
}
batchMode := o.BatchMode
forkGitURL := kube.DefaultEnvironmentGitRepoURL
if server == nil {
return fmt.Errorf("no auth server found for git server %s from gitURL %s", gitServerURL, gitURL)
}
if userAuth == nil {
return fmt.Errorf("no pipeline user found for git server %s from gitURL %s", gitServerURL, gitURL)
}
if userAuth.IsInvalid() {
return errors.Wrapf(err, "validating user '%s' of server '%s'", userAuth.Username, server.Name)
}
gitter := o.Git()
gitUserName, gitUserEmail, err := gits.EnsureUserAndEmailSetup(gitter)
if err != nil {
return errors.Wrapf(err, "couldn't configure git with user %s and email %s", gitUserName, gitUserEmail)
}
if name == kube.LabelValueDevEnvironment || environment.Spec.Kind == v1.EnvironmentKindTypeDevelopment {
if o.isJXBoot() && requirements.GitOps {
provider, err := envGitInfo.CreateProviderForUser(server, userAuth, gitKind, gitter)
if err != nil {
return errors.Wrap(err, "unable to create git provider")
}
err = o.handleDevEnvironmentRepository(envGitInfo, public, provider, gitter, requirements)
if err != nil {
return err
}
}
} else {
gitRepoOptions := &gits.GitRepositoryOptions{
ServerURL: gitServerURL,
ServerKind: gitKind,
Username: userAuth.Username,
ApiToken: userAuth.Password,
Owner: gitOwner,
RepoName: envGitInfo.Name,
Public: public,
IgnoreExistingRepository: true,
}
_, _, err = kube.DoCreateEnvironmentGitRepo(batchMode, authConfigSvc, environment, forkGitURL, envDir, gitRepoOptions, helmValues, prefix, gitter, o.ResolveChartMuseumURL, o.GetIOFileHandles())
if err != nil {
return errors.Wrapf(err, "failed to create git repository for gitURL %s", gitURL)
}
}
return nil
}
func (o *StepVerifyEnvironmentsOptions) handleDevEnvironmentRepository(envGitInfo *gits.GitRepository, public bool, provider gits.GitProvider, gitter gits.Gitter, requirements *config.RequirementsConfig) error {
fromGitURL, fromBaseRef, err := o.readEnvironment()
if err != nil {
return err
}
dir, err := filepath.Abs(o.Dir)
if err != nil {
return errors.Wrapf(err, "resolving %s to absolute path", o.Dir)
}
environmentRepo, err := provider.GetRepository(envGitInfo.Organisation, envGitInfo.Name)
// Assuming an error implies the repo does not exist. There is currently no way to distinguish between error and non existing repo
// see https://github.com/jenkins-x/jx/issues/5822
if err != nil {
environmentRepo, err = o.createDevEnvironmentRepository(envGitInfo, dir, fromGitURL, fromBaseRef, !public, requirements, provider, gitter)
if err != nil {
return errors.Wrapf(err, "creating remote for dev environment %s", envGitInfo.Name)
}
}
err = o.pushDevEnvironmentUpdates(environmentRepo, dir, provider, gitter)
if err != nil {
return errors.Wrapf(err, "error updating dev environment for %s", envGitInfo.Name)
}
// Add a remote for the user that references the boot config that they originally used
err = gitter.SetRemoteURL(dir, "jenkins-x", fromGitURL)
if err != nil {
return errors.Wrapf(err, "setting jenkins-x remote to boot config %s", fromGitURL)
}
return nil
}
func (o *StepVerifyEnvironmentsOptions) createDevEnvironmentRepository(gitInfo *gits.GitRepository, localRepoDir string, fromGitURL string, fromGitRef string, privateRepo bool, requirements *config.RequirementsConfig, provider gits.GitProvider, gitter gits.Gitter) (*gits.GitRepository, error) {
if fromGitURL == config.DefaultBootRepository && fromGitRef == "master" {
// If the GitURL is not overridden and the GitRef is set to it's default value then look up the version number
resolver, err := o.CreateVersionResolver(requirements.VersionStream.URL, requirements.VersionStream.Ref)
if err != nil {
return nil, errors.Wrapf(err, "failed to create version resolver")
}
fromGitRef, err = resolver.ResolveGitVersion(fromGitURL)
if err != nil {
return nil, errors.Wrapf(err, "failed to resolve version for https://github.com/jenkins-x/jenkins-x-boot-config.git")
}
if fromGitRef == "" {
log.Logger().Infof("Attempting to resolve version for upstream boot config %s", util.ColorInfo(config.DefaultBootRepository))
fromGitRef, err = resolver.ResolveGitVersion(config.DefaultBootRepository)
if err != nil {
return nil, errors.Wrapf(err, "failed to resolve version for https://github.com/jenkins-x/jenkins-x-boot-config.git")
}
}
}
commitish, err := gits.FindTagForVersion(localRepoDir, fromGitRef, gitter)
if err != nil {
log.Logger().Debugf(errors.Wrapf(err, "finding tag for %s", fromGitRef).Error())
commitish = fmt.Sprintf("%s/%s", "origin", fromGitRef)
log.Logger().Debugf("set commitish to '%s'", commitish)
}
duplicateInfo, err := gits.DuplicateGitRepoFromCommitish(gitInfo.Organisation, gitInfo.Name, fromGitURL, commitish, "master", privateRepo, provider, gitter)
if err != nil {
return nil, errors.Wrapf(err, "duplicating %s to %s/%s", fromGitURL, gitInfo.Organisation, gitInfo.Name)
}
return duplicateInfo, nil
}
func (o *StepVerifyEnvironmentsOptions) pushDevEnvironmentUpdates(environmentRepo *gits.GitRepository, localRepoDir string, provider gits.GitProvider, gitter gits.Gitter) error {
_, _, _, _, err := gits.ForkAndPullRepo(environmentRepo.CloneURL, localRepoDir, "master", "master", provider, gitter, environmentRepo.Name)
if err != nil {
return errors.Wrapf(err, "forking and pulling %s", environmentRepo.CloneURL)
}
err = o.modifyPipelineGitEnvVars(localRepoDir)
if err != nil {
return errors.Wrap(err, "failed to modify dev environment config")
}
hasChanges, err := gitter.HasChanges(localRepoDir)
if err != nil {
return errors.Wrap(err, "unable to check for changes")
}
if hasChanges {
err = gitter.Add(localRepoDir, ".")
if err != nil {
return errors.Wrap(err, "unable to add stage commit")
}
err = gitter.CommitDir(localRepoDir, "chore(config): update configuration")
if err != nil {
return errors.Wrapf(err, "unable to commit changes to environment repo in %s", localRepoDir)
}
}
userDetails := provider.UserAuth()
authenticatedPushURL, err := gitter.CreateAuthenticatedURL(environmentRepo.CloneURL, &userDetails)
if err != nil {
return errors.Wrapf(err, "failed to create push URL for %s", environmentRepo.CloneURL)
}
err = gitter.Push(localRepoDir, authenticatedPushURL, true, "master")
if err != nil {
return errors.Wrapf(err, "unable to push %s to %s", localRepoDir, environmentRepo.URL)
}
log.Logger().Infof("Pushed Git repository to %s\n\n", util.ColorInfo(environmentRepo.HTMLURL))
return nil
}
func (o *StepVerifyEnvironmentsOptions) createEnvironmentHelmValues(requirements *config.RequirementsConfig, environment *v1.Environment) (config.HelmValuesConfig, error) {
envCfg, err := requirements.Environment(environment.GetName())
if err != nil || envCfg == nil {
return config.HelmValuesConfig{}, errors.Wrapf(err,
"looking the configuration of environment %q in the requirements configuration", environment.GetName())
}
domain := requirements.Ingress.Domain
if envCfg.Ingress.Domain != "" {
domain = envCfg.Ingress.Domain
}
useHTTP := "true"
tlsAcme := "false"
if envCfg.Ingress.TLS.Enabled {
useHTTP = "false"
tlsAcme = "true"
}
exposer := "Ingress"
helmValues := config.HelmValuesConfig{
ExposeController: &config.ExposeController{
Config: config.ExposeControllerConfig{
Domain: domain,
Exposer: exposer,
HTTP: useHTTP,
TLSAcme: tlsAcme,
URLTemplate: config.ExposeDefaultURLTemplate,
},
Production: envCfg.Ingress.TLS.Production,
},
}
// Only set the secret name if TLS is enabled else exposecontroller thinks the ingress needs TLS
if envCfg.Ingress.TLS.Enabled {
secretName := envCfg.Ingress.TLS.SecretName
if secretName == "" {
if envCfg.Ingress.TLS.Production {
secretName = fmt.Sprintf("tls-%s-p", domain)
} else {
secretName = fmt.Sprintf("tls-%s-s", domain)
}
}
helmValues.ExposeController.Config.TLSSecretName = secretName
}
return helmValues, nil
}
func (o *StepVerifyEnvironmentsOptions) updateEnvironmentIngressConfig(requirements *config.RequirementsConfig, requirementsFileName string, env *v1.Environment) error {
if env.Spec.Kind != v1.EnvironmentKindTypeDevelopment {
return nil
}
// Override the dev environment ingress config from main ingress config
name := env.GetName()
for i, e := range requirements.Environments {
if e.Key == name {
requirements.Environments[i].Ingress = requirements.Ingress
break
}
}
return requirements.SaveConfig(requirementsFileName)
}