-
-
Notifications
You must be signed in to change notification settings - Fork 225
/
images.go
4712 lines (3988 loc) · 126 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 (
"archive/tar"
"bytes"
"context"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"io"
"math"
"math/rand"
"mime"
"mime/multipart"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"slices"
"strconv"
"strings"
"sync"
"time"
"github.com/gorilla/mux"
"github.com/kballard/go-shellquote"
"gopkg.in/yaml.v2"
"github.com/lxc/incus/client"
"github.com/lxc/incus/internal/filter"
internalInstance "github.com/lxc/incus/internal/instance"
internalIO "github.com/lxc/incus/internal/io"
"github.com/lxc/incus/internal/jmap"
"github.com/lxc/incus/internal/server/auth"
"github.com/lxc/incus/internal/server/cluster"
"github.com/lxc/incus/internal/server/db"
dbCluster "github.com/lxc/incus/internal/server/db/cluster"
"github.com/lxc/incus/internal/server/db/operationtype"
"github.com/lxc/incus/internal/server/instance"
"github.com/lxc/incus/internal/server/instance/instancetype"
"github.com/lxc/incus/internal/server/lifecycle"
"github.com/lxc/incus/internal/server/node"
"github.com/lxc/incus/internal/server/operations"
projectutils "github.com/lxc/incus/internal/server/project"
"github.com/lxc/incus/internal/server/request"
"github.com/lxc/incus/internal/server/response"
"github.com/lxc/incus/internal/server/state"
storagePools "github.com/lxc/incus/internal/server/storage"
"github.com/lxc/incus/internal/server/task"
localUtil "github.com/lxc/incus/internal/server/util"
internalUtil "github.com/lxc/incus/internal/util"
"github.com/lxc/incus/internal/version"
"github.com/lxc/incus/shared/api"
"github.com/lxc/incus/shared/archive"
"github.com/lxc/incus/shared/ioprogress"
"github.com/lxc/incus/shared/logger"
"github.com/lxc/incus/shared/osarch"
"github.com/lxc/incus/shared/util"
)
var imagesCmd = APIEndpoint{
Path: "images",
Get: APIEndpointAction{Handler: imagesGet, AllowUntrusted: true},
Post: APIEndpointAction{Handler: imagesPost, AllowUntrusted: true},
}
var imageCmd = APIEndpoint{
Path: "images/{fingerprint}",
Delete: APIEndpointAction{Handler: imageDelete, AccessHandler: allowPermission(auth.ObjectTypeImage, auth.EntitlementCanEdit, "fingerprint")},
Get: APIEndpointAction{Handler: imageGet, AllowUntrusted: true},
Patch: APIEndpointAction{Handler: imagePatch, AccessHandler: allowPermission(auth.ObjectTypeImage, auth.EntitlementCanEdit, "fingerprint")},
Put: APIEndpointAction{Handler: imagePut, AccessHandler: allowPermission(auth.ObjectTypeImage, auth.EntitlementCanEdit, "fingerprint")},
}
var imageExportCmd = APIEndpoint{
Path: "images/{fingerprint}/export",
Get: APIEndpointAction{Handler: imageExport, AllowUntrusted: true},
Post: APIEndpointAction{Handler: imageExportPost, AccessHandler: allowPermission(auth.ObjectTypeImage, auth.EntitlementCanEdit, "fingerprint")},
}
var imageSecretCmd = APIEndpoint{
Path: "images/{fingerprint}/secret",
Post: APIEndpointAction{Handler: imageSecret, AccessHandler: allowPermission(auth.ObjectTypeImage, auth.EntitlementCanEdit, "fingerprint")},
}
var imageRefreshCmd = APIEndpoint{
Path: "images/{fingerprint}/refresh",
Post: APIEndpointAction{Handler: imageRefresh, AccessHandler: allowPermission(auth.ObjectTypeImage, auth.EntitlementCanEdit, "fingerprint")},
}
var imageAliasesCmd = APIEndpoint{
Path: "images/aliases",
Get: APIEndpointAction{Handler: imageAliasesGet, AccessHandler: allowAuthenticated},
Post: APIEndpointAction{Handler: imageAliasesPost, AccessHandler: allowPermission(auth.ObjectTypeProject, auth.EntitlementCanCreateImageAliases)},
}
var imageAliasCmd = APIEndpoint{
Path: "images/aliases/{name:.*}",
Delete: APIEndpointAction{Handler: imageAliasDelete, AccessHandler: allowPermission(auth.ObjectTypeImageAlias, auth.EntitlementCanEdit, "name")},
Get: APIEndpointAction{Handler: imageAliasGet, AllowUntrusted: true},
Patch: APIEndpointAction{Handler: imageAliasPatch, AccessHandler: allowPermission(auth.ObjectTypeImageAlias, auth.EntitlementCanEdit, "name")},
Post: APIEndpointAction{Handler: imageAliasPost, AccessHandler: allowPermission(auth.ObjectTypeImageAlias, auth.EntitlementCanEdit, "name")},
Put: APIEndpointAction{Handler: imageAliasPut, AccessHandler: allowPermission(auth.ObjectTypeImageAlias, auth.EntitlementCanEdit, "name")},
}
/*
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
// imageTaskMu prevents image related tasks from being scheduled at the same time as each other to prevent them
// stepping on each other's toes.
var imageTaskMu sync.Mutex
func compressFile(compress string, infile io.Reader, outfile io.Writer) error {
reproducible := []string{"gzip"}
var cmd *exec.Cmd
// Parse the command.
fields, err := shellquote.Split(compress)
if err != nil {
return err
}
if fields[0] == "squashfs" {
// 'tar2sqfs' do not support writing to stdout. So write to a temporary
// file first and then replay the compressed content to outfile.
tempfile, err := os.CreateTemp("", "incus_compress_")
if err != nil {
return err
}
defer func() { _ = tempfile.Close() }()
defer func() { _ = os.Remove(tempfile.Name()) }()
// Prepare 'tar2sqfs' arguments
args := []string{"tar2sqfs"}
if len(fields) > 1 {
args = append(args, fields[1:]...)
}
args = append(args, "--no-skip", "--force", "--compressor", "xz", tempfile.Name())
cmd = exec.Command(args[0], args[1:]...)
cmd.Stdin = infile
output, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("tar2sqfs: %v (%v)", err, strings.TrimSpace(string(output)))
}
// Replay the result to outfile
_, err = tempfile.Seek(0, io.SeekStart)
if err != nil {
return err
}
_, err = io.Copy(outfile, tempfile)
if err != nil {
return err
}
} else {
args := []string{"-c"}
if len(fields) > 1 {
args = append(args, fields[1:]...)
}
if slices.Contains(reproducible, fields[0]) {
args = append(args, "-n")
}
cmd := exec.Command(fields[0], args...)
cmd.Stdin = infile
cmd.Stdout = outfile
err := cmd.Run()
if err != nil {
return err
}
}
return nil
}
/*
* This function takes a container or snapshot from the local image server and
* exports it as an image.
*/
func imgPostInstanceInfo(ctx context.Context, s *state.State, r *http.Request, req api.ImagesPost, op *operations.Operation, builddir string, budget int64) (*api.Image, error) {
info := api.Image{}
info.Properties = map[string]string{}
projectName := request.ProjectParam(r)
name := req.Source.Name
ctype := req.Source.Type
if ctype == "" || name == "" {
return nil, fmt.Errorf("No source provided")
}
switch ctype {
case "snapshot":
if !internalInstance.IsSnapshot(name) {
return nil, fmt.Errorf("Not a snapshot")
}
case "container", "virtual-machine", "instance":
if internalInstance.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 := instance.LoadByProjectAndName(s, projectName, name)
if err != nil {
return nil, err
}
info.Type = c.Type().String()
// Build the actual image file
imageFile, err := os.CreateTemp(builddir, "incus_build_image_")
if err != nil {
return nil, err
}
defer func() { _ = os.Remove(imageFile.Name()) }()
// Calculate (close estimate of) total size of input to image
totalSize := int64(0)
sumSize := func(path string, fi os.FileInfo, err error) error {
if err == nil {
totalSize += fi.Size()
}
return nil
}
err = filepath.Walk(c.RootfsPath(), sumSize)
if err != nil {
return nil, err
}
// Track progress creating image.
metadata := make(map[string]any)
imageProgressWriter := &ioprogress.ProgressWriter{
Tracker: &ioprogress.ProgressTracker{
Handler: func(value, speed int64) {
percent := int64(0)
var processed int64
if totalSize > 0 {
percent = value
processed = totalSize * (percent / 100.0)
} else {
processed = value
}
operations.SetProgressMetadata(metadata, "create_image_from_container_pack", "Image pack", percent, processed, speed)
_ = op.UpdateMetadata(metadata)
},
Length: totalSize,
},
}
sha256 := sha256.New()
var compress string
var writer io.Writer
if req.CompressionAlgorithm != "" {
compress = req.CompressionAlgorithm
} else {
var p *api.Project
err = s.DB.Cluster.Transaction(ctx, func(ctx context.Context, tx *db.ClusterTx) error {
project, err := dbCluster.GetProject(ctx, tx.Tx(), projectName)
if err != nil {
return err
}
p, err = project.ToAPI(ctx, tx.Tx())
return err
})
if err != nil {
return nil, err
}
if p.Config["images.compression_algorithm"] != "" {
compress = p.Config["images.compression_algorithm"]
} else {
compress = s.GlobalConfig.ImagesCompressionAlgorithm()
}
}
// Setup tar, optional compress and sha256 to happen in one pass.
wg := sync.WaitGroup{}
var compressErr error
if compress != "none" {
wg.Add(1)
tarReader, tarWriter := io.Pipe()
imageProgressWriter.WriteCloser = tarWriter
writer = imageProgressWriter
compressWriter := io.MultiWriter(imageFile, sha256)
go func() {
defer wg.Done()
compressErr = compressFile(compress, tarReader, compressWriter)
// If a compression error occurred, close the writer to end the instance export.
if compressErr != nil {
_ = imageProgressWriter.Close()
}
}()
} else {
imageProgressWriter.WriteCloser = imageFile
writer = io.MultiWriter(imageProgressWriter, sha256)
}
// Export instance to writer.
var meta api.ImageMetadata
writer = internalIO.NewQuotaWriter(writer, budget)
meta, err = c.Export(writer, req.Properties, req.ExpiresAt)
// Get ExpiresAt
if meta.ExpiryDate != 0 {
info.ExpiresAt = time.Unix(meta.ExpiryDate, 0)
}
// Clean up file handles.
// When compression is used, Close on imageProgressWriter/tarWriter is required for compressFile/gzip to
// know it is finished. Otherwise it is equivalent to imageFile.Close.
_ = imageProgressWriter.Close()
wg.Wait() // Wait until compression helper has finished if used.
_ = imageFile.Close()
// Check compression errors.
if compressErr != nil {
return nil, compressErr
}
// Check instance export errors.
if err != nil {
return nil, err
}
fi, err := os.Stat(imageFile.Name())
if err != nil {
return nil, err
}
info.Size = fi.Size()
info.Fingerprint = fmt.Sprintf("%x", sha256.Sum(nil))
info.CreatedAt = time.Now().UTC()
err = s.DB.Cluster.Transaction(ctx, func(ctx context.Context, tx *db.ClusterTx) error {
_, _, err = tx.GetImage(ctx, info.Fingerprint, dbCluster.ImageFilter{Project: &projectName})
return err
})
if !response.IsNotFoundError(err) {
if err != nil {
return nil, err
}
return &info, fmt.Errorf("The image already exists: %s", info.Fingerprint)
}
/* rename the file to the expected name so our caller can use it */
finalName := internalUtil.VarPath("images", info.Fingerprint)
err = internalUtil.FileMove(imageFile.Name(), finalName)
if err != nil {
return nil, err
}
info.Architecture, _ = osarch.ArchitectureName(c.Architecture())
info.Properties = meta.Properties
err = s.DB.Cluster.Transaction(ctx, func(ctx context.Context, tx *db.ClusterTx) error {
// Create the database entry
return tx.CreateImage(ctx, c.Project().Name, info.Fingerprint, info.Filename, info.Size, info.Public, info.AutoUpdate, info.Architecture, info.CreatedAt, info.ExpiresAt, info.Properties, info.Type, nil)
})
if err != nil {
return nil, err
}
return &info, nil
}
func imgPostRemoteInfo(ctx context.Context, s *state.State, r *http.Request, req api.ImagesPost, op *operations.Operation, project string, budget int64) (*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 := ImageDownload(ctx, r, s, op, &ImageDownloadArgs{
Server: req.Source.Server,
Protocol: req.Source.Protocol,
Certificate: req.Source.Certificate,
Secret: req.Source.Secret,
Alias: hash,
Type: req.Source.ImageType,
AutoUpdate: req.AutoUpdate,
Public: req.Public,
ProjectName: project,
Budget: budget,
SourceProjectName: req.Source.Project,
})
if err != nil {
return nil, err
}
err = s.DB.Cluster.Transaction(ctx, func(ctx context.Context, tx *db.ClusterTx) error {
var id int
id, info, err = tx.GetImage(ctx, info.Fingerprint, dbCluster.ImageFilter{Project: &project})
if err != nil {
return err
}
// Allow overriding or adding properties
for k, v := range req.Properties {
info.Properties[k] = v
}
// Get profile IDs
if req.Profiles == nil {
req.Profiles = []string{api.ProjectDefaultName}
}
profileIds := make([]int64, len(req.Profiles))
for i, profile := range req.Profiles {
profileID, _, err := tx.GetProfile(ctx, project, profile)
if response.IsNotFoundError(err) {
return fmt.Errorf("Profile '%s' doesn't exist", profile)
} else if err != nil {
return err
}
profileIds[i] = profileID
}
// Update the DB record if needed
if req.Public || req.AutoUpdate || req.Filename != "" || len(req.Properties) > 0 || len(req.Profiles) > 0 {
err := tx.UpdateImage(ctx, id, req.Filename, info.Size, req.Public, req.AutoUpdate, info.Architecture, info.CreatedAt, info.ExpiresAt, info.Properties, project, profileIds)
if err != nil {
return err
}
}
return nil
})
if err != nil {
return nil, err
}
return info, nil
}
func imgPostURLInfo(ctx context.Context, s *state.State, r *http.Request, req api.ImagesPost, op *operations.Operation, project string, budget int64) (*api.Image, error) {
var err error
if req.Source.URL == "" {
return nil, fmt.Errorf("Missing URL")
}
myhttp, err := localUtil.HTTPClient("", s.Proxy)
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
}
architectures := []string{}
for _, architecture := range s.OS.Architectures {
architectureName, err := osarch.ArchitectureName(architecture)
if err != nil {
return nil, err
}
architectures = append(architectures, architectureName)
}
head.Header.Set("User-Agent", version.UserAgent)
head.Header.Set("Incus-Server-Architectures", strings.Join(architectures, ", "))
head.Header.Set("Incus-Server-Version", version.Version)
raw, err := myhttp.Do(head)
if err != nil {
return nil, err
}
hash := raw.Header.Get("Incus-Image-Hash")
if hash == "" {
return nil, fmt.Errorf("Missing Incus-Image-Hash header")
}
url := raw.Header.Get("Incus-Image-URL")
if url == "" {
return nil, fmt.Errorf("Missing Incus-Image-URL header")
}
// Import the image
info, err := ImageDownload(ctx, r, s, op, &ImageDownloadArgs{
Server: url,
Protocol: "direct",
Alias: hash,
AutoUpdate: req.AutoUpdate,
Public: req.Public,
ProjectName: project,
Budget: budget,
})
if err != nil {
return nil, err
}
err = s.DB.Cluster.Transaction(ctx, func(ctx context.Context, tx *db.ClusterTx) error {
var id int
id, info, err = tx.GetImage(ctx, info.Fingerprint, dbCluster.ImageFilter{Project: &project})
if err != nil {
return 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 := tx.UpdateImage(ctx, id, req.Filename, info.Size, req.Public, req.AutoUpdate, info.Architecture, info.CreatedAt, info.ExpiresAt, info.Properties, "", nil)
if err != nil {
return err
}
}
return nil
})
if err != nil {
return nil, err
}
return info, nil
}
func getImgPostInfo(ctx context.Context, s *state.State, r *http.Request, builddir string, project string, post *os.File, metadata map[string]any) (*api.Image, error) {
info := api.Image{}
var imageMeta *api.ImageMetadata
l := logger.AddContext(logger.Ctx{"function": "getImgPostInfo"})
info.Public = util.IsTrue(r.Header.Get("X-Incus-public"))
propHeaders := r.Header[http.CanonicalHeaderKey("X-Incus-properties")]
profilesHeaders := r.Header.Get("X-Incus-profiles")
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 := os.CreateTemp(builddir, "incus_tar_")
if err != nil {
return nil, err
}
defer func() { _ = os.Remove(imageTarf.Name()) }()
// Parse the POST data
_, err = post.Seek(0, io.SeekStart)
if err != nil {
return nil, err
}
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 {
l.Error("Failed to copy the image tarfile", logger.Ctx{"err": err})
return nil, err
}
// Get the rootfs tarball
part, err = mr.NextPart()
if err != nil {
l.Error("Failed to get the next part", logger.Ctx{"err": err})
return nil, err
}
if part.FormName() == "rootfs" {
info.Type = instancetype.Container.String()
} else if part.FormName() == "rootfs.img" {
info.Type = instancetype.VM.String()
} else {
l.Error("Invalid multipart image")
return nil, fmt.Errorf("Invalid multipart image")
}
// Create a temporary file for the rootfs tarball
rootfsTarf, err := os.CreateTemp(builddir, "incus_tar_")
if err != nil {
return nil, err
}
defer func() { _ = os.Remove(rootfsTarf.Name()) }()
size, err = io.Copy(io.MultiWriter(rootfsTarf, sha256), part)
info.Size += size
_ = rootfsTarf.Close()
if err != nil {
l.Error("Failed to copy the rootfs tarfile", logger.Ctx{"err": err})
return nil, err
}
info.Filename = part.FileName()
info.Fingerprint = fmt.Sprintf("%x", sha256.Sum(nil))
expectedFingerprint := r.Header.Get("X-Incus-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 {
l.Error("Failed to get image metadata", logger.Ctx{"err": err})
return nil, err
}
imgfname := internalUtil.VarPath("images", info.Fingerprint)
err = internalUtil.FileMove(imageTarf.Name(), imgfname)
if err != nil {
l.Error("Failed to move the image tarfile", logger.Ctx{
"err": err,
"source": imageTarf.Name(),
"dest": imgfname})
return nil, err
}
rootfsfname := internalUtil.VarPath("images", info.Fingerprint+".rootfs")
err = internalUtil.FileMove(rootfsTarf.Name(), rootfsfname)
if err != nil {
l.Error("Failed to move the rootfs tarfile", logger.Ctx{
"err": err,
"source": rootfsTarf.Name(),
"dest": imgfname})
return nil, err
}
} else {
_, err = post.Seek(0, io.SeekStart)
if err != nil {
return nil, err
}
size, err = io.Copy(sha256, post)
if err != nil {
l.Error("Failed to copy the tarfile", logger.Ctx{"err": err})
return nil, err
}
info.Size = size
info.Filename = r.Header.Get("X-Incus-filename")
info.Fingerprint = fmt.Sprintf("%x", sha256.Sum(nil))
expectedFingerprint := r.Header.Get("X-Incus-fingerprint")
if expectedFingerprint != "" && info.Fingerprint != expectedFingerprint {
l.Error("Fingerprints don't match", logger.Ctx{
"got": info.Fingerprint,
"expected": expectedFingerprint})
err = fmt.Errorf("fingerprints don't match, got %s expected %s", info.Fingerprint, expectedFingerprint)
return nil, err
}
var imageType string
imageMeta, imageType, err = getImageMetadata(post.Name())
if err != nil {
l.Error("Failed to get image metadata", logger.Ctx{"err": err})
return nil, err
}
info.Type = imageType
imgfname := internalUtil.VarPath("images", info.Fingerprint)
err = internalUtil.FileMove(post.Name(), imgfname)
if err != nil {
l.Error("Failed to move the tarfile", logger.Ctx{
"err": err,
"source": post.Name(),
"dest": imgfname})
return nil, err
}
}
info.Architecture = imageMeta.Architecture
if imageMeta.CreationDate > 0 {
info.CreatedAt = time.Unix(imageMeta.CreationDate, 0)
}
expiresAt, ok := metadata["expires_at"]
if ok {
info.ExpiresAt = expiresAt.(time.Time)
} else if imageMeta.ExpiryDate > 0 {
info.ExpiresAt = time.Unix(imageMeta.ExpiryDate, 0)
}
properties, ok := metadata["properties"]
if ok {
info.Properties = properties.(map[string]string)
} else {
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]
}
}
}
var profileIds []int64
if len(profilesHeaders) > 0 {
p, _ := url.ParseQuery(profilesHeaders)
profileIds = make([]int64, len(p["profile"]))
err = s.DB.Cluster.Transaction(ctx, func(ctx context.Context, tx *db.ClusterTx) error {
for i, val := range p["profile"] {
profileID, _, err := tx.GetProfile(ctx, project, val)
if response.IsNotFoundError(err) {
return fmt.Errorf("Profile '%s' doesn't exist", val)
} else if err != nil {
return err
}
profileIds[i] = profileID
}
return nil
})
if err != nil {
return nil, err
}
}
var exists bool
err = s.DB.Cluster.Transaction(ctx, func(ctx context.Context, tx *db.ClusterTx) error {
// Check if the image already exists
exists, err = tx.ImageExists(ctx, project, info.Fingerprint)
return err
})
if err != nil {
return nil, err
}
if exists {
// Do not create a database entry if the request is coming from the internal
// cluster communications for image synchronization
if isClusterNotification(r) {
err = s.DB.Cluster.Transaction(ctx, func(ctx context.Context, tx *db.ClusterTx) error {
return tx.AddImageToLocalNode(ctx, project, info.Fingerprint)
})
if err != nil {
return nil, err
}
} else {
return &info, fmt.Errorf("Image with same fingerprint already exists")
}
} else {
public, ok := metadata["public"]
if ok {
info.Public = public.(bool)
}
err = s.DB.Cluster.Transaction(ctx, func(ctx context.Context, tx *db.ClusterTx) error {
// Create the database entry
return tx.CreateImage(ctx, project, info.Fingerprint, info.Filename, info.Size, info.Public, info.AutoUpdate, info.Architecture, info.CreatedAt, info.ExpiresAt, info.Properties, info.Type, profileIds)
})
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(s *state.State, info *api.Image, storagePool string) error {
if storagePool == "" {
return fmt.Errorf("No storage pool specified")
}
pool, err := storagePools.LoadByName(s, storagePool)
if err != nil {
return err
}
err = pool.EnsureImage(info.Fingerprint, nil)
if err != nil {
return err
}
return nil
}
// swagger:operation POST /1.0/images?public images images_post_untrusted
//
// Add an image
//
// Pushes the data to the target image server.
// This is meant for server to server communication where a new image entry is
// prepared on the target server and the source server is provided that URL
// and a secret token to push the image content over.
//
// ---
// consumes:
// - application/json
// produces:
// - application/json
// parameters:
// - in: query
// name: project
// description: Project name
// type: string
// example: default
// - in: body
// name: image
// description: Image
// required: true
// schema:
// $ref: "#/definitions/ImagesPost"
// responses:
// "200":
// $ref: "#/responses/EmptySyncResponse"
// "400":
// $ref: "#/responses/BadRequest"
// "403":
// $ref: "#/responses/Forbidden"
// "500":
// $ref: "#/responses/InternalServerError"
// swagger:operation POST /1.0/images images images_post
//
// Add an image
//
// Adds a new image to the image store.
//
// ---
// consumes:
// - application/json
// produces:
// - application/json
// parameters:
// - in: query
// name: project
// description: Project name
// type: string
// example: default
// - in: body
// name: image
// description: Image
// required: false
// schema:
// $ref: "#/definitions/ImagesPost"
// - in: body
// name: raw_image
// description: Raw image file
// required: false
// - in: header
// name: X-Incus-secret
// description: Push secret for server to server communication
// schema:
// type: string
// example: RANDOM-STRING
// - in: header
// name: X-Incus-fingerprint
// description: Expected fingerprint when pushing a raw image
// schema:
// type: string
// - in: header
// name: X-Incus-properties
// description: Descriptive properties
// schema:
// type: object
// additionalProperties:
// type: string
// - in: header
// name: X-Incus-public
// description: Whether the image is available to unauthenticated users
// schema:
// type: boolean
// - in: header
// name: X-Incus-filename
// description: Original filename of the image
// schema:
// type: string
// - in: header
// name: X-Incus-profiles
// description: List of profiles to use
// schema:
// type: array
// items:
// type: string
// responses:
// "202":
// $ref: "#/responses/Operation"
// "400":
// $ref: "#/responses/BadRequest"
// "403":
// $ref: "#/responses/Forbidden"
// "500":
// $ref: "#/responses/InternalServerError"
func imagesPost(d *Daemon, r *http.Request) response.Response {
s := d.State()
projectName := request.ProjectParam(r)
var userCanCreateImages bool
err := s.Authorizer.CheckPermission(r.Context(), r, auth.ObjectProject(projectName), auth.EntitlementCanCreateImages)
if err == nil {
userCanCreateImages = true
} else if !api.StatusErrorCheck(err, http.StatusForbidden) {
return response.SmartError(err)
}
trusted := d.checkTrustedClient(r) == nil && userCanCreateImages
secret := r.Header.Get("X-Incus-secret")
fingerprint := r.Header.Get("X-Incus-fingerprint")
var imageMetadata map[string]any
if !trusted && (secret == "" || fingerprint == "") {
return response.Forbidden(nil)
} else {
// We need to invalidate the secret whether the source is trusted or not.
op, err := imageValidSecret(s, r, projectName, fingerprint, secret)
if err != nil {
return response.SmartError(err)
}
if op != nil {
imageMetadata = op.Metadata
} else if !trusted {
return response.Forbidden(nil)
}
}