forked from canonical/lxd
/
images.go
1631 lines (1343 loc) · 40.3 KB
/
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
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"crypto/sha256"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"mime"
"mime/multipart"
"net/http"
"net/url"
"os"
"os/exec"
"strconv"
"strings"
"sync"
"syscall"
"time"
"github.com/gorilla/mux"
"gopkg.in/yaml.v2"
"github.com/lxc/lxd/shared"
"github.com/lxc/lxd/shared/api"
"github.com/lxc/lxd/shared/logger"
"github.com/lxc/lxd/shared/logging"
"github.com/lxc/lxd/shared/osarch"
"github.com/lxc/lxd/shared/version"
log "gopkg.in/inconshreveable/log15.v2"
)
/* We only want a single publish running at any one time.
The CPU and I/O load of publish is such that running multiple ones in
parallel takes longer than running them serially.
Additionally, publishing the same container or container snapshot
twice would lead to storage problem, not to mention a conflict at the
end for whichever finishes last. */
var imagePublishLock sync.Mutex
func detectCompression(fname string) ([]string, string, error) {
f, err := os.Open(fname)
if err != nil {
return []string{""}, "", err
}
defer f.Close()
// read header parts to detect compression method
// bz2 - 2 bytes, 'BZ' signature/magic number
// gz - 2 bytes, 0x1f 0x8b
// lzma - 6 bytes, { [0x000, 0xE0], '7', 'z', 'X', 'Z', 0x00 } -
// xy - 6 bytes, header format { 0xFD, '7', 'z', 'X', 'Z', 0x00 }
// tar - 263 bytes, trying to get ustar from 257 - 262
header := make([]byte, 263)
_, err = f.Read(header)
if err != nil {
return []string{""}, "", err
}
switch {
case bytes.Equal(header[0:2], []byte{'B', 'Z'}):
return []string{"-jxf"}, ".tar.bz2", nil
case bytes.Equal(header[0:2], []byte{0x1f, 0x8b}):
return []string{"-zxf"}, ".tar.gz", nil
case (bytes.Equal(header[1:5], []byte{'7', 'z', 'X', 'Z'}) && header[0] == 0xFD):
return []string{"-Jxf"}, ".tar.xz", nil
case (bytes.Equal(header[1:5], []byte{'7', 'z', 'X', 'Z'}) && header[0] != 0xFD):
return []string{"--lzma", "-xf"}, ".tar.lzma", nil
case bytes.Equal(header[0:3], []byte{0x5d, 0x00, 0x00}):
return []string{"--lzma", "-xf"}, ".tar.lzma", nil
case bytes.Equal(header[257:262], []byte{'u', 's', 't', 'a', 'r'}):
return []string{"-xf"}, ".tar", nil
case bytes.Equal(header[0:4], []byte{'h', 's', 'q', 's'}):
return []string{""}, ".squashfs", nil
default:
return []string{""}, "", fmt.Errorf("Unsupported compression")
}
}
func unpack(d *Daemon, file string, path string, sType storageType) error {
extractArgs, extension, err := detectCompression(file)
if err != nil {
return err
}
command := ""
args := []string{}
if strings.HasPrefix(extension, ".tar") {
command = "tar"
if runningInUserns {
args = append(args, "--wildcards")
args = append(args, "--exclude=dev/*")
args = append(args, "--exclude=./dev/*")
args = append(args, "--exclude=rootfs/dev/*")
args = append(args, "--exclude=rootfs/./dev/*")
}
args = append(args, "-C", path, "--numeric-owner")
args = append(args, extractArgs...)
args = append(args, file)
} else if strings.HasPrefix(extension, ".squashfs") {
command = "unsquashfs"
args = append(args, "-f", "-d", path, "-n")
// Limit unsquashfs chunk size to 10% of memory and up to 256MB (default)
// When running on a low memory system, also disable multi-processing
mem, err := deviceTotalMemory()
mem = mem / 1024 / 1024 / 10
if err == nil && mem < 256 {
args = append(args, "-da", fmt.Sprintf("%d", mem), "-fr", fmt.Sprintf("%d", mem), "-p", "1")
}
args = append(args, file)
} else {
return fmt.Errorf("Unsupported image format: %s", extension)
}
output, err := shared.RunCommand(command, args...)
if err != nil {
// Check if we ran out of space
fs := syscall.Statfs_t{}
err1 := syscall.Statfs(path, &fs)
if err1 != nil {
return err1
}
// Check if we're running out of space
if int64(fs.Bfree) < int64(2*fs.Bsize) {
if sType == storageTypeLvm {
return fmt.Errorf("Unable to unpack image, run out of disk space (consider increasing your pool's volume.size).")
} else {
return fmt.Errorf("Unable to unpack image, run out of disk space.")
}
}
co := output
logger.Debugf("Unpacking failed")
logger.Debugf(co)
// Truncate the output to a single line for inclusion in the error
// message. The first line isn't guaranteed to pinpoint the issue,
// but it's better than nothing and better than a multi-line message.
return fmt.Errorf("Unpack failed, %s. %s", err, strings.SplitN(co, "\n", 2)[0])
}
return nil
}
func unpackImage(d *Daemon, imagefname string, destpath string, sType storageType) error {
err := unpack(d, imagefname, destpath, sType)
if err != nil {
return err
}
rootfsPath := fmt.Sprintf("%s/rootfs", destpath)
if shared.PathExists(imagefname + ".rootfs") {
err = os.MkdirAll(rootfsPath, 0755)
if err != nil {
return fmt.Errorf("Error creating rootfs directory")
}
err = unpack(d, imagefname+".rootfs", rootfsPath, sType)
if err != nil {
return err
}
}
if !shared.PathExists(rootfsPath) {
return fmt.Errorf("Image is missing a rootfs: %s", imagefname)
}
return nil
}
func compressFile(path string, compress string) (string, error) {
reproducible := []string{"gzip"}
args := []string{path, "-c"}
if shared.StringInSlice(compress, reproducible) {
args = append(args, "-n")
}
cmd := exec.Command(compress, args...)
outfile, err := os.Create(path + ".compressed")
if err != nil {
return "", err
}
defer outfile.Close()
cmd.Stdout = outfile
err = cmd.Run()
if err != nil {
os.Remove(outfile.Name())
return "", err
}
return outfile.Name(), nil
}
type templateEntry struct {
When []string `yaml:"when"`
CreateOnly bool `yaml:"create_only"`
Template string `yaml:"template"`
Properties map[string]string `yaml:"properties"`
}
type imageMetadata struct {
Architecture string `yaml:"architecture"`
CreationDate int64 `yaml:"creation_date"`
ExpiryDate int64 `yaml:"expiry_date"`
Properties map[string]string `yaml:"properties"`
Templates map[string]*templateEntry `yaml:"templates"`
}
/*
* This function takes a container or snapshot from the local image server and
* exports it as an image.
*/
func imgPostContInfo(d *Daemon, r *http.Request, req api.ImagesPost, builddir string) (*api.Image, error) {
info := api.Image{}
info.Properties = map[string]string{}
name := req.Source.Name
ctype := req.Source.Type
if ctype == "" || name == "" {
return nil, fmt.Errorf("No source provided")
}
switch ctype {
case "snapshot":
if !shared.IsSnapshot(name) {
return nil, fmt.Errorf("Not a snapshot")
}
case "container":
if shared.IsSnapshot(name) {
return nil, fmt.Errorf("This is a snapshot")
}
default:
return nil, fmt.Errorf("Bad type")
}
info.Filename = req.Filename
switch req.Public {
case true:
info.Public = true
case false:
info.Public = false
}
c, err := containerLoadByName(d, name)
if err != nil {
return nil, err
}
// Build the actual image file
tarfile, err := ioutil.TempFile(builddir, "lxd_build_tar_")
if err != nil {
return nil, err
}
defer os.Remove(tarfile.Name())
if err := c.Export(tarfile, req.Properties); err != nil {
tarfile.Close()
return nil, err
}
tarfile.Close()
var compressedPath string
var compress string
if req.CompressionAlgorithm != "" {
compress = req.CompressionAlgorithm
} else {
compress = daemonConfig["images.compression_algorithm"].Get()
}
if compress != "none" {
compressedPath, err = compressFile(tarfile.Name(), compress)
if err != nil {
return nil, err
}
} else {
compressedPath = tarfile.Name()
}
defer os.Remove(compressedPath)
sha256 := sha256.New()
tarf, err := os.Open(compressedPath)
if err != nil {
return nil, err
}
info.Size, err = io.Copy(sha256, tarf)
tarf.Close()
if err != nil {
return nil, err
}
info.Fingerprint = fmt.Sprintf("%x", sha256.Sum(nil))
_, _, err = dbImageGet(d.db, info.Fingerprint, false, true)
if err == nil {
return nil, fmt.Errorf("The image already exists: %s", info.Fingerprint)
}
/* rename the the file to the expected name so our caller can use it */
finalName := shared.VarPath("images", info.Fingerprint)
err = shared.FileMove(compressedPath, finalName)
if err != nil {
return nil, err
}
info.Architecture, _ = osarch.ArchitectureName(c.Architecture())
info.Properties = req.Properties
// Create the database entry
err = dbImageInsert(d.db, info.Fingerprint, info.Filename, info.Size, info.Public, info.AutoUpdate, info.Architecture, info.CreatedAt, info.ExpiresAt, info.Properties)
if err != nil {
return nil, err
}
return &info, nil
}
func imgPostRemoteInfo(d *Daemon, req api.ImagesPost, op *operation) (*api.Image, error) {
var err error
var hash string
if req.Source.Fingerprint != "" {
hash = req.Source.Fingerprint
} else if req.Source.Alias != "" {
hash = req.Source.Alias
} else {
return nil, fmt.Errorf("must specify one of alias or fingerprint for init from image")
}
info, err := d.ImageDownload(op, req.Source.Server, req.Source.Protocol, req.Source.Certificate, req.Source.Secret, hash, false, req.AutoUpdate, "", false)
if err != nil {
return nil, err
}
id, info, err := dbImageGet(d.db, info.Fingerprint, false, true)
if err != nil {
return nil, err
}
// Allow overriding or adding properties
for k, v := range req.Properties {
info.Properties[k] = v
}
// Update the DB record if needed
if req.Public || req.AutoUpdate || req.Filename != "" || len(req.Properties) > 0 {
err = dbImageUpdate(d.db, id, req.Filename, info.Size, req.Public, req.AutoUpdate, info.Architecture, info.CreatedAt, info.ExpiresAt, info.Properties)
if err != nil {
return nil, err
}
}
return info, nil
}
func imgPostURLInfo(d *Daemon, req api.ImagesPost, op *operation) (*api.Image, error) {
var err error
if req.Source.URL == "" {
return nil, fmt.Errorf("Missing URL")
}
myhttp, err := d.httpClient("")
if err != nil {
return nil, err
}
// Resolve the image URL
head, err := http.NewRequest("HEAD", req.Source.URL, nil)
if err != nil {
return nil, err
}
architecturesStr := []string{}
for _, arch := range d.architectures {
architecturesStr = append(architecturesStr, fmt.Sprintf("%d", arch))
}
head.Header.Set("User-Agent", version.UserAgent)
head.Header.Set("LXD-Server-Architectures", strings.Join(architecturesStr, ", "))
head.Header.Set("LXD-Server-Version", version.Version)
raw, err := myhttp.Do(head)
if err != nil {
return nil, err
}
hash := raw.Header.Get("LXD-Image-Hash")
if hash == "" {
return nil, fmt.Errorf("Missing LXD-Image-Hash header")
}
url := raw.Header.Get("LXD-Image-URL")
if url == "" {
return nil, fmt.Errorf("Missing LXD-Image-URL header")
}
// Import the image
info, err := d.ImageDownload(op, url, "direct", "", "", hash, false, req.AutoUpdate, "", false)
if err != nil {
return nil, err
}
id, info, err := dbImageGet(d.db, info.Fingerprint, false, false)
if err != nil {
return nil, err
}
// Allow overriding or adding properties
for k, v := range req.Properties {
info.Properties[k] = v
}
if req.Public || req.AutoUpdate || req.Filename != "" || len(req.Properties) > 0 {
err = dbImageUpdate(d.db, id, req.Filename, info.Size, req.Public, req.AutoUpdate, info.Architecture, info.CreatedAt, info.ExpiresAt, info.Properties)
if err != nil {
return nil, err
}
}
return info, nil
}
func getImgPostInfo(d *Daemon, r *http.Request, builddir string, post *os.File) (*api.Image, error) {
info := api.Image{}
var imageMeta *imageMetadata
logger := logging.AddContext(logger.Log, log.Ctx{"function": "getImgPostInfo"})
public, _ := strconv.Atoi(r.Header.Get("X-LXD-public"))
info.Public = public == 1
propHeaders := r.Header[http.CanonicalHeaderKey("X-LXD-properties")]
ctype, ctypeParams, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil {
ctype = "application/octet-stream"
}
sha256 := sha256.New()
var size int64
if ctype == "multipart/form-data" {
// Create a temporary file for the image tarball
imageTarf, err := ioutil.TempFile(builddir, "lxd_tar_")
if err != nil {
return nil, err
}
defer os.Remove(imageTarf.Name())
// Parse the POST data
post.Seek(0, 0)
mr := multipart.NewReader(post, 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(imageTarf, sha256), part)
info.Size += size
imageTarf.Close()
if err != nil {
logger.Error(
"Failed to copy the image tarfile",
log.Ctx{"err": err})
return nil, err
}
// Get the rootfs tarball
part, err = mr.NextPart()
if err != nil {
logger.Error(
"Failed to get the next part",
log.Ctx{"err": err})
return nil, err
}
if part.FormName() != "rootfs" {
logger.Error(
"Invalid multipart image")
return nil, fmt.Errorf("Invalid multipart image")
}
// Create a temporary file for the rootfs tarball
rootfsTarf, err := ioutil.TempFile(builddir, "lxd_tar_")
if err != nil {
return nil, err
}
defer os.Remove(rootfsTarf.Name())
size, err = io.Copy(io.MultiWriter(rootfsTarf, sha256), part)
info.Size += size
rootfsTarf.Close()
if err != nil {
logger.Error(
"Failed to copy the rootfs tarfile",
log.Ctx{"err": err})
return nil, err
}
info.Filename = part.FileName()
info.Fingerprint = fmt.Sprintf("%x", sha256.Sum(nil))
expectedFingerprint := r.Header.Get("X-LXD-fingerprint")
if expectedFingerprint != "" && info.Fingerprint != expectedFingerprint {
err = fmt.Errorf("fingerprints don't match, got %s expected %s", info.Fingerprint, expectedFingerprint)
return nil, err
}
imageMeta, err = getImageMetadata(imageTarf.Name())
if err != nil {
logger.Error(
"Failed to get image metadata",
log.Ctx{"err": err})
return nil, err
}
imgfname := shared.VarPath("images", info.Fingerprint)
err = shared.FileMove(imageTarf.Name(), imgfname)
if err != nil {
logger.Error(
"Failed to move the image tarfile",
log.Ctx{
"err": err,
"source": imageTarf.Name(),
"dest": imgfname})
return nil, err
}
rootfsfname := shared.VarPath("images", info.Fingerprint+".rootfs")
err = shared.FileMove(rootfsTarf.Name(), rootfsfname)
if err != nil {
logger.Error(
"Failed to move the rootfs tarfile",
log.Ctx{
"err": err,
"source": rootfsTarf.Name(),
"dest": imgfname})
return nil, err
}
} else {
post.Seek(0, 0)
size, err = io.Copy(sha256, post)
info.Size = size
logger.Debug("Tar size", log.Ctx{"size": size})
if err != nil {
logger.Error(
"Failed to copy the tarfile",
log.Ctx{"err": err})
return nil, err
}
info.Filename = r.Header.Get("X-LXD-filename")
info.Fingerprint = fmt.Sprintf("%x", sha256.Sum(nil))
expectedFingerprint := r.Header.Get("X-LXD-fingerprint")
if expectedFingerprint != "" && info.Fingerprint != expectedFingerprint {
logger.Error(
"Fingerprints don't match",
log.Ctx{
"got": info.Fingerprint,
"expected": expectedFingerprint})
err = fmt.Errorf(
"fingerprints don't match, got %s expected %s",
info.Fingerprint,
expectedFingerprint)
return nil, err
}
imageMeta, err = getImageMetadata(post.Name())
if err != nil {
logger.Error(
"Failed to get image metadata",
log.Ctx{"err": err})
return nil, err
}
imgfname := shared.VarPath("images", info.Fingerprint)
err = shared.FileMove(post.Name(), imgfname)
if err != nil {
logger.Error(
"Failed to move the tarfile",
log.Ctx{
"err": err,
"source": post.Name(),
"dest": imgfname})
return nil, err
}
}
info.Architecture = imageMeta.Architecture
info.CreatedAt = time.Unix(imageMeta.CreationDate, 0)
info.ExpiresAt = time.Unix(imageMeta.ExpiryDate, 0)
info.Properties = imageMeta.Properties
if len(propHeaders) > 0 {
for _, ph := range propHeaders {
p, _ := url.ParseQuery(ph)
for pkey, pval := range p {
info.Properties[pkey] = pval[0]
}
}
}
// Check if the image already exists
exists, err := dbImageExists(d.db, info.Fingerprint)
if err != nil {
return nil, err
}
if exists {
return nil, fmt.Errorf("Image with same fingerprint already exists")
}
// Create the database entry
err = dbImageInsert(d.db, info.Fingerprint, info.Filename, info.Size, info.Public, info.AutoUpdate, info.Architecture, info.CreatedAt, info.ExpiresAt, info.Properties)
if err != nil {
return nil, err
}
return &info, nil
}
// imageCreateInPool() creates a new storage volume in a given storage pool for
// the image. No entry in the images database will be created. This implies that
// imageCreateinPool() should only be called when an image already exists in the
// database and hence has already a storage volume in at least one storage pool.
func imageCreateInPool(d *Daemon, info *api.Image, storagePool string) error {
if storagePool == "" {
return fmt.Errorf("No storage pool specified.")
}
// Initialize a new storage interface.
s, err := storagePoolInit(d, storagePool)
if err != nil {
return err
}
// Create the storage volume for the image on the requested storage
// pool.
err = s.ImageCreate(info.Fingerprint)
if err != nil {
return err
}
return nil
}
func imagesPost(d *Daemon, r *http.Request) Response {
var err error
// create a directory under which we keep everything while building
builddir, err := ioutil.TempDir(shared.VarPath("images"), "lxd_build_")
if err != nil {
return InternalError(err)
}
cleanup := func(path string, fd *os.File) {
if fd != nil {
fd.Close()
}
if err := os.RemoveAll(path); err != nil {
logger.Debugf("Error deleting temporary directory \"%s\": %s", path, err)
}
}
// Store the post data to disk
post, err := ioutil.TempFile(builddir, "lxd_post_")
if err != nil {
cleanup(builddir, nil)
return InternalError(err)
}
_, err = io.Copy(post, r.Body)
if err != nil {
cleanup(builddir, post)
return InternalError(err)
}
// Is this a container request?
post.Seek(0, 0)
decoder := json.NewDecoder(post)
imageUpload := false
req := api.ImagesPost{}
err = decoder.Decode(&req)
if err != nil {
if r.Header.Get("Content-Type") == "application/json" {
return BadRequest(err)
}
imageUpload = true
}
if !imageUpload && !shared.StringInSlice(req.Source.Type, []string{"container", "snapshot", "image", "url"}) {
cleanup(builddir, post)
return InternalError(fmt.Errorf("Invalid images JSON"))
}
// Begin background operation
run := func(op *operation) error {
var info *api.Image
// Setup the cleanup function
defer cleanup(builddir, post)
if !imageUpload {
if req.Source.Type == "image" {
/* Processing image copy from remote */
info, err = imgPostRemoteInfo(d, req, op)
if err != nil {
return err
}
} else if req.Source.Type == "url" {
/* Processing image copy from URL */
info, err = imgPostURLInfo(d, req, op)
if err != nil {
return err
}
} else {
/* Processing image creation from container */
imagePublishLock.Lock()
info, err = imgPostContInfo(d, r, req, builddir)
if err != nil {
imagePublishLock.Unlock()
return err
}
imagePublishLock.Unlock()
}
} else {
/* Processing image upload */
info, err = getImgPostInfo(d, r, builddir, post)
if err != nil {
return err
}
}
// Apply any provided alias
for _, alias := range req.Aliases {
_, _, err := dbImageAliasGet(d.db, alias.Name, true)
if err == nil {
return fmt.Errorf("Alias already exists: %s", alias.Name)
}
id, _, err := dbImageGet(d.db, info.Fingerprint, false, false)
if err != nil {
return err
}
err = dbImageAliasAdd(d.db, alias.Name, id, alias.Description)
if err != nil {
return err
}
}
// Set the metadata
metadata := make(map[string]string)
metadata["fingerprint"] = info.Fingerprint
metadata["size"] = strconv.FormatInt(info.Size, 10)
op.UpdateMetadata(metadata)
return nil
}
op, err := operationCreate(operationClassTask, nil, nil, run, nil, nil)
if err != nil {
return InternalError(err)
}
return OperationResponse(op)
}
func getImageMetadata(fname string) (*imageMetadata, error) {
metadataName := "metadata.yaml"
compressionArgs, _, err := detectCompression(fname)
if err != nil {
return nil, fmt.Errorf(
"detectCompression failed, err='%v', tarfile='%s'",
err,
fname)
}
args := []string{"-O"}
args = append(args, compressionArgs...)
args = append(args, fname, metadataName)
// read the metadata.yaml
output, err := shared.RunCommand("tar", args...)
if err != nil {
outputLines := strings.Split(output, "\n")
return nil, fmt.Errorf("Could not extract image %s from tar: %v (%s)", metadataName, err, outputLines[0])
}
metadata := imageMetadata{}
err = yaml.Unmarshal([]byte(output), &metadata)
if err != nil {
return nil, fmt.Errorf("Could not parse %s: %v", metadataName, err)
}
_, err = osarch.ArchitectureId(metadata.Architecture)
if err != nil {
return nil, err
}
if metadata.CreationDate == 0 {
return nil, fmt.Errorf("Missing creation date.")
}
return &metadata, nil
}
func doImagesGet(d *Daemon, recursion bool, public bool) (interface{}, error) {
results, err := dbImagesGet(d.db, public)
if err != nil {
return []string{}, err
}
resultString := make([]string, len(results))
resultMap := make([]*api.Image, len(results))
i := 0
for _, name := range results {
if !recursion {
url := fmt.Sprintf("/%s/images/%s", version.APIVersion, name)
resultString[i] = url
} else {
image, response := doImageGet(d, name, public)
if response != nil {
continue
}
resultMap[i] = image
}
i++
}
if !recursion {
return resultString, nil
}
return resultMap, nil
}
func imagesGet(d *Daemon, r *http.Request) Response {
public := !d.isTrustedClient(r)
result, err := doImagesGet(d, d.isRecursionRequest(r), public)
if err != nil {
return SmartError(err)
}
return SyncResponse(true, result)
}
var imagesCmd = Command{name: "images", post: imagesPost, untrustedGet: true, get: imagesGet}
func autoUpdateImages(d *Daemon) {
logger.Infof("Updating images")
images, err := dbImagesGet(d.db, false)
if err != nil {
logger.Error("Unable to retrieve the list of images", log.Ctx{"err": err})
return
}
for _, fingerprint := range images {
id, info, err := dbImageGet(d.db, fingerprint, false, true)
if err != nil {
logger.Error("Error loading image", log.Ctx{"err": err, "fp": fingerprint})
continue
}
if !info.AutoUpdate {
continue
}
autoUpdateImage(d, nil, fingerprint, id, info)
}
logger.Infof("Done updating images")
}
// Update a single image. The operation can be nil, if no progress tracking is needed.
// Returns whether the image has been updated.
func autoUpdateImage(d *Daemon, op *operation, fingerprint string, id int, info *api.Image) error {
_, source, err := dbImageSourceGet(d.db, id)
if err != nil {
logger.Error("Error getting source image", log.Ctx{"err": err, "fp": fingerprint})
return err
}
// Get the IDs of all storage pools on which a storage volume
// for the requested image currently exists.
poolIDs, err := dbImageGetPools(d.db, fingerprint)
if err != nil {
logger.Error("Error getting image pools", log.Ctx{"err": err, "fp": fingerprint})
return err
}
// Translate the IDs to poolNames.
poolNames, err := dbImageGetPoolNamesFromIDs(d.db, poolIDs)
if err != nil {
logger.Error("Error getting image pools", log.Ctx{"err": err, "fp": fingerprint})
return err
}
// If no optimized pools at least update the base store
if len(poolNames) == 0 {
poolNames = append(poolNames, "")
}
logger.Debug("Processing image", log.Ctx{"fp": fingerprint, "server": source.Server, "protocol": source.Protocol, "alias": source.Alias})
// Set operation metadata to indicate whether a refresh happened
setRefreshResult := func(result bool) {
if op == nil {
return
}
metadata := map[string]interface{}{"refreshed": result}
op.UpdateMetadata(metadata)
}
// Update the image on each pool where it currently exists.
hash := fingerprint
for _, poolName := range poolNames {
newInfo, err := d.ImageDownload(op, source.Server, source.Protocol, source.Certificate, "", source.Alias, false, true, poolName, false)
if err != nil {
logger.Error("Failed to update the image", log.Ctx{"err": err, "fp": fingerprint})
continue
}
hash = newInfo.Fingerprint
if hash == fingerprint {
logger.Debug("Already up to date", log.Ctx{"fp": fingerprint})
continue
}
newId, _, err := dbImageGet(d.db, hash, false, true)
if err != nil {
logger.Error("Error loading image", log.Ctx{"err": err, "fp": hash})
continue
}
err = dbImageLastAccessUpdate(d.db, hash, info.LastUsedAt)
if err != nil {
logger.Error("Error setting last use date", log.Ctx{"err": err, "fp": hash})
continue
}
err = dbImageAliasesMove(d.db, id, newId)
if err != nil {
logger.Error("Error moving aliases", log.Ctx{"err": err, "fp": hash})
continue
}
// If we do have optimized pools, make sure we remove
// the volumes associated with the image.
if poolName != "" {
err = doDeleteImageFromPool(d, fingerprint, poolName)
if err != nil {
logger.Error("Error deleting image from pool", log.Ctx{"err": err, "fp": fingerprint})
}
}
}
// Image didn't change, nothing to do.
if hash == fingerprint {
setRefreshResult(false)
return nil
}
// Remove main image file.
fname := shared.VarPath("images", fingerprint)
if shared.PathExists(fname) {
err = os.Remove(fname)
if err != nil {
logger.Debugf("Error deleting image file %s: %s", fname, err)
}
}
// Remove the rootfs file for the image.