-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
dependencies.go
281 lines (241 loc) · 9.14 KB
/
dependencies.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
/*
Copyright 2019 The Skaffold Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package docker
import (
"context"
"fmt"
"os"
"path/filepath"
"runtime"
"sort"
"github.com/moby/buildkit/frontend/dockerfile/dockerignore"
"github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/constants"
"github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/util"
"github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/walk"
)
var (
dependencyCache = util.NewSyncStore[[]string]()
)
// BuildConfig encapsulates all the build configuration required for performing a dockerbuild.
type BuildConfig struct {
workspace string
artifact string
dockerfilePath string
args map[string]*string
}
// NewBuildConfig returns a `BuildConfig` for a dockerfilePath build.
func NewBuildConfig(ws string, a string, path string, args map[string]*string) BuildConfig {
return BuildConfig{
workspace: ws,
artifact: a,
dockerfilePath: path,
args: args,
}
}
// NormalizeDockerfilePath returns the absolute path to the dockerfilePath.
func NormalizeDockerfilePath(context, dockerfile string) (string, error) {
// Expected case: should be found relative to the context directory.
// If it does not exist, check if it's found relative to the current directory in case it's shared.
// Otherwise return the path relative to the context directory, where it should have been.
rel := filepath.Join(context, dockerfile)
if _, err := os.Stat(rel); os.IsNotExist(err) {
if _, err := os.Stat(dockerfile); err == nil || !os.IsNotExist(err) {
return filepath.Abs(dockerfile)
}
}
if runtime.GOOS == constants.Windows && (filepath.VolumeName(dockerfile) != "" || filepath.IsAbs(dockerfile)) {
return dockerfile, nil
}
return filepath.Abs(rel)
}
// GetDependencies finds the sources dependency for the given docker artifact.
// it caches the results for the computed dependency which can be used by `GetDependenciesCached`
// All paths are relative to the workspace.
func GetDependencies(ctx context.Context, buildCfg BuildConfig, cfg Config) ([]string, error) {
absDockerfilePath, err := NormalizeDockerfilePath(buildCfg.workspace, buildCfg.dockerfilePath)
if err != nil {
return nil, fmt.Errorf("normalizing dockerfilePath path: %w", err)
}
result, err := getDependencies(ctx, buildCfg.workspace, buildCfg.dockerfilePath, absDockerfilePath, buildCfg.args, cfg)
dependencyCache.Store(buildCfg.artifact, result, err)
return result, err
}
// GetDependencies finds the sources dependency for the given docker artifact.
// it caches the results for the computed dependency which can be used by `GetDependenciesCached`
// All paths are relative to the workspace.
func GetDependenciesByDockerCopyFromTo(ctx context.Context, buildCfg BuildConfig, cfg Config) (map[string][]string, error) {
absDockerfilePath, err := NormalizeDockerfilePath(buildCfg.workspace, buildCfg.dockerfilePath)
if err != nil {
return nil, fmt.Errorf("normalizing dockerfilePath path: %w", err)
}
ftToDependencies := getDependenciesByDockerCopyFromTo(ctx, buildCfg.workspace, buildCfg.dockerfilePath, absDockerfilePath, buildCfg.args, cfg)
return resultPairForDockerCopyFromTo(ftToDependencies)
}
// GetDependenciesCached reads from cache finds the sources dependency for the given docker artifact.
// All paths are relative to the workspace.
func GetDependenciesCached(ctx context.Context, buildCfg BuildConfig, cfg Config) ([]string, error) {
absDockerfilePath, err := NormalizeDockerfilePath(buildCfg.workspace, buildCfg.dockerfilePath)
if err != nil {
return nil, fmt.Errorf("normalizing dockerfilePath path: %w", err)
}
return dependencyCache.Exec(buildCfg.artifact, func() ([]string, error) {
return getDependencies(ctx, buildCfg.workspace, buildCfg.dockerfilePath, absDockerfilePath, buildCfg.args, cfg)
})
}
func resultPairForDockerCopyFromTo(deps interface{}) (map[string][]string, error) {
switch t := deps.(type) {
case error:
return nil, t
case map[string][]string:
return t, nil
default:
return nil, fmt.Errorf("internal error when retrieving cache result of type %T", t)
}
}
func getDependencies(ctx context.Context, workspace string, dockerfilePath string, absDockerfilePath string, buildArgs map[string]*string, cfg Config) ([]string, error) {
// If the Dockerfile doesn't exist, we can't compute the dependency.
// But since we know the Dockerfile is a dependency, let's return a list
// with only that file. It makes errors down the line more actionable
// than returning an error now.
if _, err := os.Stat(absDockerfilePath); os.IsNotExist(err) {
return []string{dockerfilePath}, nil
}
fts, err := ReadCopyCmdsFromDockerfile(ctx, false, absDockerfilePath, workspace, buildArgs, cfg)
if err != nil {
return nil, err
}
excludes, err := readDockerignore(workspace, absDockerfilePath)
if err != nil {
return nil, fmt.Errorf("reading .dockerignore: %w", err)
}
deps := make([]string, 0, len(fts))
for _, ft := range fts {
deps = append(deps, ft.From)
}
files, err := WalkWorkspace(workspace, excludes, deps)
if err != nil {
return nil, fmt.Errorf("walking workspace: %w", err)
}
// Always add dockerfile even if it's .dockerignored. The daemon will need it anyways.
if !filepath.IsAbs(dockerfilePath) {
files[dockerfilePath] = true
} else {
files[absDockerfilePath] = true
}
// Ignore .dockerignore
delete(files, ".dockerignore")
var dependencies []string
for file := range files {
dependencies = append(dependencies, file)
}
sort.Strings(dependencies)
return dependencies, nil
}
func getDependenciesByDockerCopyFromTo(ctx context.Context, workspace string, dockerfilePath string, absDockerfilePath string, buildArgs map[string]*string, cfg Config) interface{} {
// If the Dockerfile doesn't exist, we can't compute the dependency.
// But since we know the Dockerfile is a dependency, let's return a list
// with only that file. It makes errors down the line more actionable
// than returning an error now.
if _, err := os.Stat(absDockerfilePath); os.IsNotExist(err) {
return []string{dockerfilePath}
}
fts, err := ReadCopyCmdsFromDockerfile(ctx, false, absDockerfilePath, workspace, buildArgs, cfg)
if err != nil {
return err
}
excludes, err := readDockerignore(workspace, absDockerfilePath)
if err != nil {
return fmt.Errorf("reading .dockerignore: %w", err)
}
ftToDependencies := map[string][]string{}
for _, ft := range fts {
files, err := WalkWorkspace(workspace, excludes, []string{ft.From})
if err != nil {
return fmt.Errorf("walking workspace: %w", err)
}
// Always add dockerfile even if it's .dockerignored. The daemon will need it anyways.
if !filepath.IsAbs(dockerfilePath) {
files[dockerfilePath] = true
} else {
files[absDockerfilePath] = true
}
// Ignore .dockerignore
delete(files, ".dockerignore")
var dependencies []string
for file := range files {
dependencies = append(dependencies, file)
}
sort.Strings(dependencies)
ftToDependencies[ft.String()] = dependencies
}
return ftToDependencies
}
// readDockerignore reads patterns to ignore
func readDockerignore(workspace string, absDockerfilePath string) ([]string, error) {
var excludes []string
dockerignorePaths := []string{
absDockerfilePath + ".dockerignore",
filepath.Join(workspace, ".dockerignore"),
}
for _, dockerignorePath := range dockerignorePaths {
if _, err := os.Stat(dockerignorePath); !os.IsNotExist(err) {
r, err := os.Open(dockerignorePath)
if err != nil {
return nil, err
}
defer r.Close()
excludes, err = dockerignore.ReadAll(r)
if err != nil {
return nil, err
}
return excludes, nil
}
}
return nil, nil
}
// WalkWorkspace walks the given host directories and records all files found.
// Note: if you change this function, you might also want to modify walkWorkspaceWithDestinations.
func WalkWorkspace(workspace string, excludes, deps []string) (map[string]bool, error) {
dockerIgnored, err := NewDockerIgnorePredicate(workspace, excludes)
if err != nil {
return nil, err
}
// Walk the workspace
files := make(map[string]bool)
for _, dep := range deps {
absFrom := filepath.Join(workspace, dep)
keepFile := func(path string, info walk.Dirent) (bool, error) {
if info.IsDir() && path == absFrom {
return true, nil
}
ignored, err := dockerIgnored(path, info)
if err != nil {
return false, err
}
return !ignored, nil
}
if err := walk.From(absFrom).Unsorted().When(keepFile).Do(func(path string, info walk.Dirent) error {
relPath, err := filepath.Rel(workspace, path)
if err != nil {
return err
}
if util.IsEmptyDir(path) || !info.IsDir() {
files[relPath] = true
}
return nil
}); err != nil {
return nil, fmt.Errorf("walking %q: %w", absFrom, err)
}
}
return files, nil
}