This repository has been archived by the owner on Jul 18, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
sti.go
438 lines (384 loc) · 15.4 KB
/
sti.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
package builder
import (
"bytes"
"context"
"errors"
"fmt"
"net/url"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
s2iapi "github.com/openshift/source-to-image/pkg/api"
"github.com/openshift/source-to-image/pkg/api/describe"
"github.com/openshift/source-to-image/pkg/api/validation"
s2ibuild "github.com/openshift/source-to-image/pkg/build"
s2i "github.com/openshift/source-to-image/pkg/build/strategies"
"github.com/openshift/source-to-image/pkg/docker"
s2igit "github.com/openshift/source-to-image/pkg/scm/git"
s2iutil "github.com/openshift/source-to-image/pkg/util"
buildapi "github.com/openshift/origin/pkg/build/apis/build"
"github.com/openshift/origin/pkg/build/builder/cmd/dockercfg"
"github.com/openshift/origin/pkg/build/builder/timing"
"github.com/openshift/origin/pkg/build/controller/strategy"
buildinternalversion "github.com/openshift/origin/pkg/build/generated/internalclientset/typed/build/internalversion"
buildutil "github.com/openshift/origin/pkg/build/util"
"github.com/openshift/origin/pkg/generate/git"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// builderFactory is the internal interface to decouple S2I-specific code from Origin builder code
type builderFactory interface {
// Create S2I Builder based on S2I configuration
Builder(config *s2iapi.Config, overrides s2ibuild.Overrides) (s2ibuild.Builder, s2iapi.BuildInfo, error)
}
// validator is the interval interface to decouple S2I-specific code from Origin builder code
type validator interface {
// Perform validation of S2I configuration, returns slice of validation errors
ValidateConfig(config *s2iapi.Config) []validation.Error
}
// runtimeBuilderFactory is the default implementation of stiBuilderFactory
type runtimeBuilderFactory struct{}
// Builder delegates execution to S2I-specific code
func (_ runtimeBuilderFactory) Builder(config *s2iapi.Config, overrides s2ibuild.Overrides) (s2ibuild.Builder, s2iapi.BuildInfo, error) {
client, err := docker.NewEngineAPIClient(config.DockerConfig)
if err != nil {
return nil, s2iapi.BuildInfo{}, err
}
builder, buildInfo, err := s2i.Strategy(client, config, overrides)
return builder, buildInfo, err
}
// runtimeConfigValidator is the default implementation of stiConfigValidator
type runtimeConfigValidator struct{}
// ValidateConfig delegates execution to S2I-specific code
func (_ runtimeConfigValidator) ValidateConfig(config *s2iapi.Config) []validation.Error {
return validation.ValidateConfig(config)
}
// S2IBuilder performs an STI build given the build object
type S2IBuilder struct {
builder builderFactory
validator validator
dockerClient DockerClient
dockerSocket string
build *buildapi.Build
client buildinternalversion.BuildResourceInterface
cgLimits *s2iapi.CGroupLimits
}
// NewS2IBuilder creates a new STIBuilder instance
func NewS2IBuilder(dockerClient DockerClient, dockerSocket string, buildsClient buildinternalversion.BuildResourceInterface, build *buildapi.Build,
cgLimits *s2iapi.CGroupLimits) *S2IBuilder {
// delegate to internal implementation passing default implementation of builderFactory and validator
return newS2IBuilder(dockerClient, dockerSocket, buildsClient, build, runtimeBuilderFactory{}, runtimeConfigValidator{}, cgLimits)
}
// newS2IBuilder is the internal factory function to create STIBuilder based on parameters. Used for testing.
func newS2IBuilder(dockerClient DockerClient, dockerSocket string, buildsClient buildinternalversion.BuildResourceInterface, build *buildapi.Build,
builder builderFactory, validator validator, cgLimits *s2iapi.CGroupLimits) *S2IBuilder {
// just create instance
return &S2IBuilder{
builder: builder,
validator: validator,
dockerClient: dockerClient,
dockerSocket: dockerSocket,
build: build,
client: buildsClient,
cgLimits: cgLimits,
}
}
// Build executes S2I build based on configured builder, S2I builder factory
// and S2I config validator
func (s *S2IBuilder) Build() error {
var err error
ctx := timing.NewContext(context.Background())
defer func() {
s.build.Status.Stages = buildapi.AppendStageAndStepInfo(s.build.Status.Stages, timing.GetStages(ctx))
HandleBuildStatusUpdate(s.build, s.client, nil)
}()
if s.build.Spec.Strategy.SourceStrategy == nil {
return errors.New("the source to image builder must be used with the source strategy")
}
var push bool
// if there is no output target, set one up so the docker build logic
// (which requires a tag) will still work, but we won't push it at the end.
if s.build.Spec.Output.To == nil || len(s.build.Spec.Output.To.Name) == 0 {
s.build.Status.OutputDockerImageReference = s.build.Name
} else {
push = true
}
pushTag := s.build.Status.OutputDockerImageReference
sourceInfo, err := readSourceInfo()
if err != nil {
return fmt.Errorf("error reading git source info: %v", err)
}
var s2iSourceInfo *s2igit.SourceInfo
if sourceInfo != nil {
s2iSourceInfo = toS2ISourceInfo(sourceInfo)
}
injections := s2iapi.VolumeList{}
for _, s := range s.build.Spec.Source.Secrets {
glog.V(3).Infof("Injecting secret %q into a build into %q", s.Secret.Name, filepath.Clean(s.DestinationDir))
secretSourcePath := filepath.Join(strategy.SecretBuildSourceBaseMountPath, s.Secret.Name)
injections = append(injections, s2iapi.VolumeSpec{
Source: secretSourcePath,
Destination: s.DestinationDir,
})
}
buildTag := randomBuildTag(s.build.Namespace, s.build.Name)
scriptDownloadProxyConfig, err := scriptProxyConfig(s.build)
if err != nil {
return err
}
if scriptDownloadProxyConfig != nil {
glog.V(0).Infof("Using HTTP proxy %v and HTTPS proxy %v for script download",
buildutil.SafeForLoggingURL(scriptDownloadProxyConfig.HTTPProxy),
buildutil.SafeForLoggingURL(scriptDownloadProxyConfig.HTTPSProxy),
)
}
var incremental bool
if s.build.Spec.Strategy.SourceStrategy.Incremental != nil {
incremental = *s.build.Spec.Strategy.SourceStrategy.Incremental
}
srcDir := buildutil.InputContentPath
contextDir := ""
if len(s.build.Spec.Source.ContextDir) != 0 {
contextDir = filepath.Clean(s.build.Spec.Source.ContextDir)
if contextDir == "." || contextDir == "/" {
contextDir = ""
}
}
networkMode, resolvConfHostPath, err := getContainerNetworkConfig()
if err != nil {
return err
}
config := &s2iapi.Config{
// Save some processing time by not cleaning up (the container will go away anyway)
PreserveWorkingDir: true,
WorkingDir: "/tmp",
DockerConfig: &s2iapi.DockerConfig{Endpoint: s.dockerSocket},
DockerCfgPath: os.Getenv(dockercfg.PullAuthType),
LabelNamespace: buildapi.DefaultDockerLabelNamespace,
ScriptsURL: s.build.Spec.Strategy.SourceStrategy.Scripts,
BuilderImage: s.build.Spec.Strategy.SourceStrategy.From.Name,
Incremental: incremental,
IncrementalFromTag: pushTag,
Environment: buildEnvVars(s.build, sourceInfo),
Labels: s2iBuildLabels(s.build, sourceInfo),
DockerNetworkMode: s2iapi.DockerNetworkMode(networkMode),
Source: &s2igit.URL{URL: url.URL{Path: srcDir}, Type: s2igit.URLTypeLocal},
ContextDir: contextDir,
SourceInfo: s2iSourceInfo,
ForceCopy: true,
Injections: injections,
Tag: buildTag,
CGroupLimits: s.cgLimits,
ScriptDownloadProxyConfig: scriptDownloadProxyConfig,
BlockOnBuild: true,
}
if len(resolvConfHostPath) != 0 {
cmd := exec.Command("chcon", "system_u:object_r:svirt_sandbox_file_t:s0", "/etc/resolv.conf")
err := cmd.Run()
if err != nil {
return fmt.Errorf("unable to set permissions on /etc/resolv.conf: %v", err)
}
config.BuildVolumes = []string{fmt.Sprintf("%s:/etc/resolv.conf", resolvConfHostPath)}
}
if s.build.Spec.Strategy.SourceStrategy.ForcePull {
glog.V(4).Infof("With force pull true, setting policies to %s", s2iapi.PullAlways)
config.BuilderPullPolicy = s2iapi.PullAlways
} else {
glog.V(4).Infof("With force pull false, setting policies to %s", s2iapi.PullIfNotPresent)
config.BuilderPullPolicy = s2iapi.PullIfNotPresent
}
config.PreviousImagePullPolicy = s2iapi.PullAlways
allowedUIDs := os.Getenv(buildapi.AllowedUIDs)
glog.V(4).Infof("The value of %s is [%s]", buildapi.AllowedUIDs, allowedUIDs)
if len(allowedUIDs) > 0 {
err = config.AllowedUIDs.Set(allowedUIDs)
if err != nil {
return err
}
}
dropCaps := os.Getenv(buildapi.DropCapabilities)
glog.V(4).Infof("The value of %s is [%s]", buildapi.DropCapabilities, dropCaps)
if len(dropCaps) > 0 {
config.DropCapabilities = strings.Split(dropCaps, ",")
}
// If DockerCfgPath is provided in buildapi.Config, then attempt to read the
// dockercfg file and get the authentication for pulling the builder image.
t, _ := dockercfg.NewHelper().GetDockerAuth(config.BuilderImage, dockercfg.PullAuthType)
config.PullAuthentication = s2iapi.AuthConfig{Username: t.Username, Password: t.Password, Email: t.Email, ServerAddress: t.ServerAddress}
t, _ = dockercfg.NewHelper().GetDockerAuth(pushTag, dockercfg.PushAuthType)
config.IncrementalAuthentication = s2iapi.AuthConfig{Username: t.Username, Password: t.Password, Email: t.Email, ServerAddress: t.ServerAddress}
if errs := s.validator.ValidateConfig(config); len(errs) != 0 {
var buffer bytes.Buffer
for _, ve := range errs {
buffer.WriteString(ve.Error())
buffer.WriteString(", ")
}
return errors.New(buffer.String())
}
client, err := docker.NewEngineAPIClient(config.DockerConfig)
if err != nil {
return err
}
if glog.Is(4) {
redactedConfig := SafeForLoggingS2IConfig(config)
glog.V(4).Infof("Creating a new S2I builder with config: %#v\n", describe.Config(client, redactedConfig))
}
builder, buildInfo, err := s.builder.Builder(config, s2ibuild.Overrides{Downloader: nil})
if err != nil {
s.build.Status.Phase = buildapi.BuildPhaseFailed
s.build.Status.Reason, s.build.Status.Message = convertS2IFailureType(
buildInfo.FailureReason.Reason,
buildInfo.FailureReason.Message,
)
HandleBuildStatusUpdate(s.build, s.client, nil)
return err
}
glog.V(4).Infof("Starting S2I build from %s/%s BuildConfig ...", s.build.Namespace, s.build.Name)
startTime := metav1.Now()
result, err := builder.Build(config)
for _, stage := range result.BuildInfo.Stages {
for _, step := range stage.Steps {
timing.RecordNewStep(ctx, buildapi.StageName(stage.Name), buildapi.StepName(step.Name), metav1.NewTime(step.StartTime), metav1.NewTime(step.StartTime.Add(time.Duration(step.DurationMilliseconds)*time.Millisecond)))
}
}
if err != nil {
s.build.Status.Phase = buildapi.BuildPhaseFailed
s.build.Status.Reason, s.build.Status.Message = convertS2IFailureType(
result.BuildInfo.FailureReason.Reason,
result.BuildInfo.FailureReason.Message,
)
HandleBuildStatusUpdate(s.build, s.client, nil)
return err
}
cName := containerName("s2i", s.build.Name, s.build.Namespace, "post-commit")
err = execPostCommitHook(ctx, s.dockerClient, s.build.Spec.PostCommit, buildTag, cName)
if err != nil {
s.build.Status.Phase = buildapi.BuildPhaseFailed
s.build.Status.Reason = buildapi.StatusReasonPostCommitHookFailed
s.build.Status.Message = buildapi.StatusMessagePostCommitHookFailed
HandleBuildStatusUpdate(s.build, s.client, nil)
return err
}
if push {
if err = tagImage(s.dockerClient, buildTag, pushTag); err != nil {
return err
}
}
if err = removeImage(s.dockerClient, buildTag); err != nil {
glog.V(0).Infof("warning: Failed to remove temporary build tag %v: %v", buildTag, err)
}
if push {
// Get the Docker push authentication
pushAuthConfig, authPresent := dockercfg.NewHelper().GetDockerAuth(
pushTag,
dockercfg.PushAuthType,
)
if authPresent {
glog.V(3).Infof("Using provided push secret for pushing %s image", pushTag)
} else {
glog.V(3).Infof("No push secret provided")
}
glog.V(0).Infof("\nPushing image %s ...", pushTag)
startTime = metav1.Now()
digest, err := pushImage(s.dockerClient, pushTag, pushAuthConfig)
timing.RecordNewStep(ctx, buildapi.StagePushImage, buildapi.StepPushImage, startTime, metav1.Now())
if err != nil {
s.build.Status.Phase = buildapi.BuildPhaseFailed
s.build.Status.Reason = buildapi.StatusReasonPushImageToRegistryFailed
s.build.Status.Message = buildapi.StatusMessagePushImageToRegistryFailed
HandleBuildStatusUpdate(s.build, s.client, nil)
return reportPushFailure(err, authPresent, pushAuthConfig)
}
if len(digest) > 0 {
s.build.Status.Output.To = &buildapi.BuildStatusOutputTo{
ImageDigest: digest,
}
HandleBuildStatusUpdate(s.build, s.client, nil)
}
glog.V(0).Infof("Push successful")
}
return nil
}
// buildEnvVars returns a map with build metadata to be inserted into Docker
// images produced by build. It transforms the output from buildInfo into the
// input format expected by s2iapi.Config.Environment.
// Note that using a map has at least two downsides:
// 1. The order of metadata KeyValue pairs is lost;
// 2. In case of repeated Keys, the last Value takes precedence right here,
// instead of deferring what to do with repeated environment variables to the
// Docker runtime.
func buildEnvVars(build *buildapi.Build, sourceInfo *git.SourceInfo) s2iapi.EnvironmentList {
bi := buildInfo(build, sourceInfo)
envVars := &s2iapi.EnvironmentList{}
for _, item := range bi {
envVars.Set(fmt.Sprintf("%s=%s", item.Key, item.Value))
}
return *envVars
}
// s2iBuildLabels returns a slice of KeyValue pairs in a format that appendLabel can
// consume.
func s2iBuildLabels(build *buildapi.Build, sourceInfo *git.SourceInfo) map[string]string {
labels := map[string]string{}
if sourceInfo == nil {
sourceInfo = &git.SourceInfo{}
}
if len(build.Spec.Source.ContextDir) > 0 {
sourceInfo.ContextDir = build.Spec.Source.ContextDir
}
labels = s2iutil.GenerateLabelsFromSourceInfo(labels, toS2ISourceInfo(sourceInfo), buildapi.DefaultDockerLabelNamespace)
// override autogenerated labels
for _, lbl := range build.Spec.Output.ImageLabels {
labels[lbl.Name] = lbl.Value
}
return labels
}
// scriptProxyConfig determines a proxy configuration for downloading
// scripts from a URL. For now, it uses environment variables passed in
// the strategy's environment. There is no preference given to either lowercase
// or uppercase form of the variable.
func scriptProxyConfig(build *buildapi.Build) (*s2iapi.ProxyConfig, error) {
httpProxy := ""
httpsProxy := ""
for _, env := range build.Spec.Strategy.SourceStrategy.Env {
switch env.Name {
case "HTTP_PROXY", "http_proxy":
httpProxy = env.Value
case "HTTPS_PROXY", "https_proxy":
httpsProxy = env.Value
}
}
if len(httpProxy) == 0 && len(httpsProxy) == 0 {
return nil, nil
}
config := &s2iapi.ProxyConfig{}
if len(httpProxy) > 0 {
proxyURL, err := buildutil.ParseProxyURL(httpProxy)
if err != nil {
return nil, err
}
config.HTTPProxy = proxyURL
}
if len(httpsProxy) > 0 {
proxyURL, err := buildutil.ParseProxyURL(httpsProxy)
if err != nil {
return nil, err
}
config.HTTPSProxy = proxyURL
}
return config, nil
}
// copyToVolumeList copies the artifacts set in the build config to the
// VolumeList struct in the s2iapi.Config
func copyToVolumeList(artifactsMapping []buildapi.ImageSourcePath) (volumeList s2iapi.VolumeList) {
for _, mappedPath := range artifactsMapping {
volumeList = append(volumeList, s2iapi.VolumeSpec{
Source: mappedPath.SourcePath,
Destination: mappedPath.DestinationDir,
})
}
return
}
func convertS2IFailureType(reason s2iapi.StepFailureReason, message s2iapi.StepFailureMessage) (buildapi.StatusReason, string) {
return buildapi.StatusReason(reason), string(message)
}