forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnewapp.go
1302 lines (1160 loc) · 43.7 KB
/
newapp.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
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package cmd
import (
"encoding/json"
"errors"
"fmt"
"io"
"reflect"
"strings"
"time"
"github.com/fsouza/go-dockerclient"
"github.com/golang/glog"
kerrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
kutilerrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/client-go/discovery"
kapi "k8s.io/kubernetes/pkg/apis/core"
"k8s.io/kubernetes/pkg/apis/core/validation"
kclientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset"
"k8s.io/kubernetes/pkg/kubectl/genericclioptions/resource"
ometa "github.com/openshift/origin/pkg/api/meta"
authapi "github.com/openshift/origin/pkg/authorization/apis/authorization"
buildapi "github.com/openshift/origin/pkg/build/apis/build"
buildutil "github.com/openshift/origin/pkg/build/util"
imageapi "github.com/openshift/origin/pkg/image/apis/image"
imageclient "github.com/openshift/origin/pkg/image/generated/internalclientset/typed/image/internalversion"
dockerregistry "github.com/openshift/origin/pkg/image/importer/dockerv1client"
"github.com/openshift/origin/pkg/oc/lib/newapp"
"github.com/openshift/origin/pkg/oc/lib/newapp/app"
"github.com/openshift/origin/pkg/oc/lib/newapp/dockerfile"
"github.com/openshift/origin/pkg/oc/lib/newapp/jenkinsfile"
"github.com/openshift/origin/pkg/oc/lib/newapp/source"
"github.com/openshift/origin/pkg/oc/util/env"
utilenv "github.com/openshift/origin/pkg/oc/util/env"
routeclient "github.com/openshift/origin/pkg/route/generated/internalclientset/typed/route/internalversion"
templateinternalclient "github.com/openshift/origin/pkg/template/client/internalversion"
templateclient "github.com/openshift/origin/pkg/template/generated/internalclientset/typed/template/internalversion"
outil "github.com/openshift/origin/pkg/util"
)
const (
GeneratedByNamespace = "openshift.io/generated-by"
GeneratedForJob = "openshift.io/generated-job"
GeneratedForJobFor = "openshift.io/generated-job.for"
GeneratedByNewApp = "OpenShiftNewApp"
GeneratedByNewBuild = "OpenShiftNewBuild"
)
// GenerationInputs control how new-app creates output
// TODO: split these into finer grained structs
type GenerationInputs struct {
TemplateParameters []string
Environment []string
BuildEnvironment []string
BuildArgs []string
Labels map[string]string
TemplateParameterFiles []string
EnvironmentFiles []string
BuildEnvironmentFiles []string
IgnoreUnknownParameters bool
InsecureRegistry bool
Strategy generate.Strategy
Name string
To string
NoOutput bool
OutputDocker bool
Dockerfile string
ExpectToBuild bool
BinaryBuild bool
ContextDir string
SourceImage string
SourceImagePath string
Secrets []string
ConfigMaps []string
AllowMissingImageStreamTags bool
Deploy bool
AsTestDeployment bool
AllowGenerationErrors bool
}
// AppConfig contains all the necessary configuration for an application
type AppConfig struct {
ComponentInputs
GenerationInputs
ResolvedComponents *ResolvedComponents
SkipGeneration bool
AllowSecretUse bool
SourceSecret string
PushSecret string
SecretAccessor app.SecretAccessor
AsSearch bool
AsList bool
DryRun bool
In io.Reader
Out io.Writer
ErrOut io.Writer
KubeClient kclientset.Interface
ImageClient imageclient.ImageInterface
RouteClient routeclient.RouteInterface
TemplateClient templateclient.TemplateInterface
DiscoveryClient discovery.DiscoveryInterface
Resolvers
Builder *resource.Builder
Typer runtime.ObjectTyper
Mapper meta.RESTMapper
OriginNamespace string
EnvironmentClassificationErrors map[string]ArgumentClassificationError
SourceClassificationErrors map[string]ArgumentClassificationError
TemplateClassificationErrors map[string]ArgumentClassificationError
ComponentClassificationErrors map[string]ArgumentClassificationError
ClassificationWinners map[string]ArgumentClassificationWinner
}
type ArgumentClassificationError struct {
Key string
Value error
}
type ArgumentClassificationWinner struct {
Name string
Suffix string
IncludeGitErrors bool
}
func (w *ArgumentClassificationWinner) String() string {
if len(w.Name) == 0 || len(w.Suffix) == 0 {
return ""
}
return fmt.Sprintf("Argument '%s' was classified as %s.", w.Name, w.Suffix)
}
type ErrRequiresExplicitAccess struct {
Match app.ComponentMatch
Input app.GeneratorInput
}
func (e ErrRequiresExplicitAccess) Error() string {
return fmt.Sprintf("the component %q is requesting access to run with your security credentials and install components - you must explicitly grant that access to continue", e.Match.String())
}
// ErrNoInputs is returned when no inputs are specified
var ErrNoInputs = errors.New("no inputs provided")
// AppResult contains the results of an application
type AppResult struct {
List *kapi.List
Name string
HasSource bool
Namespace string
GeneratedJobs bool
}
// QueryResult contains the results of a query (search or list)
type QueryResult struct {
Matches app.ComponentMatches
List *kapi.List
}
// NewAppConfig returns a new AppConfig, but you must set your typer, mapper, and clientMapper after the command has been run
// and flags have been parsed.
func NewAppConfig() *AppConfig {
return &AppConfig{
Resolvers: Resolvers{
Detector: app.SourceRepositoryEnumerator{
Detectors: source.DefaultDetectors,
DockerfileTester: dockerfile.NewTester(),
JenkinsfileTester: jenkinsfile.NewTester(),
},
},
EnvironmentClassificationErrors: map[string]ArgumentClassificationError{},
SourceClassificationErrors: map[string]ArgumentClassificationError{},
TemplateClassificationErrors: map[string]ArgumentClassificationError{},
ComponentClassificationErrors: map[string]ArgumentClassificationError{},
ClassificationWinners: map[string]ArgumentClassificationWinner{},
}
}
func (c *AppConfig) DockerRegistrySearcher() app.Searcher {
return app.DockerRegistrySearcher{
Client: dockerregistry.NewClient(30*time.Second, true),
AllowInsecure: c.InsecureRegistry,
}
}
func (c *AppConfig) ensureDockerSearch() {
if c.DockerSearcher == nil {
c.DockerSearcher = c.DockerRegistrySearcher()
}
}
// SetOpenShiftClient sets the passed OpenShift client in the application configuration
func (c *AppConfig) SetOpenShiftClient(imageClient imageclient.ImageInterface, templateClient templateclient.TemplateInterface, routeClient routeclient.RouteInterface, OriginNamespace string, dockerclient *docker.Client) {
c.OriginNamespace = OriginNamespace
namespaces := []string{OriginNamespace}
if openshiftNamespace := "openshift"; OriginNamespace != openshiftNamespace {
namespaces = append(namespaces, openshiftNamespace)
}
c.ImageClient = imageClient
c.RouteClient = routeClient
c.TemplateClient = templateClient
c.ImageStreamSearcher = app.ImageStreamSearcher{
Client: c.ImageClient,
ImageStreamImages: c.ImageClient,
Namespaces: namespaces,
AllowMissingTags: c.AllowMissingImageStreamTags,
}
c.ImageStreamByAnnotationSearcher = app.NewImageStreamByAnnotationSearcher(
c.ImageClient,
c.ImageClient,
namespaces,
)
c.TemplateSearcher = app.TemplateSearcher{
Client: c.TemplateClient,
Namespaces: namespaces,
}
c.TemplateFileSearcher = &app.TemplateFileSearcher{
Builder: c.Builder,
Namespace: OriginNamespace,
}
// the hierarchy of docker searching is:
// 1) if we have an openshift client - query docker registries via openshift,
// if we're unable to query via openshift, query the docker registries directly(fallback),
// if we don't find a match there and a local docker daemon exists, look in the local registry.
// 2) if we don't have an openshift client - query the docker registries directly,
// if we don't find a match there and a local docker daemon exists, look in the local registry.
c.DockerSearcher = app.DockerClientSearcher{
Client: dockerclient,
Insecure: c.InsecureRegistry,
AllowMissingImages: c.AllowMissingImages,
RegistrySearcher: app.ImageImportSearcher{
Client: c.ImageClient.ImageStreamImports(OriginNamespace),
AllowInsecure: c.InsecureRegistry,
Fallback: c.DockerRegistrySearcher(),
},
}
}
func (c *AppConfig) tryToAddEnvironmentArguments(s string) bool {
rc := env.IsEnvironmentArgument(s)
if rc {
glog.V(2).Infof("treating %s as possible environment argument\n", s)
c.Environment = append(c.Environment, s)
} else {
c.EnvironmentClassificationErrors[s] = ArgumentClassificationError{
Key: "is not an environment variable",
Value: nil,
}
}
return rc
}
func (c *AppConfig) tryToAddSourceArguments(s string) bool {
remote, rerr := app.IsRemoteRepository(s)
local, derr := app.IsDirectory(s)
if remote || local {
glog.V(2).Infof("treating %s as possible source repo\n", s)
c.SourceRepositories = append(c.SourceRepositories, s)
return true
}
// will combine multiple errors into one line / string
errStr := ""
if rerr != nil {
errStr = fmt.Sprintf("git ls-remote failed with: %v", rerr)
}
if derr != nil {
if len(errStr) > 0 {
errStr = errStr + "; "
}
errStr = fmt.Sprintf("%s local file access failed with: %v", errStr, derr)
}
c.SourceClassificationErrors[s] = ArgumentClassificationError{
Key: "is not a Git repository",
Value: fmt.Errorf(errStr),
}
return false
}
func (c *AppConfig) tryToAddComponentArguments(s string) bool {
err := app.IsComponentReference(s)
if err == nil {
glog.V(2).Infof("treating %s as a component ref\n", s)
c.Components = append(c.Components, s)
return true
}
c.ComponentClassificationErrors[s] = ArgumentClassificationError{
Key: "is not an image reference, image~source reference, nor template loaded in an accessible project",
Value: err,
}
return false
}
func (c *AppConfig) tryToAddTemplateArguments(s string) bool {
rc, err := app.IsPossibleTemplateFile(s)
if rc {
glog.V(2).Infof("treating %s as possible template file\n", s)
c.Components = append(c.Components, s)
return true
}
if err != nil {
c.TemplateClassificationErrors[s] = ArgumentClassificationError{
Key: "is not a template stored in a local file",
Value: err,
}
}
return false
}
// AddArguments converts command line arguments into the appropriate bucket based on what they look like
func (c *AppConfig) AddArguments(args []string) []string {
unknown := []string{}
for _, s := range args {
if len(s) == 0 {
continue
}
switch {
case c.tryToAddEnvironmentArguments(s):
c.ClassificationWinners[s] = ArgumentClassificationWinner{Name: s, Suffix: "an environment value"}
case c.tryToAddSourceArguments(s):
c.ClassificationWinners[s] = ArgumentClassificationWinner{Name: s, Suffix: "a source repository"}
delete(c.EnvironmentClassificationErrors, s)
case c.tryToAddTemplateArguments(s):
c.ClassificationWinners[s] = ArgumentClassificationWinner{Name: s, Suffix: "a template"}
delete(c.EnvironmentClassificationErrors, s)
delete(c.SourceClassificationErrors, s)
case c.tryToAddComponentArguments(s):
// NOTE, component argument classification currently is the most lenient, so we save it for the end
c.ClassificationWinners[s] = ArgumentClassificationWinner{Name: s, Suffix: "an image, image~source, or loaded template reference", IncludeGitErrors: true}
delete(c.EnvironmentClassificationErrors, s)
delete(c.TemplateClassificationErrors, s)
// we are going to save the source errors in case this really was a source repo in the end
default:
glog.V(2).Infof("treating %s as unknown\n", s)
unknown = append(unknown, s)
}
}
return unknown
}
// validateBuilders confirms that all images associated with components that are to be built,
// are builders (or we're using a non-source strategy).
func (c *AppConfig) validateBuilders(components app.ComponentReferences) error {
if c.Strategy != generate.StrategyUnspecified {
return nil
}
errs := []error{}
for _, ref := range components {
input := ref.Input()
// if we're supposed to build this thing, and the image/imagestream we've matched it to did not come from an explicit CLI argument,
// and the image/imagestream we matched to is not explicitly an s2i builder, and we're doing a source-type build, warn the user
// that this probably won't work and force them to declare their intention explicitly.
if input.ExpectToBuild && input.ResolvedMatch != nil && !app.IsBuilderMatch(input.ResolvedMatch) && input.Uses != nil && input.Uses.GetStrategy() == generate.StrategySource {
errs = append(errs, fmt.Errorf("the image match %q for source repository %q does not appear to be a source-to-image builder.\n\n- to attempt to use this image as a source builder, pass \"--strategy=source\"\n- to use it as a base image for a Docker build, pass \"--strategy=docker\"", input.ResolvedMatch.Name, input.Uses))
continue
}
}
return kutilerrors.NewAggregate(errs)
}
func validateEnforcedName(name string) error {
// up to 63 characters is nominally possible, however "-1" gets added on the
// end later for the deployment controller. Deduct 5 from 63 to at least
// cover us up to -9999.
if reasons := validation.ValidateServiceName(name, false); (len(reasons) != 0 || len(name) > 58) && !app.IsParameterizableValue(name) {
return fmt.Errorf("invalid name: %s. Must be an a lower case alphanumeric (a-z, and 0-9) string with a maximum length of 58 characters, where the first character is a letter (a-z), and the '-' character is allowed anywhere except the first or last character.", name)
}
return nil
}
func validateOutputImageReference(ref string) error {
if _, err := imageapi.ParseDockerImageReference(ref); err != nil {
return fmt.Errorf("invalid output image reference: %s", ref)
}
return nil
}
// buildPipelines converts a set of resolved, valid references into pipelines.
func (c *AppConfig) buildPipelines(components app.ComponentReferences, environment app.Environment, buildEnvironment app.Environment) (app.PipelineGroup, error) {
pipelines := app.PipelineGroup{}
buildArgs, err := utilenv.ParseBuildArg(c.BuildArgs, c.In)
if err != nil {
return nil, err
}
var DockerStrategyOptions *buildapi.DockerStrategyOptions
if len(c.BuildArgs) > 0 {
DockerStrategyOptions = &buildapi.DockerStrategyOptions{
BuildArgs: buildArgs,
}
}
numDockerBuilds := 0
pipelineBuilder := app.NewPipelineBuilder(c.Name, buildEnvironment, DockerStrategyOptions, c.OutputDocker).To(c.To)
for _, group := range components.Group() {
glog.V(4).Infof("found group: %v", group)
common := app.PipelineGroup{}
for _, ref := range group {
refInput := ref.Input()
from := refInput.String()
var pipeline *app.Pipeline
switch {
case refInput.ExpectToBuild:
glog.V(4).Infof("will add %q secrets into a build for a source build of %q", strings.Join(c.Secrets, ","), refInput.Uses)
if err := refInput.Uses.AddBuildSecrets(c.Secrets); err != nil {
return nil, fmt.Errorf("unable to add build secrets %q: %v", strings.Join(c.Secrets, ","), err)
}
glog.V(4).Infof("will add %q configMaps into a build for a source build of %q", strings.Join(c.ConfigMaps, ","), refInput.Uses)
if err = refInput.Uses.AddBuildConfigMaps(c.ConfigMaps); err != nil {
return nil, fmt.Errorf("unable to add build configMaps %q: %v", strings.Join(c.Secrets, ","), err)
}
if refInput.Uses.GetStrategy() == generate.StrategyDocker {
numDockerBuilds++
}
var (
image *app.ImageRef
err error
)
if refInput.ResolvedMatch != nil {
inputImage, err := app.InputImageFromMatch(refInput.ResolvedMatch)
if err != nil {
return nil, fmt.Errorf("can't build %q: %v", from, err)
}
if !inputImage.AsImageStream && from != "scratch" && (refInput.Uses == nil || refInput.Uses.GetStrategy() != generate.StrategyPipeline) {
msg := "Could not find an image stream match for %q. Make sure that a Docker image with that tag is available on the node for the build to succeed."
glog.Warningf(msg, from)
}
image = inputImage
}
glog.V(4).Infof("will use %q as the base image for a source build of %q", ref, refInput.Uses)
if pipeline, err = pipelineBuilder.NewBuildPipeline(from, image, refInput.Uses, c.BinaryBuild); err != nil {
return nil, fmt.Errorf("can't build %q: %v", refInput.Uses, err)
}
default:
inputImage, err := app.InputImageFromMatch(refInput.ResolvedMatch)
if err != nil {
return nil, fmt.Errorf("can't include %q: %v", from, err)
}
if !inputImage.AsImageStream {
msg := "Could not find an image stream match for %q. Make sure that a Docker image with that tag is available on the node for the deployment to succeed."
glog.Warningf(msg, from)
}
glog.V(4).Infof("will include %q", ref)
if pipeline, err = pipelineBuilder.NewImagePipeline(from, inputImage); err != nil {
return nil, fmt.Errorf("can't include %q: %v", refInput, err)
}
}
if c.Deploy {
if err := pipeline.NeedsDeployment(environment, c.Labels, c.AsTestDeployment); err != nil {
return nil, fmt.Errorf("can't set up a deployment for %q: %v", refInput, err)
}
}
if c.NoOutput {
pipeline.Build.Output = nil
}
if refInput.Uses != nil && refInput.Uses.GetStrategy() == generate.StrategyPipeline {
pipeline.Build.Output = nil
pipeline.Deployment = nil
pipeline.Image = nil
pipeline.InputImage = nil
}
common = append(common, pipeline)
if err := common.Reduce(); err != nil {
return nil, fmt.Errorf("can't create a pipeline from %s: %v", common, err)
}
describeBuildPipelineWithImage(c.Out, ref, pipeline, c.OriginNamespace)
}
pipelines = append(pipelines, common...)
}
if len(c.BuildArgs) > 0 {
if numDockerBuilds == 0 {
return nil, fmt.Errorf("Cannot use '--build-arg' without a Docker build")
}
if numDockerBuilds > 1 {
fmt.Fprintf(c.ErrOut, "--> WARNING: Applying --build-arg to multiple Docker builds.\n")
}
}
return pipelines, nil
}
// buildTemplates converts a set of resolved, valid references into references to template objects.
func (c *AppConfig) buildTemplates(components app.ComponentReferences, parameters app.Environment, environment app.Environment, buildEnvironment app.Environment, templateProcessor templateinternalclient.TemplateProcessorInterface) (string, []runtime.Object, error) {
objects := []runtime.Object{}
name := ""
for _, ref := range components {
tpl := ref.Input().ResolvedMatch.Template
glog.V(4).Infof("processing template %s/%s", c.OriginNamespace, tpl.Name)
if len(c.ContextDir) > 0 {
return "", nil, fmt.Errorf("--context-dir is not supported when using a template")
}
result, err := TransformTemplate(tpl, templateProcessor, c.OriginNamespace, parameters, c.IgnoreUnknownParameters)
if err != nil {
return name, nil, err
}
if len(name) == 0 {
name = tpl.Name
}
objects = append(objects, result.Objects...)
if len(result.Objects) > 0 {
// if environment variables were passed in, let's apply the environment variables
// to every pod template object
for _, obj := range result.Objects {
if bc, ok := obj.(*buildapi.BuildConfig); ok {
buildEnv := buildutil.GetBuildConfigEnv(bc)
buildEnv = app.JoinEnvironment(buildEnv, buildEnvironment.List())
buildutil.SetBuildConfigEnv(bc, buildEnv)
}
podSpec, _, err := ometa.GetPodSpec(obj)
if err == nil {
for ii := range podSpec.Containers {
if podSpec.Containers[ii].Env != nil {
podSpec.Containers[ii].Env = app.JoinEnvironment(environment.List(), podSpec.Containers[ii].Env)
} else {
podSpec.Containers[ii].Env = environment.List()
}
}
}
}
}
DescribeGeneratedTemplate(c.Out, ref.Input().String(), result, c.OriginNamespace)
}
return name, objects, nil
}
// fakeSecretAccessor is used during dry runs of installation
type fakeSecretAccessor struct {
token string
}
func (a *fakeSecretAccessor) Token() (string, error) {
return a.token, nil
}
func (a *fakeSecretAccessor) CACert() (string, error) {
return "", nil
}
// installComponents attempts to create pods to run installable images identified by the user. If an image
// is installable, we check whether it requires access to the user token. If so, the caller must have
// explicitly granted that access (because the token may be the user's).
func (c *AppConfig) installComponents(components app.ComponentReferences, env app.Environment) ([]runtime.Object, string, error) {
if c.SkipGeneration {
return nil, "", nil
}
jobs := components.InstallableComponentRefs()
switch {
case len(jobs) > 1:
return nil, "", fmt.Errorf("only one installable component may be provided: %s", jobs.HumanString(", "))
case len(jobs) == 0:
return nil, "", nil
}
job := jobs[0]
if len(components) > 1 {
return nil, "", fmt.Errorf("%q is installable and may not be specified with other components", job.Input().Value)
}
input := job.Input()
imageRef, err := app.InputImageFromMatch(input.ResolvedMatch)
if err != nil {
return nil, "", fmt.Errorf("can't include %q: %v", input, err)
}
glog.V(4).Infof("Resolved match for installer %#v", input.ResolvedMatch)
imageRef.AsImageStream = false
imageRef.AsResolvedImage = true
imageRef.Env = env
name := c.Name
if len(name) == 0 {
var ok bool
name, ok = imageRef.SuggestName()
if !ok {
return nil, "", errors.New("can't suggest a valid name, please specify a name with --name")
}
}
imageRef.ObjectName = name
glog.V(4).Infof("Proposed installable image %#v", imageRef)
secretAccessor := c.SecretAccessor
generatorInput := input.ResolvedMatch.GeneratorInput
token := generatorInput.Token
if token != nil && !c.AllowSecretUse || secretAccessor == nil {
if !c.DryRun {
return nil, "", ErrRequiresExplicitAccess{Match: *input.ResolvedMatch, Input: generatorInput}
}
secretAccessor = &fakeSecretAccessor{token: "FAKE_TOKEN"}
}
objects := []runtime.Object{}
serviceAccountName := "installer"
if token != nil && token.ServiceAccount {
if _, err := c.KubeClient.Core().ServiceAccounts(c.OriginNamespace).Get(serviceAccountName, metav1.GetOptions{}); err != nil {
if kerrors.IsNotFound(err) {
objects = append(objects,
// create a new service account
&kapi.ServiceAccount{ObjectMeta: metav1.ObjectMeta{Name: serviceAccountName}},
// grant the service account the edit role on the project (TODO: installer)
&authapi.RoleBinding{
ObjectMeta: metav1.ObjectMeta{Name: "installer-role-binding"},
Subjects: []kapi.ObjectReference{{Kind: "ServiceAccount", Name: serviceAccountName}},
RoleRef: kapi.ObjectReference{Name: "edit"},
},
)
}
}
}
pod, secret, err := imageRef.InstallablePod(generatorInput, secretAccessor, serviceAccountName)
if err != nil {
return nil, "", err
}
objects = append(objects, pod)
if secret != nil {
objects = append(objects, secret)
}
for i := range objects {
outil.AddObjectAnnotations(objects[i], map[string]string{
GeneratedForJob: "true",
GeneratedForJobFor: input.String(),
})
}
describeGeneratedJob(c.Out, job, pod, secret, c.OriginNamespace)
return objects, name, nil
}
// RunQuery executes the provided config and returns the result of the resolution.
func (c *AppConfig) RunQuery() (*QueryResult, error) {
environment, buildEnvironment, parameters, err := c.validate()
if err != nil {
return nil, err
}
// TODO: I don't belong here
c.ensureDockerSearch()
if c.AsList {
if c.AsSearch {
return nil, errors.New("--list and --search can't be used together")
}
if c.HasArguments() {
return nil, errors.New("--list can't be used with arguments")
}
c.Components = append(c.Components, "*")
}
b := &app.ReferenceBuilder{}
s := &c.SourceRepositories
i := &c.ImageStreams
if err := AddComponentInputsToRefBuilder(b, &c.Resolvers, &c.ComponentInputs, &c.GenerationInputs, s, i); err != nil {
return nil, err
}
components, repositories, errs := b.Result()
if len(errs) > 0 {
return nil, kutilerrors.NewAggregate(errs)
}
if len(components) == 0 && !c.AsList {
return nil, ErrNoInputs
}
if len(repositories) > 0 {
errs = append(errs, errors.New("--search can't be used with source code"))
}
if len(environment) > 0 {
errs = append(errs, errors.New("--search can't be used with --env"))
}
if len(buildEnvironment) > 0 {
errs = append(errs, errors.New("--search can't be used with --build-env"))
}
if len(parameters) > 0 {
errs = append(errs, errors.New("--search can't be used with --param"))
}
if len(errs) > 0 {
return nil, kutilerrors.NewAggregate(errs)
}
if err := components.Search(); err != nil {
return nil, err
}
glog.V(4).Infof("Code %v", repositories)
glog.V(4).Infof("Components %v", components)
matches := app.ComponentMatches{}
objects := app.Objects{}
for _, ref := range components {
for _, match := range ref.Input().SearchMatches {
matches = append(matches, match)
if match.IsTemplate() {
objects = append(objects, match.Template)
} else if match.IsImage() {
if match.ImageStream != nil {
objects = append(objects, match.ImageStream)
}
if match.Image != nil {
objects = append(objects, match.Image)
}
}
}
}
return &QueryResult{
Matches: matches,
List: &kapi.List{Items: objects},
}, nil
}
func (c *AppConfig) validate() (app.Environment, app.Environment, app.Environment, error) {
env, err := app.ParseAndCombineEnvironment(c.Environment, c.EnvironmentFiles, c.In, func(key, file string) error {
if file == "" {
fmt.Fprintf(c.ErrOut, "warning: Environment variable %q was overwritten\n", key)
} else {
fmt.Fprintf(c.ErrOut, "warning: Environment variable %q already defined, ignoring value from file %q\n", key, file)
}
return nil
})
if err != nil {
return nil, nil, nil, err
}
buildEnv, err := app.ParseAndCombineEnvironment(c.BuildEnvironment, c.BuildEnvironmentFiles, c.In, func(key, file string) error {
if file == "" {
fmt.Fprintf(c.ErrOut, "warning: Build Environment variable %q was overwritten\n", key)
} else {
fmt.Fprintf(c.ErrOut, "warning: Build Environment variable %q already defined, ignoring value from file %q\n", key, file)
}
return nil
})
if err != nil {
return nil, nil, nil, err
}
params, err := app.ParseAndCombineEnvironment(c.TemplateParameters, c.TemplateParameterFiles, c.In, func(key, file string) error {
if file == "" {
fmt.Fprintf(c.ErrOut, "warning: Template parameter %q was overwritten\n", key)
} else {
fmt.Fprintf(c.ErrOut, "warning: Template parameter %q already defined, ignoring value from file %q\n", key, file)
}
return nil
})
if err != nil {
return nil, nil, nil, err
}
return env, buildEnv, params, nil
}
// Run executes the provided config to generate objects.
func (c *AppConfig) Run() (*AppResult, error) {
env, buildenv, parameters, err := c.validate()
if err != nil {
return nil, err
}
// TODO: I don't belong here
c.ensureDockerSearch()
resolved, err := Resolve(c)
if err != nil {
return nil, err
}
repositories := resolved.Repositories
components := resolved.Components
if len(repositories) == 0 && len(components) == 0 {
return nil, ErrNoInputs
}
if err := c.validateBuilders(components); err != nil {
return nil, err
}
if len(c.Name) > 0 {
if err := validateEnforcedName(c.Name); err != nil {
return nil, err
}
}
if len(c.To) > 0 {
if err := validateOutputImageReference(c.To); err != nil {
return nil, err
}
}
if len(components.ImageComponentRefs().Group()) > 1 && len(c.Name) > 0 {
return nil, errors.New("only one component or source repository can be used when specifying a name")
}
if len(components.UseSource()) > 1 && len(c.To) > 0 {
return nil, errors.New("only one component with source can be used when specifying an output image reference")
}
// identify if there are installable components in the input provided by the user
installables, name, err := c.installComponents(components, env)
if err != nil {
return nil, err
}
if len(installables) > 0 {
return &AppResult{
List: &kapi.List{Items: installables},
Name: name,
Namespace: c.OriginNamespace,
GeneratedJobs: true,
}, nil
}
pipelines, err := c.buildPipelines(components.ImageComponentRefs(), env, buildenv)
if err != nil {
return nil, err
}
acceptors := app.Acceptors{app.NewAcceptUnique(c.Typer), app.AcceptNew,
app.NewAcceptNonExistentImageStream(c.Typer, c.ImageClient, c.OriginNamespace), app.NewAcceptNonExistentImageStreamTag(c.Typer, c.ImageClient, c.OriginNamespace)}
objects := app.Objects{}
accept := app.NewAcceptFirst()
for _, p := range pipelines {
accepted, err := p.Objects(accept, acceptors)
if err != nil {
return nil, fmt.Errorf("can't setup %q: %v", p.From, err)
}
objects = append(objects, accepted...)
}
objects = app.AddServices(objects, false)
templateProcessor := templateinternalclient.NewTemplateProcessorClient(c.TemplateClient.RESTClient(), c.OriginNamespace)
templateName, templateObjects, err := c.buildTemplates(components.TemplateComponentRefs(), parameters, env, buildenv, templateProcessor)
if err != nil {
return nil, err
}
// check for circular reference specifically from the template objects and print warnings if they exist
err = c.checkCircularReferences(templateObjects)
if err != nil {
if err, ok := err.(app.CircularOutputReferenceError); ok {
// templates only apply to `oc new-app`
addOn := ""
if len(c.Name) == 0 {
addOn = ", override artifact names with --name"
}
fmt.Fprintf(c.ErrOut, "--> WARNING: %v\n%s", err, addOn)
} else {
return nil, err
}
}
// check for circular reference specifically from the newly generated objects, handling new-app vs. new-build nuances as needed
err = c.checkCircularReferences(objects)
if err != nil {
if err, ok := err.(app.CircularOutputReferenceError); ok {
if c.ExpectToBuild {
// circular reference handling for `oc new-build`.
if len(c.To) == 0 {
// Output reference was generated, return error.
return nil, fmt.Errorf("%v, set a different tag with --to", err)
}
// Output reference was explicitly provided, print warning.
fmt.Fprintf(c.ErrOut, "--> WARNING: %v\n", err)
} else {
// circular reference handling for `oc new-app`
if len(c.Name) == 0 {
return nil, fmt.Errorf("%v, override artifact names with --name", err)
}
// Output reference was explicitly provided, print warning.
fmt.Fprintf(c.ErrOut, "--> WARNING: %v\n", err)
}
} else {
return nil, err
}
}
objects = append(objects, templateObjects...)
name = c.Name
if len(name) == 0 {
name = templateName
}
if len(name) == 0 {
for _, pipeline := range pipelines {
if pipeline.Deployment != nil {
name = pipeline.Deployment.Name
break
}
}
}
if len(name) == 0 {
for _, obj := range objects {
if bc, ok := obj.(*buildapi.BuildConfig); ok {
name = bc.Name
break
}
}
}
if len(c.SourceSecret) > 0 {
if len(validation.ValidateSecretName(c.SourceSecret, false)) != 0 {
return nil, fmt.Errorf("source secret name %q is invalid", c.SourceSecret)
}
for _, obj := range objects {
if bc, ok := obj.(*buildapi.BuildConfig); ok {
glog.V(4).Infof("Setting source secret for build config to: %v", c.SourceSecret)
bc.Spec.Source.SourceSecret = &kapi.LocalObjectReference{Name: c.SourceSecret}
break
}
}
}
if len(c.PushSecret) > 0 {
if len(validation.ValidateSecretName(c.PushSecret, false)) != 0 {
return nil, fmt.Errorf("push secret name %q is invalid", c.PushSecret)
}
for _, obj := range objects {
if bc, ok := obj.(*buildapi.BuildConfig); ok {
glog.V(4).Infof("Setting push secret for build config to: %v", c.SourceSecret)
bc.Spec.Output.PushSecret = &kapi.LocalObjectReference{Name: c.PushSecret}
break
}
}
}
return &AppResult{
List: &kapi.List{Items: objects},
Name: name,
HasSource: len(repositories) != 0,
Namespace: c.OriginNamespace,
}, nil
}
func (c *AppConfig) findImageStreamInObjectList(objects app.Objects, name, namespace string) *imageapi.ImageStream {
for _, check := range objects {
if is, ok := check.(*imageapi.ImageStream); ok {
nsToCompare := is.Namespace
if len(nsToCompare) == 0 {
nsToCompare = c.OriginNamespace
}
if is.Name == name && nsToCompare == namespace {
return is
}
}
}
return nil
}
// crossStreamCircularTagReference inherits some logic from imageapi.FollowTagReference, but differs in that a) it is only concerned
// with whether we can definitively say the IST chain is circular, and b) can cross image stream boundaries;
// not in imageapi pkg (see imports above) like other helpers cause of import cycle with the image client
func (c *AppConfig) crossStreamCircularTagReference(stream *imageapi.ImageStream, tag string, objects app.Objects) bool {
if stream == nil {
return false
}
seen := sets.NewString()
for {
if seen.Has(stream.ObjectMeta.Namespace + ":" + stream.ObjectMeta.Name + ":" + tag) {
// circular reference
return true
}
seen.Insert(stream.ObjectMeta.Namespace + ":" + stream.ObjectMeta.Name + ":" + tag)
tagRef, ok := stream.Spec.Tags[tag]