forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sti.go
389 lines (342 loc) · 12.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
package builder
import (
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"net/url"
"os"
"path/filepath"
"strings"
"time"
"github.com/golang/glog"
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/origin/pkg/build/api"
"github.com/openshift/origin/pkg/build/builder/cmd/dockercfg"
"github.com/openshift/origin/pkg/build/controller/strategy"
"github.com/openshift/origin/pkg/client"
)
// 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, 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.ValidationError
}
// 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, error) {
return s2i.Strategy(config, overrides)
}
// runtimeConfigValidator is the default implementation of stiConfigValidator
type runtimeConfigValidator struct{}
// ValidateConfig delegates execution to S2I-specific code
func (_ runtimeConfigValidator) ValidateConfig(config *s2iapi.Config) []validation.ValidationError {
return validation.ValidateConfig(config)
}
// S2IBuilder performs an STI build given the build object
type S2IBuilder struct {
builder builderFactory
validator validator
gitClient GitClient
dockerClient DockerClient
dockerSocket string
build *api.Build
client client.BuildInterface
cgLimits *s2iapi.CGroupLimits
}
// NewS2IBuilder creates a new STIBuilder instance
func NewS2IBuilder(dockerClient DockerClient, dockerSocket string, buildsClient client.BuildInterface, build *api.Build, gitClient GitClient, cgLimits *s2iapi.CGroupLimits) *S2IBuilder {
// delegate to internal implementation passing default implementation of builderFactory and validator
return newS2IBuilder(dockerClient, dockerSocket, buildsClient, build, gitClient, 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 client.BuildInterface, build *api.Build,
gitClient GitClient, builder builderFactory, validator validator, cgLimits *s2iapi.CGroupLimits) *S2IBuilder {
// just create instance
return &S2IBuilder{
builder: builder,
validator: validator,
gitClient: gitClient,
dockerClient: dockerClient,
dockerSocket: dockerSocket,
build: build,
client: buildsClient,
cgLimits: cgLimits,
}
}
// Build executes STI build based on configured builder, S2I builder factory and S2I config validator
func (s *S2IBuilder) Build() error {
if s.build.Spec.Strategy.SourceStrategy == nil {
return fmt.Errorf("the source to image builder must be used with the source strategy")
}
var push bool
contextDir := filepath.Clean(s.build.Spec.Source.ContextDir)
if contextDir == "." || contextDir == "/" {
contextDir = ""
}
buildDir, err := ioutil.TempDir("", "s2i-build")
if err != nil {
return err
}
srcDir := filepath.Join(buildDir, s2iapi.Source)
if err := os.MkdirAll(srcDir, os.ModePerm); err != nil {
return err
}
tmpDir := filepath.Join(buildDir, "tmp")
if err := os.MkdirAll(tmpDir, os.ModePerm); err != nil {
return err
}
download := &downloader{
s: s,
in: os.Stdin,
timeout: urlCheckTimeout,
dir: srcDir,
contextDir: contextDir,
tmpDir: tmpDir,
}
// 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
git := s.build.Spec.Source.Git
var ref string
if s.build.Spec.Revision != nil && s.build.Spec.Revision.Git != nil &&
len(s.build.Spec.Revision.Git.Commit) != 0 {
ref = s.build.Spec.Revision.Git.Commit
} else if git != nil && len(git.Ref) != 0 {
ref = git.Ref
}
sourceURI := &url.URL{
Scheme: "file",
Path: srcDir,
Fragment: ref,
}
injections := s2iapi.InjectionList{}
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.InjectPath{
SourcePath: secretSourcePath,
DestinationDir: 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(2).Infof("Using HTTP proxy %v and HTTPS proxy %v for script download",
scriptDownloadProxyConfig.HTTPProxy,
scriptDownloadProxyConfig.HTTPSProxy)
}
config := &s2iapi.Config{
WorkingDir: buildDir,
DockerConfig: &s2iapi.DockerConfig{Endpoint: s.dockerSocket},
DockerCfgPath: os.Getenv(dockercfg.PullAuthType),
LabelNamespace: api.DefaultDockerLabelNamespace,
ScriptsURL: s.build.Spec.Strategy.SourceStrategy.Scripts,
BuilderImage: s.build.Spec.Strategy.SourceStrategy.From.Name,
Incremental: s.build.Spec.Strategy.SourceStrategy.Incremental,
IncrementalFromTag: pushTag,
Environment: buildEnvVars(s.build),
DockerNetworkMode: getDockerNetworkMode(),
Source: sourceURI.String(),
Tag: buildTag,
ContextDir: s.build.Spec.Source.ContextDir,
CGroupLimits: s.cgLimits,
Injections: injections,
ScriptDownloadProxyConfig: scriptDownloadProxyConfig,
}
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(api.AllowedUIDs)
glog.V(2).Infof("The value of %s is [%s]", api.AllowedUIDs, allowedUIDs)
if len(allowedUIDs) > 0 {
err := config.AllowedUIDs.Set(allowedUIDs)
if err != nil {
return err
}
}
dropCaps := os.Getenv(api.DropCapabilities)
glog.V(2).Infof("The value of %s is [%s]", api.DropCapabilities, dropCaps)
if len(dropCaps) > 0 {
config.DropCapabilities = strings.Split(dropCaps, ",")
}
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())
}
// If DockerCfgPath is provided in api.Config, then attempt to read the the
// dockercfg file and get the authentication for pulling the builder image.
config.PullAuthentication, _ = dockercfg.NewHelper().GetDockerAuth(config.BuilderImage, dockercfg.PullAuthType)
config.IncrementalAuthentication, _ = dockercfg.NewHelper().GetDockerAuth(pushTag, dockercfg.PushAuthType)
glog.V(2).Infof("Creating a new S2I builder with build config: %#v\n", describe.DescribeConfig(config))
builder, err := s.builder.Builder(config, s2ibuild.Overrides{Downloader: download})
if err != nil {
return err
}
glog.V(4).Infof("Starting S2I build from %s/%s BuildConfig ...", s.build.Namespace, s.build.Name)
if _, err = builder.Build(config); err != nil {
return err
}
cname := containerName("s2i", s.build.Name, s.build.Namespace, "post-commit")
if err := execPostCommitHook(s.dockerClient, s.build.Spec.PostCommit, buildTag, cname); err != 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.Warningf("Failed to remove temporary build tag %v: %v", buildTag, err)
}
defer glog.Flush()
if push {
// Get the Docker push authentication
pushAuthConfig, authPresent := dockercfg.NewHelper().GetDockerAuth(
pushTag,
dockercfg.PushAuthType,
)
if authPresent {
glog.Infof("Using provided push secret for pushing %s image", pushTag)
} else {
glog.Infof("No push secret provided")
}
glog.Infof("Pushing %s image ...", pushTag)
if err := pushImage(s.dockerClient, pushTag, pushAuthConfig); err != nil {
// write extended error message to assist in problem resolution
msg := fmt.Sprintf("Failed to push image. Response from registry is: %v", err)
if authPresent {
glog.Infof("Registry server Address: %s", pushAuthConfig.ServerAddress)
glog.Infof("Registry server User Name: %s", pushAuthConfig.Username)
glog.Infof("Registry server Email: %s", pushAuthConfig.Email)
passwordPresent := "<<empty>>"
if len(pushAuthConfig.Password) > 0 {
passwordPresent = "<<non-empty>>"
}
glog.Infof("Registry server Password: %s", passwordPresent)
}
return errors.New(msg)
}
glog.Infof("Successfully pushed %s", pushTag)
}
return nil
}
type downloader struct {
s *S2IBuilder
in io.Reader
timeout time.Duration
dir string
contextDir string
tmpDir string
}
func (d *downloader) Download(config *s2iapi.Config) (*s2iapi.SourceInfo, error) {
var targetDir string
if len(d.contextDir) > 0 {
targetDir = d.tmpDir
} else {
targetDir = d.dir
}
// fetch source
sourceInfo, err := fetchSource(d.s.dockerClient, targetDir, d.s.build, d.timeout, d.in, d.s.gitClient)
if err != nil {
return nil, err
}
if sourceInfo != nil {
updateBuildRevision(d.s.client, d.s.build, sourceInfo)
}
if sourceInfo != nil {
sourceInfo.ContextDir = config.ContextDir
}
// if a context dir is provided, move the context dir contents into the src location
if len(d.contextDir) > 0 {
srcDir := filepath.Join(targetDir, d.contextDir)
if err := os.Remove(d.dir); err != nil {
return nil, err
}
if err := os.Rename(srcDir, d.dir); err != nil {
return nil, err
}
}
if sourceInfo != nil {
return &sourceInfo.SourceInfo, nil
}
return nil, 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 *api.Build) map[string]string {
bi := buildInfo(build)
envVars := make(map[string]string, len(bi))
for _, item := range bi {
envVars[item.Key] = item.Value
}
return envVars
}
// 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 *api.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 := url.Parse(httpProxy)
if err != nil {
return nil, err
}
config.HTTPProxy = proxyURL
}
if len(httpsProxy) > 0 {
proxyURL, err := url.Parse(httpsProxy)
if err != nil {
return nil, err
}
config.HTTPSProxy = proxyURL
}
return config, nil
}