Debian Codegraph @

cmd/imagebuilder/imagebuilder.go

raw ◀ ▶
2 Debian patches touch this file
1 package main
2
3 import (
4 "errors"
5 "flag"
6 "fmt"
7 "log"
8 "os"
9 "path/filepath"
10 "strings"
11 "syscall"
12
13 "github.com/distribution/reference"
14 docker "github.com/fsouza/go-dockerclient"
•15 dockerregistrytypes "github.com/docker/docker/api/types/registry"
•16 "k8s.io/klog/v2"
17
18 "github.com/openshift/imagebuilder"
19 "github.com/openshift/imagebuilder/dockerclient"
20 )
21
22 func init() {
23 klog.InitFlags(flag.CommandLine)
24 }
25
26 func main() {
27 log.SetFlags(0)
28 options := dockerclient.NewClientExecutor(nil)
29 var tags stringSliceFlag
30 var target string
31 var dockerfilePath string
32 var imageFrom string
33 var privileged bool
34 var version bool
35 var mountSpecs stringSliceFlag
36
37 VERSION := "1.2.22"
38 arguments := stringMapFlag{}
39
40 flag.Var(&tags, "t", "The name to assign this image, if any. May be specified multiple times.")
41 flag.Var(&tags, "tag", "The name to assign this image, if any. May be specified multiple times.")
42 flag.Var(&arguments, "build-arg", "An optional list of build-time variables usable as ARG in Dockerfile. Use --build-arg ARG1=VAL1 --build-arg ARG2=VAL2 syntax for passing multiple build args.")
43 flag.StringVar(&dockerfilePath, "f", dockerfilePath, "An optional path to a Dockerfile to use. You may pass multiple docker files using the operating system delimiter.")
44 flag.StringVar(&dockerfilePath, "file", dockerfilePath, "An optional path to a Dockerfile to use. You may pass multiple docker files using the operating system delimiter.")
45 flag.StringVar(&imageFrom, "from", imageFrom, "An optional FROM to use instead of the one in the Dockerfile.")
46 flag.StringVar(&target, "target", "", "The name of a stage within the Dockerfile to build.")
47 flag.Var(&mountSpecs, "mount", "An optional list of files and directories to mount during the build. Use SRC:DST syntax for each path.")
48 flag.BoolVar(&options.AllowPull, "allow-pull", true, "Pull the images that are not present.")
49 flag.BoolVar(&options.IgnoreUnrecognizedInstructions, "ignore-unrecognized-instructions", true, "If an unrecognized Docker instruction is encountered, warn but do not fail the build.")
50 flag.BoolVar(&options.StrictVolumeOwnership, "strict-volume-ownership", false, "Due to limitations in docker `cp`, owner permissions on volumes are lost. This flag will fail builds that might fall victim to this.")
51 flag.BoolVar(&privileged, "privileged", false, "Builds run as privileged containers instead of restricted containers.")
52 flag.BoolVar(&version, "version", false, "Display imagebuilder version.")
53
54 flag.Parse()
55
56 args := flag.Args()
57 if version {
58 fmt.Println(VERSION)
59 return
60 }
61
62 if len(args) != 1 {
63 log.Fatalf("You must provide one argument, the name of a directory to build")
64 }
65
66 options.Directory = args[0]
67 if len(tags) > 0 {
68 options.Tag = tags[0]
69 options.AdditionalTags = tags[1:]
70 }
71 if len(dockerfilePath) == 0 {
72 dockerfilePath = filepath.Join(options.Directory, "Dockerfile")
73 }
74
75 if privileged {
76 if options.HostConfig == nil {
77 options.HostConfig = &docker.HostConfig{}
78 }
79 options.HostConfig.Privileged = true
80 }
81
82 var mounts []dockerclient.Mount
83 for _, s := range mountSpecs {
84 segments := strings.Split(s, ":")
85 if len(segments) != 2 {
86 log.Fatalf("--mount must be of the form SOURCE:DEST")
87 }
88 mounts = append(mounts, dockerclient.Mount{SourcePath: segments[0], DestinationPath: segments[1]})
89 }
90 options.TransientMounts = mounts
91
92 options.Out, options.ErrOut = os.Stdout, os.Stderr
93 authConfigurations, err := docker.NewAuthConfigurationsFromDockerCfg()
94 if err != nil {
95 if errors.Is(err, syscall.ENOENT) {
96 klog.Warning("No docker configuration found")
97 } else {
98 log.Fatalf("reading authentication configurations: %v", err)
99 }
100 }
101 if authConfigurations == nil {
102 klog.V(4).Info("No authentication secrets found")
103 }
104
105 options.AuthFn = func(name string) ([]dockerregistrytypes.AuthConfig, bool) {
106 if authConfigurations != nil {
107 if authConfig, ok := authConfigurations.Configs[name]; ok {
108 klog.V(4).Infof("Found authentication secret for registry %q", name)
109 return []dockerregistrytypes.AuthConfig{{
110 Username: authConfig.Username,
111 Password: authConfig.Password,
112 ServerAddress: authConfig.ServerAddress,
113 IdentityToken: authConfig.IdentityToken,
114 RegistryToken: authConfig.RegistryToken,
115 }}, true
116 }
117 if named, err := reference.ParseNormalizedNamed(name); err == nil {
118 domain := reference.Domain(named)
119 if authConfig, ok := authConfigurations.Configs[domain]; ok {
120 klog.V(4).Infof("Found authentication secret for registry %q", domain)
121 return []dockerregistrytypes.AuthConfig{{
122 Username: authConfig.Username,
123 Password: authConfig.Password,
124 ServerAddress: authConfig.ServerAddress,
125 IdentityToken: authConfig.IdentityToken,
126 RegistryToken: authConfig.RegistryToken,
127 }}, true
128 }
129 if domain == "docker.io" || strings.HasSuffix(domain, ".docker.io") {
130 var auths []dockerregistrytypes.AuthConfig
131 for _, aka := range []string{"docker.io", "index.docker.io", "https://index.docker.io/v1/"} {
132 if aka == domain {
133 continue
134 }
135 if authConfig, ok := authConfigurations.Configs[aka]; ok {
136 klog.V(4).Infof("Found authentication secret for registry %q", aka)
137 auths = append(auths, dockerregistrytypes.AuthConfig{
138 Username: authConfig.Username,
139 Password: authConfig.Password,
140 ServerAddress: authConfig.ServerAddress,
141 IdentityToken: authConfig.IdentityToken,
142 RegistryToken: authConfig.RegistryToken,
143 })
144 }
145 }
146 if len(auths) > 0 {
147 return auths, true
148 }
149 }
150 }
151 }
152 return nil, false
153 }
154 options.LogFn = func(format string, args ...interface{}) {
•155 if klog.V(2).Enabled() {
156 log.Printf("Builder: "+format, args...)
157 } else {
158 fmt.Fprintf(options.Out, "--> %s\n", fmt.Sprintf(format, args...))
159 }
160 }
161
162 dockerfiles := filepath.SplitList(dockerfilePath)
163 if len(dockerfiles) == 0 {
164 dockerfiles = []string{filepath.Join(options.Directory, "Dockerfile")}
165 }
166
167 if err := build(dockerfiles[0], dockerfiles[1:], arguments, imageFrom, target, options); err != nil {
168 log.Fatal(err.Error())
169 }
170 }
171
172 func build(dockerfile string, additionalDockerfiles []string, arguments map[string]string, from string, target string, e *dockerclient.ClientExecutor) error {
173 if err := e.DefaultExcludes(); err != nil {
174 return fmt.Errorf("error: Could not parse default .dockerignore: %v", err)
175 }
176
177 client, err := docker.NewClientFromEnv()
178 if err != nil {
179 return fmt.Errorf("error: No connection to Docker available: %v", err)
180 }
181 e.Client = client
182
183 // TODO: handle signals
184 defer func() {
185 for _, err := range e.Release() {
186 fmt.Fprintf(e.ErrOut, "error: Unable to clean up build: %v\n", err)
187 }
188 }()
189
190 node, err := imagebuilder.ParseFile(dockerfile)
191 if err != nil {
192 return err
193 }
194 for _, s := range additionalDockerfiles {
195 additionalNode, err := imagebuilder.ParseFile(s)
196 if err != nil {
197 return err
198 }
199 node.Children = append(node.Children, additionalNode.Children...)
200 }
201
202 b := imagebuilder.NewBuilder(arguments)
203 stages, err := imagebuilder.NewStages(node, b)
204 if err != nil {
205 return err
206 }
207 stages, ok := stages.ByTarget(target)
208 if !ok {
209 return fmt.Errorf("error: The target %q was not found in the provided Dockerfile", target)
210 }
211
212 lastExecutor, err := e.Stages(b, stages, from)
213 if err != nil {
214 return err
215 }
216
217 return lastExecutor.Commit(stages[len(stages)-1].Builder)
218 }
219
220 type stringSliceFlag []string
221
222 func (f *stringSliceFlag) Set(s string) error {
223 *f = append(*f, s)
224 return nil
225 }
226
227 func (f *stringSliceFlag) String() string {
228 return strings.Join(*f, " ")
229 }
230
231 type stringMapFlag map[string]string
232
233 func (f *stringMapFlag) String() string {
234 args := []string{}
235 for k, v := range *f {
236 args = append(args, strings.Join([]string{k, v}, "="))
237 }
238 return strings.Join(args, " ")
239 }
240
241 func (f *stringMapFlag) Set(value string) error {
242 kv := strings.Split(value, "=")
243 (*f)[kv[0]] = kv[1]
244 return nil
245 }