-
Notifications
You must be signed in to change notification settings - Fork 0
/
daemon_images.go
486 lines (416 loc) · 11.9 KB
/
daemon_images.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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
package main
import (
"crypto/sha256"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"sync"
"time"
"github.com/lxc/lxd/client"
"github.com/lxc/lxd/lxd/cluster"
"github.com/lxc/lxd/lxd/db"
"github.com/lxc/lxd/lxd/operations"
"github.com/lxc/lxd/lxd/util"
"github.com/lxc/lxd/shared"
"github.com/lxc/lxd/shared/api"
"github.com/lxc/lxd/shared/cancel"
"github.com/lxc/lxd/shared/ioprogress"
"github.com/lxc/lxd/shared/logger"
"github.com/lxc/lxd/shared/units"
"github.com/lxc/lxd/shared/version"
log "github.com/lxc/lxd/shared/log15"
)
var imagesDownloading = map[string]chan bool{}
var imagesDownloadingLock sync.Mutex
// ImageDownload resolves the image fingerprint and if not in the database, downloads it
func (d *Daemon) ImageDownload(op *operations.Operation, server string, protocol string, certificate string, secret string, alias string, imageType string, forContainer bool, autoUpdate bool, storagePool string, preferCached bool, project string) (*api.Image, error) {
var err error
var ctxMap log.Ctx
var remote lxd.ImageServer
var info *api.Image
// Default protocol is LXD
if protocol == "" {
protocol = "lxd"
}
// Default the fingerprint to the alias string we received
fp := alias
// Attempt to resolve the alias
if shared.StringInSlice(protocol, []string{"lxd", "simplestreams"}) {
args := &lxd.ConnectionArgs{
TLSServerCert: certificate,
UserAgent: version.UserAgent,
Proxy: d.proxy,
CachePath: d.os.CacheDir,
CacheExpiry: time.Hour,
}
if protocol == "lxd" {
// Setup LXD client
remote, err = lxd.ConnectPublicLXD(server, args)
if err != nil {
return nil, err
}
} else {
// Setup simplestreams client
remote, err = lxd.ConnectSimpleStreams(server, args)
if err != nil {
return nil, err
}
}
// For public images, handle aliases and initial metadata
if secret == "" {
// Look for a matching alias
entry, _, err := remote.GetImageAliasType(imageType, fp)
if err == nil {
fp = entry.Target
}
// Expand partial fingerprints
info, _, err = remote.GetImage(fp)
if err != nil {
return nil, err
}
fp = info.Fingerprint
}
}
// If auto-update is on and we're being given the image by
// alias, try to use a locally cached image matching the given
// server/protocol/alias, regardless of whether it's stale or
// not (we can assume that it will be not *too* stale since
// auto-update is on).
interval, err := cluster.ConfigGetInt64(d.cluster, "images.auto_update_interval")
if err != nil {
return nil, err
}
if preferCached && interval > 0 && alias != fp {
for _, architecture := range d.os.Architectures {
cachedFingerprint, err := d.cluster.ImageSourceGetCachedFingerprint(server, protocol, alias, imageType, architecture)
if err == nil && cachedFingerprint != fp {
fp = cachedFingerprint
break
}
}
}
// Check if the image already exists in this project (partial hash match)
_, imgInfo, err := d.cluster.ImageGet(project, fp, false, true)
if err == db.ErrNoSuchObject {
// Check if the image already exists in some other project.
_, imgInfo, err = d.cluster.ImageGetFromAnyProject(fp)
if err == nil {
// We just need to insert the database data, no actual download necessary.
err = d.cluster.ImageInsert(
project, imgInfo.Fingerprint, imgInfo.Filename, imgInfo.Size, false,
imgInfo.AutoUpdate, imgInfo.Architecture, imgInfo.CreatedAt, imgInfo.ExpiresAt,
imgInfo.Properties, imgInfo.Type)
if err != nil {
return nil, err
}
var id int
id, imgInfo, err = d.cluster.ImageGet(project, fp, false, true)
if err != nil {
return nil, err
}
err = d.cluster.ImageSourceInsert(id, server, protocol, certificate, alias)
if err != nil {
return nil, err
}
}
}
if err == nil {
logger.Debug("Image already exists in the db", log.Ctx{"image": fp})
info = imgInfo
// If not requested in a particular pool, we're done.
if storagePool == "" {
return info, nil
}
// Get the ID of the target storage pool
poolID, err := d.cluster.StoragePoolGetID(storagePool)
if err != nil {
return nil, err
}
// Check if the image is already in the pool
poolIDs, err := d.cluster.ImageGetPools(info.Fingerprint)
if err != nil {
return nil, err
}
if shared.Int64InSlice(poolID, poolIDs) {
logger.Debugf("Image already exists on storage pool \"%s\"", storagePool)
return info, nil
}
// Import the image in the pool
logger.Debugf("Image does not exist on storage pool \"%s\"", storagePool)
err = imageCreateInPool(d, info, storagePool)
if err != nil {
logger.Debugf("Failed to create image on storage pool \"%s\": %s", storagePool, err)
return nil, err
}
logger.Debugf("Created image on storage pool \"%s\"", storagePool)
return info, nil
}
// Deal with parallel downloads
imagesDownloadingLock.Lock()
if waitChannel, ok := imagesDownloading[fp]; ok {
// We are already downloading the image
imagesDownloadingLock.Unlock()
logger.Debug(
"Already downloading the image, waiting for it to succeed",
log.Ctx{"image": fp})
// Wait until the download finishes (channel closes)
<-waitChannel
// Grab the database entry
_, imgInfo, err := d.cluster.ImageGet(project, fp, false, true)
if err != nil {
// Other download failed, lets try again
logger.Error("Other image download didn't succeed", log.Ctx{"image": fp})
} else {
// Other download succeeded, we're done
return imgInfo, nil
}
} else {
imagesDownloadingLock.Unlock()
}
// Add the download to the queue
imagesDownloadingLock.Lock()
imagesDownloading[fp] = make(chan bool)
imagesDownloadingLock.Unlock()
// Unlock once this func ends.
defer func() {
imagesDownloadingLock.Lock()
if waitChannel, ok := imagesDownloading[fp]; ok {
close(waitChannel)
delete(imagesDownloading, fp)
}
imagesDownloadingLock.Unlock()
}()
// Begin downloading
if op == nil {
ctxMap = log.Ctx{"alias": alias, "server": server}
} else {
ctxMap = log.Ctx{"trigger": op.URL(), "image": fp, "operation": op.ID(), "alias": alias, "server": server}
}
logger.Info("Downloading image", ctxMap)
// Cleanup any leftover from a past attempt
destDir := shared.VarPath("images")
destName := filepath.Join(destDir, fp)
failure := true
cleanup := func() {
if failure {
os.Remove(destName)
os.Remove(destName + ".rootfs")
}
}
defer cleanup()
// Setup a progress handler
progress := func(progress ioprogress.ProgressData) {
if op == nil {
return
}
meta := op.Metadata()
if meta == nil {
meta = make(map[string]interface{})
}
if meta["download_progress"] != progress.Text {
meta["download_progress"] = progress.Text
op.UpdateMetadata(meta)
}
}
var canceler *cancel.Canceler
if op != nil {
canceler = cancel.NewCanceler()
op.SetCanceler(canceler)
}
if protocol == "lxd" || protocol == "simplestreams" {
// Create the target files
dest, err := os.Create(destName)
if err != nil {
return nil, err
}
defer dest.Close()
destRootfs, err := os.Create(destName + ".rootfs")
if err != nil {
return nil, err
}
defer destRootfs.Close()
// Get the image information
if info == nil {
if secret != "" {
info, _, err = remote.GetPrivateImage(fp, secret)
if err != nil {
return nil, err
}
// Expand the fingerprint now and mark alias string to match
fp = info.Fingerprint
alias = info.Fingerprint
} else {
info, _, err = remote.GetImage(fp)
if err != nil {
return nil, err
}
}
}
// Compatibility with older LXD servers
if info.Type == "" {
info.Type = "container"
}
// Download the image
var resp *lxd.ImageFileResponse
request := lxd.ImageFileRequest{
MetaFile: io.WriteSeeker(dest),
RootfsFile: io.WriteSeeker(destRootfs),
ProgressHandler: progress,
Canceler: canceler,
DeltaSourceRetriever: func(fingerprint string, file string) string {
path := shared.VarPath("images", fmt.Sprintf("%s.%s", fingerprint, file))
if shared.PathExists(path) {
return path
}
return ""
},
}
if secret != "" {
resp, err = remote.GetPrivateImageFile(fp, secret, request)
} else {
resp, err = remote.GetImageFile(fp, request)
}
if err != nil {
return nil, err
}
// Truncate down to size
if resp.RootfsSize > 0 {
err = destRootfs.Truncate(resp.RootfsSize)
if err != nil {
return nil, err
}
}
err = dest.Truncate(resp.MetaSize)
if err != nil {
return nil, err
}
// Deal with unified images
if resp.RootfsSize == 0 {
err := os.Remove(destName + ".rootfs")
if err != nil {
return nil, err
}
}
} else if protocol == "direct" {
// Setup HTTP client
httpClient, err := util.HTTPClient(certificate, d.proxy)
if err != nil {
return nil, err
}
req, err := http.NewRequest("GET", server, nil)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", version.UserAgent)
// Make the request
raw, doneCh, err := cancel.CancelableDownload(canceler, httpClient, req)
defer close(doneCh)
if err != nil {
return nil, err
}
if raw.StatusCode != http.StatusOK {
return nil, fmt.Errorf("Unable to fetch %s: %s", server, raw.Status)
}
// Progress handler
body := &ioprogress.ProgressReader{
ReadCloser: raw.Body,
Tracker: &ioprogress.ProgressTracker{
Length: raw.ContentLength,
Handler: func(percent int64, speed int64) {
progress(ioprogress.ProgressData{Text: fmt.Sprintf("%d%% (%s/s)", percent, units.GetByteSizeString(speed, 2))})
},
},
}
// Create the target files
f, err := os.Create(destName)
if err != nil {
return nil, err
}
defer f.Close()
// Hashing
sha256 := sha256.New()
// Download the image
size, err := io.Copy(io.MultiWriter(f, sha256), body)
if err != nil {
return nil, err
}
// Validate hash
result := fmt.Sprintf("%x", sha256.Sum(nil))
if result != fp {
return nil, fmt.Errorf("Hash mismatch for %s: %s != %s", server, result, fp)
}
// Parse the image
imageMeta, imageType, err := getImageMetadata(destName)
if err != nil {
return nil, err
}
info = &api.Image{}
info.Fingerprint = fp
info.Size = size
info.Architecture = imageMeta.Architecture
info.CreatedAt = time.Unix(imageMeta.CreationDate, 0)
info.ExpiresAt = time.Unix(imageMeta.ExpiryDate, 0)
info.Properties = imageMeta.Properties
info.Type = imageType
} else {
return nil, fmt.Errorf("Unsupported protocol: %v", protocol)
}
// Override visiblity
info.Public = false
// We want to enable auto-update only if we were passed an
// alias name, so we can figure when the associated
// fingerprint changes in the remote.
if alias != fp {
info.AutoUpdate = autoUpdate
}
// Create the database entry
err = d.cluster.ImageInsert(project, info.Fingerprint, info.Filename, info.Size, info.Public, info.AutoUpdate, info.Architecture, info.CreatedAt, info.ExpiresAt, info.Properties, info.Type)
if err != nil {
return nil, err
}
// Image is in the DB now, don't wipe on-disk files on failure
failure = false
// Check if the image path changed (private images)
newDestName := filepath.Join(destDir, fp)
if newDestName != destName {
err = shared.FileMove(destName, newDestName)
if err != nil {
return nil, err
}
if shared.PathExists(destName + ".rootfs") {
err = shared.FileMove(destName+".rootfs", newDestName+".rootfs")
if err != nil {
return nil, err
}
}
}
// Record the image source
if alias != fp {
id, _, err := d.cluster.ImageGet(project, fp, false, true)
if err != nil {
return nil, err
}
err = d.cluster.ImageSourceInsert(id, server, protocol, certificate, alias)
if err != nil {
return nil, err
}
}
// Import into the requested storage pool
if storagePool != "" {
err = imageCreateInPool(d, info, storagePool)
if err != nil {
return nil, err
}
}
// Mark the image as "cached" if downloading for a container
if forContainer {
err := d.cluster.ImageLastAccessInit(fp)
if err != nil {
return nil, err
}
}
logger.Info("Image downloaded", ctxMap)
return info, nil
}