forked from GoogleContainerTools/container-diff
/
image_prep_utils.go
295 lines (259 loc) · 7.48 KB
/
image_prep_utils.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
package utils
import (
"archive/tar"
"compress/gzip"
"encoding/json"
"errors"
"io/ioutil"
"os"
"path/filepath"
"reflect"
"regexp"
"strings"
"github.com/containers/image/docker"
"github.com/docker/docker/api/types/container"
"github.com/golang/glog"
)
var sourceToPrepMap = map[string]Prepper{
"ID": IDPrepper{},
"URL": CloudPrepper{},
"tar": TarPrepper{},
}
var sourceCheckMap = map[string]func(string) bool{
"ID": CheckImageID,
"URL": CheckImageURL,
"tar": CheckTar,
}
type Image struct {
Source string
FSPath string
Config ConfigSchema
}
type ImageHistoryItem struct {
CreatedBy string `json:"created_by"`
}
type ConfigObject struct {
Env []string `json:"Env"`
}
type ConfigSchema struct {
Config ConfigObject `json:"config"`
History []ImageHistoryItem `json:"history"`
}
type ImagePrepper struct {
Source string
}
type Prepper interface {
getFileSystem() (string, error)
getConfig() (ConfigSchema, error)
}
func (p ImagePrepper) GetImage() (Image, error) {
glog.Infof("Starting prep for image %s", p.Source)
img := p.Source
var prepper Prepper
for source, check := range sourceCheckMap {
if check(img) {
typePrepper := reflect.TypeOf(sourceToPrepMap[source])
prepper = reflect.New(typePrepper).Interface().(Prepper)
reflect.ValueOf(prepper).Elem().Field(0).Set(reflect.ValueOf(p))
break
}
}
if prepper == nil {
return Image{}, errors.New("Could not retrieve image from source")
}
imgPath, err := prepper.getFileSystem()
if err != nil {
return Image{}, err
}
config, err := prepper.getConfig()
if err != nil {
glog.Error("Error retrieving History: ", err)
}
glog.Infof("Finished prepping image %s", p.Source)
return Image{
Source: img,
FSPath: imgPath,
Config: config,
}, nil
}
func getImageFromTar(tarPath string) (string, error) {
glog.Info("Extracting image tar to obtain image file system")
path := strings.TrimSuffix(tarPath, filepath.Ext(tarPath))
err := unpackDockerSave(tarPath, path)
return path, err
}
// CloudPrepper prepares images sourced from a Cloud registry
type CloudPrepper struct {
ImagePrepper
}
func (p CloudPrepper) getFileSystem() (string, error) {
// The regexp when passed a string creates a list of the form
// [repourl/image:tag, image:tag, tag] (the tag may or may not be present)
URLPattern := regexp.MustCompile("^.+/(.+(:.+){0,1})$")
URLMatch := URLPattern.FindStringSubmatch(p.Source)
// Removing the ":" so that the image path name can be <image><tag>
path := strings.Replace(URLMatch[1], ":", "", -1)
ref, err := docker.ParseReference("//" + p.Source)
if err != nil {
panic(err)
}
img, err := ref.NewImage(nil)
if err != nil {
glog.Error(err)
return "", err
}
defer img.Close()
imgSrc, err := ref.NewImageSource(nil, nil)
if err != nil {
glog.Error(err)
return "", err
}
if _, ok := os.Stat(path); ok != nil {
os.MkdirAll(path, 0777)
}
for _, b := range img.LayerInfos() {
bi, _, err := imgSrc.GetBlob(b)
if err != nil {
glog.Errorf("Diff may be inaccurate, failed to pull image layer with error: %s", err)
}
gzf, err := gzip.NewReader(bi)
if err != nil {
glog.Errorf("Diff may be inaccurate, failed to read layers with error: %s", err)
}
tr := tar.NewReader(gzf)
err = unpackTar(tr, path)
if err != nil {
glog.Errorf("Diff may be inaccurate, failed to untar layer with error: %s", err)
}
}
return path, nil
}
func (p CloudPrepper) getConfig() (ConfigSchema, error) {
ref, err := docker.ParseReference("//" + p.Source)
if err != nil {
return ConfigSchema{}, err
}
img, err := ref.NewImage(nil)
if err != nil {
glog.Errorf("Error referencing image %s from registry: %s", p.Source, err)
return ConfigSchema{}, errors.New("Could not obtain image config")
}
defer img.Close()
configBlob, err := img.ConfigBlob()
if err != nil {
glog.Errorf("Error obtaining config blob for image %s from registry: %s", p.Source, err)
return ConfigSchema{}, errors.New("Could not obtain image config")
}
var config ConfigSchema
err = json.Unmarshal(configBlob, &config)
if err != nil {
glog.Errorf("Error with config file struct for image %s: %s", p.Source, err)
return ConfigSchema{}, errors.New("Could not obtain image config")
}
return config, nil
}
type IDPrepper struct {
ImagePrepper
}
func (p IDPrepper) getFileSystem() (string, error) {
// check client compatibility with Docker API
valid, err := ValidDockerVersion()
if err != nil {
return "", err
}
var tarPath string
if !valid {
glog.Info("Docker version incompatible with api, shelling out to local Docker client.")
tarPath, err = imageToTarCmd(p.Source, p.Source)
} else {
tarPath, err = saveImageToTar(p.Source, p.Source)
}
if err != nil {
return "", err
}
defer os.Remove(tarPath)
return getImageFromTar(tarPath)
}
func (p IDPrepper) getConfig() (ConfigSchema, error) {
// check client compatibility with Docker API
valid, err := ValidDockerVersion()
if err != nil {
return ConfigSchema{}, err
}
var containerConfig container.Config
if !valid {
glog.Info("Docker version incompatible with api, shelling out to local Docker client.")
containerConfig, err = getImageConfigCmd(p.Source)
} else {
containerConfig, err = getImageConfig(p.Source)
}
if err != nil {
return ConfigSchema{}, err
}
config := ConfigObject{
Env: containerConfig.Env,
}
history := p.getHistory()
return ConfigSchema{
Config: config,
History: history,
}, nil
}
func (p IDPrepper) getHistory() []ImageHistoryItem {
history, err := getImageHistory(p.Source)
if err != nil {
glog.Error("Could not obtain image history for %s: %s", p.Source, err)
}
historyItems := []ImageHistoryItem{}
for _, item := range history {
historyItems = append(historyItems, ImageHistoryItem{CreatedBy: item.CreatedBy})
}
return historyItems
}
type TarPrepper struct {
ImagePrepper
}
func (p TarPrepper) getFileSystem() (string, error) {
return getImageFromTar(p.Source)
}
func (p TarPrepper) getConfig() (ConfigSchema, error) {
tempDir := strings.TrimSuffix(p.Source, filepath.Ext(p.Source)) + "-config"
defer os.RemoveAll(tempDir)
err := UnTar(p.Source, tempDir)
if err != nil {
return ConfigSchema{}, err
}
contents, err := ioutil.ReadDir(tempDir)
if err != nil {
glog.Errorf("Could not read image tar contents: %s", err)
return ConfigSchema{}, errors.New("Could not obtain image config")
}
var config ConfigSchema
configList := []string{}
for _, item := range contents {
if filepath.Ext(item.Name()) == ".json" && item.Name() != "manifest.json" {
if len(configList) != 0 {
// Another <image>.json file has already been processed and the image config obtained is uncertain.
glog.Error("Multiple possible config sources detected for image at " + p.Source + ". Multiple images likely contained in tar. Choosing first one, but diff results may not be completely accurate.")
break
}
fileName := filepath.Join(tempDir, item.Name())
file, err := ioutil.ReadFile(fileName)
if err != nil {
glog.Errorf("Could not read config file %s: %s", fileName, err)
return ConfigSchema{}, errors.New("Could not obtain image config")
}
err = json.Unmarshal(file, &config)
if err != nil {
glog.Errorf("Could not marshal config file %s: %s", fileName, err)
return ConfigSchema{}, errors.New("Could not obtain image config")
}
configList = append(configList, fileName)
}
}
if reflect.DeepEqual(ConfigSchema{}, config) {
glog.Warningf("No image config found in tar source %s. Pip differ may be incomplete due to missing PYTHONPATH information.")
return config, nil
}
return config, nil
}