forked from canonical/lxd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lxd_images.go
660 lines (536 loc) · 15.8 KB
/
lxd_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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
package lxd
import (
"crypto/sha256"
"fmt"
"io"
"io/ioutil"
"mime"
"mime/multipart"
"net/http"
"net/url"
"os"
"strings"
"github.com/lxc/lxd/shared"
"github.com/lxc/lxd/shared/api"
"github.com/lxc/lxd/shared/cancel"
"github.com/lxc/lxd/shared/ioprogress"
)
// Image handling functions
// GetImages returns a list of available images as Image structs
func (r *ProtocolLXD) GetImages() ([]api.Image, error) {
images := []api.Image{}
_, err := r.queryStruct("GET", "/images?recursion=1", nil, "", &images)
if err != nil {
return nil, err
}
return images, nil
}
// GetImageFingerprints returns a list of available image fingerprints
func (r *ProtocolLXD) GetImageFingerprints() ([]string, error) {
urls := []string{}
// Fetch the raw value
_, err := r.queryStruct("GET", "/images", nil, "", &urls)
if err != nil {
return nil, err
}
// Parse it
fingerprints := []string{}
for _, url := range urls {
fields := strings.Split(url, "/images/")
fingerprints = append(fingerprints, fields[len(fields)-1])
}
return fingerprints, nil
}
// GetImage returns an Image struct for the provided fingerprint
func (r *ProtocolLXD) GetImage(fingerprint string) (*api.Image, string, error) {
return r.GetPrivateImage(fingerprint, "")
}
// GetImageFile downloads an image from the server, returning an ImageFileRequest struct
func (r *ProtocolLXD) GetImageFile(fingerprint string, req ImageFileRequest) (*ImageFileResponse, error) {
return r.GetPrivateImageFile(fingerprint, "", req)
}
// GetImageSecret is a helper around CreateImageSecret that returns a secret for the image
func (r *ProtocolLXD) GetImageSecret(fingerprint string) (string, error) {
op, err := r.CreateImageSecret(fingerprint)
if err != nil {
return "", err
}
return op.Metadata["secret"].(string), nil
}
// GetPrivateImage is similar to GetImage but allows passing a secret download token
func (r *ProtocolLXD) GetPrivateImage(fingerprint string, secret string) (*api.Image, string, error) {
image := api.Image{}
// Build the API path
path := fmt.Sprintf("/images/%s", url.QueryEscape(fingerprint))
if secret != "" {
path = fmt.Sprintf("%s?secret=%s", path, url.QueryEscape(secret))
}
// Fetch the raw value
etag, err := r.queryStruct("GET", path, nil, "", &image)
if err != nil {
return nil, "", err
}
return &image, etag, nil
}
// GetPrivateImageFile is similar to GetImageFile but allows passing a secret download token
func (r *ProtocolLXD) GetPrivateImageFile(fingerprint string, secret string, req ImageFileRequest) (*ImageFileResponse, error) {
// Sanity checks
if req.MetaFile == nil && req.RootfsFile == nil {
return nil, fmt.Errorf("No file requested")
}
// Prepare the response
resp := ImageFileResponse{}
// Build the URL
uri := fmt.Sprintf("%s/1.0/images/%s/export", r.httpHost, url.QueryEscape(fingerprint))
if secret != "" {
uri = fmt.Sprintf("%s?secret=%s", uri, url.QueryEscape(secret))
}
// Prepare the download request
request, err := http.NewRequest("GET", uri, nil)
if err != nil {
return nil, err
}
if r.httpUserAgent != "" {
request.Header.Set("User-Agent", r.httpUserAgent)
}
// Start the request
response, doneCh, err := cancel.CancelableDownload(req.Canceler, r.http, request)
if err != nil {
return nil, err
}
defer response.Body.Close()
defer close(doneCh)
if response.StatusCode != http.StatusOK {
_, _, err := r.parseResponse(response)
if err != nil {
return nil, err
}
}
ctype, ctypeParams, err := mime.ParseMediaType(response.Header.Get("Content-Type"))
if err != nil {
ctype = "application/octet-stream"
}
// Handle the data
body := response.Body
if req.ProgressHandler != nil {
body = &ioprogress.ProgressReader{
ReadCloser: response.Body,
Tracker: &ioprogress.ProgressTracker{
Length: response.ContentLength,
Handler: func(percent int64, speed int64) {
req.ProgressHandler(ioprogress.ProgressData{Text: fmt.Sprintf("%d%% (%s/s)", percent, shared.GetByteSizeString(speed, 2))})
},
},
}
}
// Hashing
sha256 := sha256.New()
// Deal with split images
if ctype == "multipart/form-data" {
if req.MetaFile == nil || req.RootfsFile == nil {
return nil, fmt.Errorf("Multi-part image but only one target file provided")
}
// Parse the POST data
mr := multipart.NewReader(body, ctypeParams["boundary"])
// Get the metadata tarball
part, err := mr.NextPart()
if err != nil {
return nil, err
}
if part.FormName() != "metadata" {
return nil, fmt.Errorf("Invalid multipart image")
}
size, err := io.Copy(io.MultiWriter(req.MetaFile, sha256), part)
if err != nil {
return nil, err
}
resp.MetaSize = size
resp.MetaName = part.FileName()
// Get the rootfs tarball
part, err = mr.NextPart()
if err != nil {
return nil, err
}
if part.FormName() != "rootfs" {
return nil, fmt.Errorf("Invalid multipart image")
}
size, err = io.Copy(io.MultiWriter(req.RootfsFile, sha256), part)
if err != nil {
return nil, err
}
resp.RootfsSize = size
resp.RootfsName = part.FileName()
// Check the hash
hash := fmt.Sprintf("%x", sha256.Sum(nil))
if !strings.HasPrefix(hash, fingerprint) {
return nil, fmt.Errorf("Image fingerprint doesn't match. Got %s expected %s", hash, fingerprint)
}
return &resp, nil
}
// Deal with unified images
_, cdParams, err := mime.ParseMediaType(response.Header.Get("Content-Disposition"))
if err != nil {
return nil, err
}
filename, ok := cdParams["filename"]
if !ok {
return nil, fmt.Errorf("No filename in Content-Disposition header")
}
size, err := io.Copy(io.MultiWriter(req.MetaFile, sha256), body)
if err != nil {
return nil, err
}
resp.MetaSize = size
resp.MetaName = filename
// Check the hash
hash := fmt.Sprintf("%x", sha256.Sum(nil))
if !strings.HasPrefix(hash, fingerprint) {
return nil, fmt.Errorf("Image fingerprint doesn't match. Got %s expected %s", hash, fingerprint)
}
return &resp, nil
}
// GetImageAliases returns the list of available aliases as ImageAliasesEntry structs
func (r *ProtocolLXD) GetImageAliases() ([]api.ImageAliasesEntry, error) {
aliases := []api.ImageAliasesEntry{}
// Fetch the raw value
_, err := r.queryStruct("GET", "/images/aliases?recursion=1", nil, "", &aliases)
if err != nil {
return nil, err
}
return aliases, nil
}
// GetImageAliasNames returns the list of available alias names
func (r *ProtocolLXD) GetImageAliasNames() ([]string, error) {
urls := []string{}
// Fetch the raw value
_, err := r.queryStruct("GET", "/images/aliases", nil, "", &urls)
if err != nil {
return nil, err
}
// Parse it
names := []string{}
for _, url := range urls {
fields := strings.Split(url, "/images/aliases/")
names = append(names, fields[len(fields)-1])
}
return names, nil
}
// GetImageAlias returns an existing alias as an ImageAliasesEntry struct
func (r *ProtocolLXD) GetImageAlias(name string) (*api.ImageAliasesEntry, string, error) {
alias := api.ImageAliasesEntry{}
// Fetch the raw value
etag, err := r.queryStruct("GET", fmt.Sprintf("/images/aliases/%s", url.QueryEscape(name)), nil, "", &alias)
if err != nil {
return nil, "", err
}
return &alias, etag, nil
}
// CreateImage requests that LXD creates, copies or import a new image
func (r *ProtocolLXD) CreateImage(image api.ImagesPost, args *ImageCreateArgs) (*Operation, error) {
if image.CompressionAlgorithm != "" {
if !r.HasExtension("image_compression_algorithm") {
return nil, fmt.Errorf("The server is missing the required \"image_compression_algorithm\" API extension")
}
}
// Send the JSON based request
if args == nil {
op, _, err := r.queryOperation("POST", "/images", image, "")
if err != nil {
return nil, err
}
return op, nil
}
// Prepare an image upload
if args.MetaFile == nil {
return nil, fmt.Errorf("Metadata file is required")
}
// Prepare the body
var body io.Reader
var contentType string
if args.RootfsFile == nil {
// If unified image, just pass it through
body = args.MetaFile
contentType = "application/octet-stream"
} else {
// If split image, we need mime encoding
tmpfile, err := ioutil.TempFile("", "lxc_image_")
if err != nil {
return nil, err
}
defer os.Remove(tmpfile.Name())
// Setup the multipart writer
w := multipart.NewWriter(tmpfile)
// Metadata file
fw, err := w.CreateFormFile("metadata", args.MetaName)
if err != nil {
return nil, err
}
_, err = io.Copy(fw, args.MetaFile)
if err != nil {
return nil, err
}
// Rootfs file
fw, err = w.CreateFormFile("rootfs", args.RootfsName)
if err != nil {
return nil, err
}
_, err = io.Copy(fw, args.RootfsFile)
if err != nil {
return nil, err
}
// Done writing to multipart
w.Close()
// Figure out the size of the whole thing
size, err := tmpfile.Seek(0, 2)
if err != nil {
return nil, err
}
_, err = tmpfile.Seek(0, 0)
if err != nil {
return nil, err
}
// Setup progress handler
body = &ioprogress.ProgressReader{
ReadCloser: tmpfile,
Tracker: &ioprogress.ProgressTracker{
Length: size,
Handler: func(percent int64, speed int64) {
args.ProgressHandler(ioprogress.ProgressData{Text: fmt.Sprintf("%d%% (%s/s)", percent, shared.GetByteSizeString(speed, 2))})
},
},
}
contentType = w.FormDataContentType()
}
// Prepare the HTTP request
reqURL := fmt.Sprintf("%s/1.0/images", r.httpHost)
req, err := http.NewRequest("POST", reqURL, body)
if err != nil {
return nil, err
}
// Setup the headers
req.Header.Set("Content-Type", contentType)
if image.Public {
req.Header.Set("X-LXD-public", "true")
}
if image.Filename != "" {
req.Header.Set("X-LXD-filename", image.Filename)
}
if len(image.Properties) > 0 {
imgProps := url.Values{}
for k, v := range image.Properties {
imgProps.Set(k, v)
}
req.Header.Set("X-LXD-properties", imgProps.Encode())
}
// Set the user agent
if r.httpUserAgent != "" {
req.Header.Set("User-Agent", r.httpUserAgent)
}
// Send the request
resp, err := r.do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
// Handle errors
response, _, err := r.parseResponse(resp)
if err != nil {
return nil, err
}
// Get to the operation
respOperation, err := response.MetadataAsOperation()
if err != nil {
return nil, err
}
// Setup an Operation wrapper
op := Operation{
Operation: *respOperation,
r: r,
chActive: make(chan bool),
}
return &op, nil
}
// tryCopyImage iterates through the source server URLs until one lets it download the image
func (r *ProtocolLXD) tryCopyImage(req api.ImagesPost, urls []string) (*RemoteOperation, error) {
if len(urls) == 0 {
return nil, fmt.Errorf("The source server isn't listening on the network")
}
rop := RemoteOperation{
chDone: make(chan bool),
}
// For older servers, apply the aliases after copy
if !r.HasExtension("image_create_aliases") && req.Aliases != nil {
rop.chPost = make(chan bool)
go func() {
defer close(rop.chPost)
// Wait for the main operation to finish
<-rop.chDone
if rop.err != nil {
return
}
// Get the operation data
op, err := rop.GetTarget()
if err != nil {
return
}
// Extract the fingerprint
fingerprint := op.Metadata["fingerprint"].(string)
// Add the aliases
for _, entry := range req.Aliases {
alias := api.ImageAliasesPost{}
alias.Name = entry.Name
alias.Target = fingerprint
r.CreateImageAlias(alias)
}
}()
}
// Forward targetOp to remote op
go func() {
success := false
errors := []string{}
for _, serverURL := range urls {
req.Source.Server = serverURL
op, err := r.CreateImage(req, nil)
if err != nil {
errors = append(errors, fmt.Sprintf("%s: %v", serverURL, err))
continue
}
rop.targetOp = op
for _, handler := range rop.handlers {
rop.targetOp.AddHandler(handler)
}
err = rop.targetOp.Wait()
if err != nil {
errors = append(errors, fmt.Sprintf("%s: %v", serverURL, err))
continue
}
success = true
break
}
if !success {
rop.err = fmt.Errorf("Failed remote image download:\n - %s", strings.Join(errors, "\n - "))
}
close(rop.chDone)
}()
return &rop, nil
}
// CopyImage copies an image from a remote server. Additional options can be passed using ImageCopyArgs
func (r *ProtocolLXD) CopyImage(source ImageServer, image api.Image, args *ImageCopyArgs) (*RemoteOperation, error) {
// Sanity checks
if r == source {
return nil, fmt.Errorf("The source and target servers must be different")
}
// Get source server connection information
info, err := source.GetConnectionInfo()
if err != nil {
return nil, err
}
// Prepare the copy request
req := api.ImagesPost{
Source: &api.ImagesPostSource{
ImageSource: api.ImageSource{
Certificate: info.Certificate,
Protocol: info.Protocol,
},
Fingerprint: image.Fingerprint,
Mode: "pull",
Type: "image",
},
}
// Generate secret token if needed
if !image.Public {
secret, err := source.GetImageSecret(image.Fingerprint)
if err != nil {
return nil, err
}
req.Source.Secret = secret
}
// Process the arguments
if args != nil {
req.Aliases = args.Aliases
req.AutoUpdate = args.AutoUpdate
req.Public = args.Public
if args.CopyAliases {
req.Aliases = image.Aliases
if args.Aliases != nil {
req.Aliases = append(req.Aliases, args.Aliases...)
}
}
}
return r.tryCopyImage(req, info.Addresses)
}
// UpdateImage updates the image definition
func (r *ProtocolLXD) UpdateImage(fingerprint string, image api.ImagePut, ETag string) error {
// Send the request
_, _, err := r.query("PUT", fmt.Sprintf("/images/%s", url.QueryEscape(fingerprint)), image, ETag)
if err != nil {
return err
}
return nil
}
// DeleteImage requests that LXD removes an image from the store
func (r *ProtocolLXD) DeleteImage(fingerprint string) (*Operation, error) {
// Send the request
op, _, err := r.queryOperation("DELETE", fmt.Sprintf("/images/%s", url.QueryEscape(fingerprint)), nil, "")
if err != nil {
return nil, err
}
return op, nil
}
// RefreshImage requests that LXD issues an image refresh
func (r *ProtocolLXD) RefreshImage(fingerprint string) (*Operation, error) {
if !r.HasExtension("image_force_refresh") {
return nil, fmt.Errorf("The server is missing the required \"image_force_refresh\" API extension")
}
// Send the request
op, _, err := r.queryOperation("POST", fmt.Sprintf("/images/%s/refresh", url.QueryEscape(fingerprint)), nil, "")
if err != nil {
return nil, err
}
return op, nil
}
// CreateImageSecret requests that LXD issues a temporary image secret
func (r *ProtocolLXD) CreateImageSecret(fingerprint string) (*Operation, error) {
// Send the request
op, _, err := r.queryOperation("POST", fmt.Sprintf("/images/%s/secret", url.QueryEscape(fingerprint)), nil, "")
if err != nil {
return nil, err
}
return op, nil
}
// CreateImageAlias sets up a new image alias
func (r *ProtocolLXD) CreateImageAlias(alias api.ImageAliasesPost) error {
// Send the request
_, _, err := r.query("POST", "/images/aliases", alias, "")
if err != nil {
return err
}
return nil
}
// UpdateImageAlias updates the image alias definition
func (r *ProtocolLXD) UpdateImageAlias(name string, alias api.ImageAliasesEntryPut, ETag string) error {
// Send the request
_, _, err := r.query("PUT", fmt.Sprintf("/images/aliases/%s", url.QueryEscape(name)), alias, ETag)
if err != nil {
return err
}
return nil
}
// RenameImageAlias renames an existing image alias
func (r *ProtocolLXD) RenameImageAlias(name string, alias api.ImageAliasesEntryPost) error {
// Send the request
_, _, err := r.query("POST", fmt.Sprintf("/images/aliases/%s", url.QueryEscape(name)), alias, "")
if err != nil {
return err
}
return nil
}
// DeleteImageAlias removes an alias from the LXD image store
func (r *ProtocolLXD) DeleteImageAlias(name string) error {
// Send the request
_, _, err := r.query("DELETE", fmt.Sprintf("/images/aliases/%s", url.QueryEscape(name)), nil, "")
if err != nil {
return err
}
return nil
}