-
Notifications
You must be signed in to change notification settings - Fork 933
/
image.go
1770 lines (1428 loc) · 41.7 KB
/
image.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 (
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"github.com/spf13/cobra"
"gopkg.in/yaml.v2"
"github.com/canonical/lxd/client"
"github.com/canonical/lxd/shared"
"github.com/canonical/lxd/shared/api"
cli "github.com/canonical/lxd/shared/cmd"
"github.com/canonical/lxd/shared/i18n"
"github.com/canonical/lxd/shared/termios"
)
type imageColumn struct {
Name string
Data func(api.Image) string
}
type cmdImage struct {
global *cmdGlobal
}
func (c *cmdImage) command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("image")
cmd.Short = i18n.G("Manage images")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Manage images
In LXD instances are created from images. Those images were themselves
either generated from an existing instance or downloaded from an image
server.
When using remote images, LXD will automatically cache images for you
and remove them upon expiration.
The image unique identifier is the hash (sha-256) of its representation
as a compressed tarball (or for split images, the concatenation of the
metadata and rootfs tarballs).
Images can be referenced by their full hash, shortest unique partial
hash or alias name (if one is set).`))
// Alias
imageAliasCmd := cmdImageAlias{global: c.global, image: c}
cmd.AddCommand(imageAliasCmd.command())
// Copy
imageCopyCmd := cmdImageCopy{global: c.global, image: c}
cmd.AddCommand(imageCopyCmd.command())
// Delete
imageDeleteCmd := cmdImageDelete{global: c.global, image: c}
cmd.AddCommand(imageDeleteCmd.command())
// Edit
imageEditCmd := cmdImageEdit{global: c.global, image: c}
cmd.AddCommand(imageEditCmd.command())
// Export
imageExportCmd := cmdImageExport{global: c.global, image: c}
cmd.AddCommand(imageExportCmd.command())
// Import
imageImportCmd := cmdImageImport{global: c.global, image: c}
cmd.AddCommand(imageImportCmd.command())
// Info
imageInfoCmd := cmdImageInfo{global: c.global, image: c}
cmd.AddCommand(imageInfoCmd.command())
// List
imageListCmd := cmdImageList{global: c.global, image: c}
cmd.AddCommand(imageListCmd.command())
// Refresh
imageRefreshCmd := cmdImageRefresh{global: c.global, image: c}
cmd.AddCommand(imageRefreshCmd.command())
// Show
imageShowCmd := cmdImageShow{global: c.global, image: c}
cmd.AddCommand(imageShowCmd.command())
// Get-property
imageGetPropCmd := cmdImageGetProp{global: c.global, image: c}
cmd.AddCommand(imageGetPropCmd.command())
// Set-property
imageSetPropCmd := cmdImageSetProp{global: c.global, image: c}
cmd.AddCommand(imageSetPropCmd.command())
// Unset-property
imageUnsetPropCmd := cmdImageUnsetProp{global: c.global, image: c, imageSetProp: &imageSetPropCmd}
cmd.AddCommand(imageUnsetPropCmd.command())
// Workaround for subcommand usage errors. See: https://github.com/spf13/cobra/issues/706
cmd.Args = cobra.NoArgs
cmd.Run = func(cmd *cobra.Command, args []string) { _ = cmd.Usage() }
return cmd
}
// dereferenceAlias resolves an alias (or a fingerprint) to an image and returns the image and its etag.
func (c *cmdImage) dereferenceAlias(d lxd.ImageServer, imageType string, inName string) (image *api.Image, etag string, err error) {
if inName == "" {
inName = "default"
}
result, _, err := d.GetImageAliasType(imageType, inName)
if err != nil {
// Maybe that inName is a fingerprint and can't be found as an alias
image, etag, errImage := d.GetImage(inName)
if errImage != nil {
return nil, "", fmt.Errorf(i18n.G("Failed fetching fingerprint %q: %w"), inName, errImage)
}
return image, etag, nil
}
// Alias could be resolved, return its image
image, etag, err = d.GetImage(result.Target)
if err != nil {
return nil, "", fmt.Errorf(i18n.G("Failed fetching fingerprint %q for alias %q: %w"), result.Target, inName, err)
}
return image, etag, nil
}
// Copy.
type cmdImageCopy struct {
global *cmdGlobal
image *cmdImage
flagAliases []string
flagPublic bool
flagCopyAliases bool
flagAutoUpdate bool
flagVM bool
flagMode string
flagTargetProject string
flagProfile []string
}
func (c *cmdImageCopy) command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("copy", i18n.G("[<remote>:]<image> <remote>:"))
cmd.Aliases = []string{"cp"}
cmd.Short = i18n.G("Copy images between servers")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Copy images between servers
The auto-update flag instructs the server to keep this image up to date.
It requires the source to be an alias and for it to be public.`))
cmd.Flags().BoolVar(&c.flagPublic, "public", false, i18n.G("Make image public"))
cmd.Flags().BoolVar(&c.flagCopyAliases, "copy-aliases", false, i18n.G("Copy aliases from source"))
cmd.Flags().BoolVar(&c.flagAutoUpdate, "auto-update", false, i18n.G("Keep the image up to date after initial copy"))
cmd.Flags().StringArrayVar(&c.flagAliases, "alias", nil, i18n.G("New aliases to add to the image")+"``")
cmd.Flags().BoolVar(&c.flagVM, "vm", false, i18n.G("Copy virtual machine images"))
cmd.Flags().StringVar(&c.flagMode, "mode", "pull", i18n.G("Transfer mode. One of pull (default), push or relay")+"``")
cmd.Flags().StringVar(&c.flagTargetProject, "target-project", "", i18n.G("Copy to a project different from the source")+"``")
cmd.Flags().StringArrayVarP(&c.flagProfile, "profile", "p", nil, i18n.G("Profile to apply to the new image")+"``")
cmd.RunE = c.run
cmd.ValidArgsFunction = func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) == 0 {
return c.global.cmpImages(toComplete)
}
if len(args) == 1 {
return c.global.cmpRemotes(false)
}
return nil, cobra.ShellCompDirectiveNoFileComp
}
return cmd
}
func (c *cmdImageCopy) run(cmd *cobra.Command, args []string) error {
conf := c.global.conf
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 2, 2)
if exit {
return err
}
if c.flagMode != "pull" && c.flagAutoUpdate {
return errors.New(i18n.G("Auto update is only available in pull mode"))
}
// Parse source remote
remoteName, name, err := c.global.conf.ParseRemote(args[0])
if err != nil {
return err
}
sourceServer, err := c.global.conf.GetImageServer(remoteName)
if err != nil {
return err
}
// Revert project for `sourceServer` which may have been overwritten
// by `--project` flag in `GetImageServer` method
remote := conf.Remotes[remoteName]
if remote.Protocol != "simplestream" && !remote.Public {
d, ok := sourceServer.(lxd.InstanceServer)
if ok {
sourceServer = d.UseProject(remote.Project)
}
}
// Parse destination remote
resources, err := c.global.ParseServers(args[1])
if err != nil {
return err
}
destinationServer := resources[0].server
if resources[0].name != "" {
return errors.New(i18n.G("Can't provide a name for the target image"))
}
// Resolve image type
imageType := ""
if c.flagVM {
imageType = "virtual-machine"
}
if c.flagTargetProject != "" {
destinationServer = destinationServer.UseProject(c.flagTargetProject)
}
// Copy the image
var imgInfo *api.Image
var fp string
if conf.Remotes[remoteName].Protocol == "simplestreams" && !c.flagCopyAliases && len(c.flagAliases) == 0 {
// All simplestreams images are always public, so unless we
// need the aliases list too or the real fingerprint, we can skip the otherwise very expensive
// alias resolution and image info retrieval step.
imgInfo = &api.Image{}
imgInfo.Fingerprint = name
imgInfo.Public = true
} else {
// Resolve any alias and then grab the image information from the source
imgInfo, _, err = c.image.dereferenceAlias(sourceServer, imageType, name)
if err != nil {
return err
}
// Store the fingerprint for use when creating aliases later (as imgInfo.Fingerprint may be overridden)
fp = imgInfo.Fingerprint
}
if imgInfo.Public && imgInfo.Fingerprint != name && !strings.HasPrefix(imgInfo.Fingerprint, name) {
// If dealing with an alias, set the imgInfo fingerprint to match the provided alias (needed for auto-update)
imgInfo.Fingerprint = name
}
copyArgs := lxd.ImageCopyArgs{
AutoUpdate: c.flagAutoUpdate,
Public: c.flagPublic,
Type: imageType,
Mode: c.flagMode,
Profiles: c.flagProfile,
}
// Do the copy
op, err := destinationServer.CopyImage(sourceServer, *imgInfo, ©Args)
if err != nil {
return err
}
// Register progress handler
progress := cli.ProgressRenderer{
Format: i18n.G("Copying the image: %s"),
Quiet: c.global.flagQuiet,
}
_, err = op.AddHandler(progress.UpdateOp)
if err != nil {
progress.Done("")
return err
}
// Wait for operation to finish
err = cli.CancelableWait(op, &progress)
if err != nil {
progress.Done("")
return err
}
progress.Done(i18n.G("Image copied successfully!"))
// Ensure aliases
aliases := make([]api.ImageAlias, len(c.flagAliases))
for i, entry := range c.flagAliases {
aliases[i].Name = entry
}
if c.flagCopyAliases {
// Also add the original aliases
aliases = append(aliases, imgInfo.Aliases...)
}
err = ensureImageAliases(destinationServer, aliases, fp)
if err != nil {
return err
}
return nil
}
// Delete.
type cmdImageDelete struct {
global *cmdGlobal
image *cmdImage
}
func (c *cmdImageDelete) command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("delete", i18n.G("[<remote>:]<image> [[<remote>:]<image>...]"))
cmd.Aliases = []string{"rm"}
cmd.Short = i18n.G("Delete images")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Delete images`))
cmd.RunE = c.run
cmd.ValidArgsFunction = func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return c.global.cmpImages(toComplete)
}
return cmd
}
func (c *cmdImageDelete) run(cmd *cobra.Command, args []string) error {
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 1, -1)
if exit {
return err
}
// Parse remote
resources, err := c.global.ParseServers(args...)
if err != nil {
return err
}
for _, resource := range resources {
if resource.name == "" {
return errors.New(i18n.G("Image identifier missing"))
}
image, _, err := c.image.dereferenceAlias(resource.server, "", resource.name)
if err != nil {
return err
}
op, err := resource.server.DeleteImage(image.Fingerprint)
if err != nil {
return err
}
err = op.Wait()
if err != nil {
return err
}
}
return nil
}
// Edit.
type cmdImageEdit struct {
global *cmdGlobal
image *cmdImage
}
func (c *cmdImageEdit) command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("edit", i18n.G("[<remote>:]<image>"))
cmd.Short = i18n.G("Edit image properties")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Edit image properties`))
cmd.Example = cli.FormatSection("", i18n.G(
`lxc image edit <image>
Launch a text editor to edit the properties
lxc image edit <image> < image.yaml
Load the image properties from a YAML file`))
cmd.RunE = c.run
cmd.ValidArgsFunction = func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) == 0 {
return c.global.cmpImages(toComplete)
}
return nil, cobra.ShellCompDirectiveNoFileComp
}
return cmd
}
func (c *cmdImageEdit) helpTemplate() string {
return i18n.G(
`### This is a YAML representation of the image properties.
### Any line starting with a '# will be ignored.
###
### Each property is represented by a single line:
### An example would be:
### description: My custom image`)
}
func (c *cmdImageEdit) run(cmd *cobra.Command, args []string) error {
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 1, 1)
if exit {
return err
}
// Parse remote
resources, err := c.global.ParseServers(args[0])
if err != nil {
return err
}
resource := resources[0]
if resource.name == "" {
return fmt.Errorf(i18n.G("Image identifier missing: %s"), args[0])
}
// Resolve any aliases
image, etag, err := c.image.dereferenceAlias(resource.server, "", resource.name)
if err != nil {
return err
}
// If stdin isn't a terminal, read text from it
if !termios.IsTerminal(getStdinFd()) {
contents, err := io.ReadAll(os.Stdin)
if err != nil {
return err
}
newdata := api.ImagePut{}
err = yaml.Unmarshal(contents, &newdata)
if err != nil {
return err
}
return resource.server.UpdateImage(image.Fingerprint, newdata, "")
}
brief := image.Writable()
data, err := yaml.Marshal(&brief)
if err != nil {
return err
}
// Spawn the editor
content, err := shared.TextEditor("", []byte(c.helpTemplate()+"\n\n"+string(data)))
if err != nil {
return err
}
for {
// Parse the text received from the editor
newdata := api.ImagePut{}
err = yaml.Unmarshal(content, &newdata)
if err == nil {
err = resource.server.UpdateImage(image.Fingerprint, newdata, etag)
}
// Respawn the editor
if err != nil {
fmt.Fprintf(os.Stderr, i18n.G("Config parsing error: %s")+"\n", err)
fmt.Println(i18n.G("Press enter to open the editor again or ctrl+c to abort change"))
_, err := os.Stdin.Read(make([]byte, 1))
if err != nil {
return err
}
content, err = shared.TextEditor("", content)
if err != nil {
return err
}
continue
}
break
}
return nil
}
// Export.
type cmdImageExport struct {
global *cmdGlobal
image *cmdImage
flagVM bool
}
func (c *cmdImageExport) command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("export", i18n.G("[<remote>:]<image> [<target>]"))
cmd.Short = i18n.G("Export and download images")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Export and download images
The output target is optional and defaults to the working directory.`))
cmd.Flags().BoolVar(&c.flagVM, "vm", false, i18n.G("Query virtual machine images"))
cmd.RunE = c.run
cmd.ValidArgsFunction = func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) == 0 {
return c.global.cmpImages(toComplete)
}
return nil, cobra.ShellCompDirectiveNoFileComp
}
return cmd
}
func (c *cmdImageExport) run(cmd *cobra.Command, args []string) error {
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 1, 2)
if exit {
return err
}
// Parse remote
remoteName, name, err := c.global.conf.ParseRemote(args[0])
if err != nil {
return err
}
remoteServer, err := c.global.conf.GetImageServer(remoteName)
if err != nil {
return err
}
// Resolve aliases
imageType := ""
if c.flagVM {
imageType = "virtual-machine"
}
image, _, err := c.image.dereferenceAlias(remoteServer, imageType, name)
if err != nil {
return err
}
// Default target is current directory
target := "."
targetMeta := image.Fingerprint
if len(args) > 1 {
target = args[1]
if shared.IsDir(shared.HostPathFollow(args[1])) {
targetMeta = filepath.Join(args[1], targetMeta)
} else {
targetMeta = args[1]
}
}
targetMeta = shared.HostPathFollow(targetMeta)
targetRootfs := targetMeta + ".root"
// Prepare the files
dest, err := os.Create(targetMeta)
if err != nil {
return err
}
defer func() { _ = dest.Close() }()
destRootfs, err := os.Create(targetRootfs)
if err != nil {
return err
}
defer func() { _ = destRootfs.Close() }()
// Prepare the download request
progress := cli.ProgressRenderer{
Format: i18n.G("Exporting the image: %s"),
Quiet: c.global.flagQuiet,
}
req := lxd.ImageFileRequest{
MetaFile: io.WriteSeeker(dest),
RootfsFile: io.WriteSeeker(destRootfs),
ProgressHandler: progress.UpdateProgress,
}
// Download the image
resp, err := remoteServer.GetImageFile(image.Fingerprint, req)
if err != nil {
_ = os.Remove(targetMeta)
_ = os.Remove(targetRootfs)
progress.Done("")
return err
}
// Truncate down to size
if resp.RootfsSize > 0 {
err = destRootfs.Truncate(resp.RootfsSize)
if err != nil {
return err
}
}
err = dest.Truncate(resp.MetaSize)
if err != nil {
return err
}
// Cleanup
if resp.RootfsSize == 0 {
err := os.Remove(targetRootfs)
if err != nil {
_ = os.Remove(targetMeta)
_ = os.Remove(targetRootfs)
progress.Done("")
return err
}
}
// Rename files
if shared.IsDir(shared.HostPathFollow(target)) {
if resp.MetaName != "" {
err := os.Rename(targetMeta, shared.HostPathFollow(filepath.Join(target, resp.MetaName)))
if err != nil {
_ = os.Remove(targetMeta)
_ = os.Remove(targetRootfs)
progress.Done("")
return err
}
}
if resp.RootfsSize > 0 && resp.RootfsName != "" {
err := os.Rename(targetRootfs, shared.HostPathFollow(filepath.Join(target, resp.RootfsName)))
if err != nil {
_ = os.Remove(targetMeta)
_ = os.Remove(targetRootfs)
progress.Done("")
return err
}
}
} else if resp.RootfsSize == 0 && len(args) > 1 {
if resp.MetaName != "" {
extension := strings.SplitN(resp.MetaName, ".", 2)[1]
err := os.Rename(targetMeta, fmt.Sprintf("%s.%s", targetMeta, extension))
if err != nil {
_ = os.Remove(targetMeta)
progress.Done("")
return err
}
}
}
progress.Done(i18n.G("Image exported successfully!"))
return nil
}
// Import.
type cmdImageImport struct {
global *cmdGlobal
image *cmdImage
flagPublic bool
flagAliases []string
}
func (c *cmdImageImport) command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("import", i18n.G("<tarball>|<directory>|<URL> [<rootfs tarball>] [<remote>:] [key=value...]"))
cmd.Short = i18n.G("Import images into the image store")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Import image into the image store
Directory import is only available on Linux and must be performed as root.
Descriptive properties can be set by providing key=value pairs. Example: os=Ubuntu release=noble variant=cloud.`))
cmd.Flags().BoolVar(&c.flagPublic, "public", false, i18n.G("Make image public"))
cmd.Flags().StringArrayVar(&c.flagAliases, "alias", nil, i18n.G("New aliases to add to the image")+"``")
cmd.RunE = c.run
cmd.ValidArgsFunction = func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) == 0 {
return nil, cobra.ShellCompDirectiveDefault
}
if len(args) == 1 {
return c.global.cmpRemotes(false)
}
return nil, cobra.ShellCompDirectiveNoFileComp
}
return cmd
}
func (c *cmdImageImport) packImageDir(path string) (string, error) {
// Quick checks.
if os.Geteuid() == -1 {
return "", errors.New(i18n.G("Directory import is not available on this platform"))
} else if os.Geteuid() != 0 {
return "", errors.New(i18n.G("Must run as root to import from directory"))
}
outFile, err := os.CreateTemp("", "lxd_image_")
if err != nil {
return "", err
}
defer func() { _ = outFile.Close() }()
outFileName := outFile.Name()
_, err = shared.RunCommand("tar", "-C", path, "--numeric-owner", "--restrict", "--force-local", "--xattrs", "-cJf", outFileName, "rootfs", "templates", "metadata.yaml")
if err != nil {
return "", err
}
return outFileName, outFile.Close()
}
func (c *cmdImageImport) run(cmd *cobra.Command, args []string) error {
conf := c.global.conf
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 1, -1)
if exit {
return err
}
// Import the image
var imageFile string
var rootfsFile string
var properties []string
var remote string
for _, arg := range args {
split := strings.Split(arg, "=")
if len(split) == 1 || shared.PathExists(shared.HostPathFollow(arg)) {
if strings.HasSuffix(arg, ":") {
var err error
remote, _, err = conf.ParseRemote(arg)
if err != nil {
return err
}
} else {
if imageFile == "" {
imageFile = args[0]
} else {
rootfsFile = arg
}
}
} else {
properties = append(properties, arg)
}
}
if remote == "" {
remote = conf.DefaultRemote
}
if imageFile == "" {
imageFile = args[0]
}
if shared.PathExists(shared.HostPathFollow(filepath.Clean(imageFile))) {
imageFile = shared.HostPathFollow(filepath.Clean(imageFile))
}
if rootfsFile != "" && shared.PathExists(shared.HostPathFollow(filepath.Clean(rootfsFile))) {
rootfsFile = shared.HostPathFollow(filepath.Clean(rootfsFile))
}
d, err := conf.GetInstanceServer(remote)
if err != nil {
return err
}
if strings.HasPrefix(imageFile, "http://") {
return errors.New(i18n.G("Only https:// is supported for remote image import"))
}
var createArgs *lxd.ImageCreateArgs
image := api.ImagesPost{}
image.Public = c.flagPublic
// Handle properties
for _, entry := range properties {
fields := strings.SplitN(entry, "=", 2)
if len(fields) < 2 {
return fmt.Errorf(i18n.G("Bad property: %s"), entry)
}
if image.Properties == nil {
image.Properties = map[string]string{}
}
image.Properties[strings.TrimSpace(fields[0])] = strings.TrimSpace(fields[1])
}
progress := cli.ProgressRenderer{
Format: i18n.G("Transferring image: %s"),
Quiet: c.global.flagQuiet,
}
imageType := "container"
if strings.HasPrefix(imageFile, "https://") {
image.Source = &api.ImagesPostSource{}
image.Source.Type = "url"
image.Source.Mode = "pull"
image.Source.Protocol = "direct"
image.Source.URL = imageFile
createArgs = nil
} else {
var meta io.ReadCloser
var rootfs io.ReadCloser
// Open meta
if shared.IsDir(imageFile) {
imageFile, err = c.packImageDir(imageFile)
if err != nil {
return err
}
// remove temp file
defer func() { _ = os.Remove(imageFile) }()
}
meta, err = os.Open(imageFile)
if err != nil {
return err
}
defer func() { _ = meta.Close() }()
// Open rootfs
if rootfsFile != "" {
rootfs, err = os.Open(rootfsFile)
if err != nil {
return err
}
defer func() { _ = rootfs.Close() }()
_, ext, _, err := shared.DetectCompressionFile(rootfs)
if err != nil {
return err
}
_, err = rootfs.(*os.File).Seek(0, io.SeekStart)
if err != nil {
return err
}
if ext == ".qcow2" {
imageType = "virtual-machine"
}
}
createArgs = &lxd.ImageCreateArgs{
MetaFile: meta,
MetaName: filepath.Base(imageFile),
RootfsFile: rootfs,
RootfsName: filepath.Base(rootfsFile),
ProgressHandler: progress.UpdateProgress,
Type: imageType,
}
image.Filename = createArgs.MetaName
}
// Start the transfer
op, err := d.CreateImage(image, createArgs)
if err != nil {
progress.Done("")
return err
}
// Wait for operation to finish
err = cli.CancelableWait(op, &progress)
if err != nil {
progress.Done("")
return err
}
opAPI := op.Get()
// Get the fingerprint
fingerprint, ok := opAPI.Metadata["fingerprint"].(string)
if !ok {
return fmt.Errorf(`Invalid type %T for "fingerprint" key in operation metadata`, fingerprint)
}
progress.Done(fmt.Sprintf(i18n.G("Image imported with fingerprint: %s"), fingerprint))
// Add the aliases
if len(c.flagAliases) > 0 {
aliases := make([]api.ImageAlias, len(c.flagAliases))
for i, entry := range c.flagAliases {
aliases[i].Name = entry
}
err = ensureImageAliases(d, aliases, fingerprint)
if err != nil {
return err
}
}
return nil
}
// Info.
type cmdImageInfo struct {
global *cmdGlobal
image *cmdImage
flagVM bool
}
func (c *cmdImageInfo) command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("info", i18n.G("[<remote>:]<image>"))
cmd.Short = i18n.G("Show useful information about images")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Show useful information about images`))
cmd.Flags().BoolVar(&c.flagVM, "vm", false, i18n.G("Query virtual machine images"))
cmd.RunE = c.run
cmd.ValidArgsFunction = func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) == 0 {
return c.global.cmpImages(toComplete)
}
return nil, cobra.ShellCompDirectiveNoFileComp
}
return cmd
}
func (c *cmdImageInfo) run(cmd *cobra.Command, args []string) error {
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 1, 1)
if exit {
return err
}
// Parse remote
remoteName, name, err := c.global.conf.ParseRemote(args[0])
if err != nil {
return err
}
remoteServer, err := c.global.conf.GetImageServer(remoteName)
if err != nil {
return err
}
// Render info
imageType := ""
if c.flagVM {
imageType = "virtual-machine"
}
info, _, err := c.image.dereferenceAlias(remoteServer, imageType, name)
if err != nil {
return err
}
public := i18n.G("no")
if info.Public {
public = i18n.G("yes")
}
cached := i18n.G("no")
if info.Cached {