-
Notifications
You must be signed in to change notification settings - Fork 42
/
save_file.go
249 lines (225 loc) · 6.3 KB
/
save_file.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
package local
import (
"archive/tar"
"context"
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"time"
"github.com/docker/docker/api/types"
registryName "github.com/google/go-containerregistry/pkg/name"
v1 "github.com/google/go-containerregistry/pkg/v1"
"github.com/pkg/errors"
"golang.org/x/sync/errgroup"
)
func (i *Image) SaveFile() (string, error) {
f, err := os.CreateTemp("", "imgutil.local.image.export.*.tar")
if err != nil {
return "", errors.Wrap(err, "failed to create temporary file")
}
defer func() {
f.Close()
if err != nil {
os.Remove(f.Name())
}
}()
// All layers need to be present here. Missing layers are either due to utilization of
// (1) WithPreviousImage(), or (2) FromBaseImage().
// The former is only relevant if ReuseLayers() has been called which takes care of resolving them.
// The latter case needs to be handled explicitly.
if err := i.downloadBaseLayersOnce(); err != nil {
return "", errors.Wrap(err, "failed to fetch base layers")
}
errs, _ := errgroup.WithContext(context.Background())
pr, pw := io.Pipe()
// File writer
errs.Go(func() error {
defer pr.Close()
_, err = f.ReadFrom(pr)
return err
})
// Tar producer
errs.Go(func() error {
defer pw.Close()
tw := tar.NewWriter(pw)
defer tw.Close()
t, err := registryName.NewTag(i.repoName, registryName.WeakValidation)
if err != nil {
return errors.Wrap(err, "failed to create tag")
}
// returns valid 'name:tag' appending 'latest', if missing tag
repoName := t.Name()
_, err = i.addImageToTar(tw, repoName)
return err
})
err = errs.Wait()
if err != nil {
return "", err
}
return f.Name(), nil
}
func (i *Image) newConfigFile() ([]byte, error) {
if !i.withHistory {
// zero history
i.history = make([]v1.History, len(i.inspect.RootFS.Layers))
}
cfg, err := v1Config(i.inspect, i.createdAt, i.history)
if err != nil {
return nil, err
}
return json.Marshal(cfg)
}
// helpers
func addFileToTar(tw *tar.Writer, name string, contents *os.File) error {
fi, err := contents.Stat()
if err != nil {
return err
}
hdr := &tar.Header{Name: name, Mode: 0644, Size: fi.Size()}
if err := tw.WriteHeader(hdr); err != nil {
return err
}
_, err = io.Copy(tw, contents)
return err
}
func addTextToTar(tw *tar.Writer, name string, contents []byte) error {
hdr := &tar.Header{Name: name, Mode: 0644, Size: int64(len(contents))}
if err := tw.WriteHeader(hdr); err != nil {
return err
}
_, err := tw.Write(contents)
return err
}
func cleanPath(dest, header string) (string, error) {
joined := filepath.Join(dest, header)
if strings.HasPrefix(joined, filepath.Clean(dest)) {
return joined, nil
}
return "", fmt.Errorf("bad filepath: %s", header)
}
func untar(r io.Reader, dest string) error {
tr := tar.NewReader(r)
for {
hdr, err := tr.Next()
if err == io.EOF {
// end of tar archive
return nil
}
if err != nil {
return err
}
path, err := cleanPath(dest, hdr.Name)
if err != nil {
return err
}
switch hdr.Typeflag {
case tar.TypeDir:
if err := os.MkdirAll(path, hdr.FileInfo().Mode()); err != nil {
return err
}
case tar.TypeReg:
_, err := os.Stat(filepath.Dir(path))
if os.IsNotExist(err) {
if err := os.MkdirAll(filepath.Dir(path), 0750); err != nil {
return err
}
}
fh, err := os.OpenFile(filepath.Clean(path), os.O_CREATE|os.O_WRONLY, hdr.FileInfo().Mode())
if err != nil {
return err
}
if _, err := io.Copy(fh, tr); err != nil {
fh.Close()
return err
} // #nosec G110
fh.Close()
case tar.TypeSymlink:
_, err := os.Stat(filepath.Dir(path))
if os.IsNotExist(err) {
if err := os.MkdirAll(filepath.Dir(path), 0750); err != nil {
return err
}
}
if err := os.Symlink(hdr.Linkname, path); err != nil {
return err
}
default:
return fmt.Errorf("unknown file type in tar %d", hdr.Typeflag)
}
}
}
func v1Config(inspect types.ImageInspect, createdAt time.Time, history []v1.History) (v1.ConfigFile, error) {
if len(history) != len(inspect.RootFS.Layers) {
history = make([]v1.History, len(inspect.RootFS.Layers))
}
for i := range history {
// zero history
history[i].Created = v1.Time{Time: createdAt}
}
diffIDs := make([]v1.Hash, len(inspect.RootFS.Layers))
for i, layer := range inspect.RootFS.Layers {
hash, err := v1.NewHash(layer)
if err != nil {
return v1.ConfigFile{}, err
}
diffIDs[i] = hash
}
exposedPorts := make(map[string]struct{}, len(inspect.Config.ExposedPorts))
for key, val := range inspect.Config.ExposedPorts {
exposedPorts[string(key)] = val
}
var config v1.Config
if inspect.Config != nil {
var healthcheck *v1.HealthConfig
if inspect.Config.Healthcheck != nil {
healthcheck = &v1.HealthConfig{
Test: inspect.Config.Healthcheck.Test,
Interval: inspect.Config.Healthcheck.Interval,
Timeout: inspect.Config.Healthcheck.Timeout,
StartPeriod: inspect.Config.Healthcheck.StartPeriod,
Retries: inspect.Config.Healthcheck.Retries,
}
}
config = v1.Config{
AttachStderr: inspect.Config.AttachStderr,
AttachStdin: inspect.Config.AttachStdin,
AttachStdout: inspect.Config.AttachStdout,
Cmd: inspect.Config.Cmd,
Healthcheck: healthcheck,
Domainname: inspect.Config.Domainname,
Entrypoint: inspect.Config.Entrypoint,
Env: inspect.Config.Env,
Hostname: inspect.Config.Hostname,
Image: inspect.Config.Image,
Labels: inspect.Config.Labels,
OnBuild: inspect.Config.OnBuild,
OpenStdin: inspect.Config.OpenStdin,
StdinOnce: inspect.Config.StdinOnce,
Tty: inspect.Config.Tty,
User: inspect.Config.User,
Volumes: inspect.Config.Volumes,
WorkingDir: inspect.Config.WorkingDir,
ExposedPorts: exposedPorts,
ArgsEscaped: inspect.Config.ArgsEscaped,
NetworkDisabled: inspect.Config.NetworkDisabled,
MacAddress: inspect.Config.MacAddress,
StopSignal: inspect.Config.StopSignal,
Shell: inspect.Config.Shell,
}
}
return v1.ConfigFile{
Architecture: inspect.Architecture,
Created: v1.Time{Time: createdAt},
History: history,
OS: inspect.Os,
OSVersion: inspect.OsVersion,
RootFS: v1.RootFS{
Type: "layers",
DiffIDs: diffIDs,
},
Config: config,
}, nil
}