/
util.go
1465 lines (1201 loc) · 34.1 KB
/
util.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 shared
import (
"bufio"
"bytes"
"context"
"crypto/rand"
"encoding/base64"
"encoding/gob"
"encoding/hex"
"encoding/json"
"fmt"
"hash"
"io"
"net/http"
"net/url"
"os"
"os/exec"
"path"
"path/filepath"
"reflect"
"regexp"
"runtime"
"strconv"
"strings"
"time"
"github.com/flosch/pongo2"
"github.com/canonical/lxd/shared/api"
"github.com/canonical/lxd/shared/cancel"
"github.com/canonical/lxd/shared/ioprogress"
"github.com/canonical/lxd/shared/revert"
"github.com/canonical/lxd/shared/units"
)
const SnapshotDelimiter = "/"
const HTTPSDefaultPort = 8443
const HTTPDefaultPort = 8080
const HTTPSMetricsDefaultPort = 9100
// HTTPSStorageBucketsDefaultPort the default port for the storage buckets listener.
const HTTPSStorageBucketsDefaultPort = 9000
// URLEncode encodes a path and query parameters to a URL.
func URLEncode(path string, query map[string]string) (string, error) {
u, err := url.Parse(path)
if err != nil {
return "", err
}
params := url.Values{}
for key, value := range query {
params.Add(key, value)
}
u.RawQuery = params.Encode()
return u.String(), nil
}
// AddSlash adds a slash to the end of paths if they don't already have one.
// This can be useful for rsyncing things, since rsync has behavior present on
// the presence or absence of a trailing slash.
func AddSlash(path string) string {
if path[len(path)-1] != '/' {
return path + "/"
}
return path
}
func PathExists(name string) bool {
_, err := os.Lstat(name)
if err != nil && os.IsNotExist(err) {
return false
}
return true
}
// PathIsEmpty checks if the given path is empty.
func PathIsEmpty(path string) (bool, error) {
f, err := os.Open(path)
if err != nil {
return false, err
}
defer func() { _ = f.Close() }()
// read in ONLY one file
_, err = f.ReadDir(1)
// and if the file is EOF... well, the dir is empty.
if err == io.EOF {
return true, nil
}
return false, err
}
// IsDir returns true if the given path is a directory.
func IsDir(name string) bool {
stat, err := os.Stat(name)
if err != nil {
return false
}
return stat.IsDir()
}
// IsUnixSocket returns true if the given path is either a Unix socket
// or a symbolic link pointing at a Unix socket.
func IsUnixSocket(path string) bool {
stat, err := os.Stat(path)
if err != nil {
return false
}
return (stat.Mode() & os.ModeSocket) == os.ModeSocket
}
// HostPathFollow takes a valid path (from HostPath) and resolves it
// all the way to its target or to the last which can be resolved.
func HostPathFollow(path string) string {
// Ignore empty paths
if len(path) == 0 {
return path
}
// Don't prefix stdin/stdout
if path == "-" {
return path
}
// Check if we're running in a snap package.
if !InSnap() {
return path
}
// Handle relative paths
if path[0] != os.PathSeparator {
// Use the cwd of the parent as snap-confine alters our own cwd on launch
ppid := os.Getppid()
if ppid < 1 {
return path
}
pwd, err := os.Readlink(fmt.Sprintf("/proc/%d/cwd", ppid))
if err != nil {
return path
}
path = filepath.Clean(strings.Join([]string{pwd, path}, string(os.PathSeparator)))
}
// Rely on "readlink -m" to do the right thing.
path = HostPath(path)
for {
target, err := RunCommand("readlink", "-m", path)
if err != nil {
return path
}
target = strings.TrimSpace(target)
if path == HostPath(target) {
return path
}
path = HostPath(target)
}
}
// HostPath returns the host path for the provided path
// On a normal system, this does nothing
// When inside of a snap environment, returns the real path.
func HostPath(path string) string {
// Ignore empty paths
if len(path) == 0 {
return path
}
// Don't prefix stdin/stdout
if path == "-" {
return path
}
// Check if we're running in a snap package
if !InSnap() {
return path
}
// Handle relative paths
if path[0] != os.PathSeparator {
// Use the cwd of the parent as snap-confine alters our own cwd on launch
ppid := os.Getppid()
if ppid < 1 {
return path
}
pwd, err := os.Readlink(fmt.Sprintf("/proc/%d/cwd", ppid))
if err != nil {
return path
}
path = filepath.Clean(strings.Join([]string{pwd, path}, string(os.PathSeparator)))
}
// Check if the path is already snap-aware
for _, prefix := range []string{"/dev", "/snap", "/var/snap", "/var/lib/snapd"} {
if path == prefix || strings.HasPrefix(path, fmt.Sprintf("%s/", prefix)) {
return path
}
}
return fmt.Sprintf("/var/lib/snapd/hostfs%s", path)
}
// VarPath returns the provided path elements joined by a slash and
// appended to the end of $LXD_DIR, which defaults to /var/lib/lxd.
func VarPath(path ...string) string {
varDir := os.Getenv("LXD_DIR")
if varDir == "" {
varDir = "/var/lib/lxd"
}
items := []string{varDir}
items = append(items, path...)
return filepath.Join(items...)
}
// CachePath returns the directory that LXD should its cache under. If LXD_DIR is
// set, this path is $LXD_DIR/cache, otherwise it is /var/cache/lxd.
func CachePath(path ...string) string {
varDir := os.Getenv("LXD_DIR")
logDir := "/var/cache/lxd"
if varDir != "" {
logDir = filepath.Join(varDir, "cache")
}
items := []string{logDir}
items = append(items, path...)
return filepath.Join(items...)
}
// LogPath returns the directory that LXD should put logs under. If LXD_DIR is
// set, this path is $LXD_DIR/logs, otherwise it is /var/log/lxd.
func LogPath(path ...string) string {
varDir := os.Getenv("LXD_DIR")
logDir := "/var/log/lxd"
if varDir != "" {
logDir = filepath.Join(varDir, "logs")
}
items := []string{logDir}
items = append(items, path...)
return filepath.Join(items...)
}
// LXDFileHeaders is extracted from the `X-LXD-*` family of file permissions
// headers.
type LXDFileHeaders struct {
UID int64
GID int64
Mode int
GIDModifyExisting bool
UIDModifyExisting bool
ModeModifyExisting bool
Type string
Write string
}
// ParseLXDFileHeaders parses and validates the `X-LXD-*` family of file
// permissions headers.
// - `X-LXD-uid`, `X-LXD-gid`
// Base 10 integer
// - `X-LXD-mode`
// Base 10 integer (no leading `0`) or base 8 integer (leading `0`) for the
// unix permissions bits
// - `X-LXD-type`
// One of `file`, `symlink`, `directory`
// - `X-LXD-write`
// One of `overwrite`, `append`
// - `X-LXD-modify-perm`
// Comma separated list; 0 or more of `mode`, `uid`, `gid`
func ParseLXDFileHeaders(headers http.Header) (*LXDFileHeaders, error) {
var uid, gid int64 = -1, -1
var mode = -1
var err error
rawUID := headers.Get("X-LXD-uid")
if rawUID != "" {
uid, err = strconv.ParseInt(rawUID, 10, 32)
if err != nil {
return nil, fmt.Errorf("Invalid UID: %w", err)
}
}
rawGID := headers.Get("X-LXD-gid")
if rawGID != "" {
gid, err = strconv.ParseInt(rawGID, 10, 32)
if err != nil {
return nil, fmt.Errorf("Invalid GID: %w", err)
}
}
rawMode := headers.Get("X-LXD-mode")
if rawMode != "" {
mode64, err := strconv.ParseInt(rawMode, 0, 0)
if err != nil || mode64 < 0 {
return nil, fmt.Errorf("Invalid Mode: %w", err)
}
mode = int(mode64 & int64(os.ModePerm))
}
filetype := headers.Get("X-LXD-type")
/* backwards compat: before "type" was introduced, we could only
* manipulate files
*/
if filetype == "" {
filetype = "file"
}
if !ValueInSlice(filetype, []string{"file", "symlink", "directory"}) {
return nil, fmt.Errorf("Invalid file type: %q", filetype)
}
write := headers.Get("X-LXD-write")
/* backwards compat: before "write" was introduced, we could only
* overwrite files
*/
if write == "" {
write = "overwrite"
}
if !ValueInSlice(write, []string{"overwrite", "append"}) {
return nil, fmt.Errorf("Invalid file write mode: %q", write)
}
UIDModifyExisting := false
GIDModifyExisting := false
modeModifyExisting := false
modifyPermHeader := headers.Get("X-LXD-modify-perm")
if modifyPermHeader != "" {
for _, perm := range strings.Split(modifyPermHeader, ",") {
UIDModifyExisting = UIDModifyExisting || perm == "uid"
GIDModifyExisting = GIDModifyExisting || perm == "gid"
modeModifyExisting = modeModifyExisting || perm == "mode"
if !ValueInSlice(perm, []string{"uid", "gid", "mode"}) {
return nil, fmt.Errorf("Invalid modify-perm field: %q", perm)
}
}
}
return &LXDFileHeaders{
UID: uid,
GID: gid,
Mode: mode,
UIDModifyExisting: UIDModifyExisting,
GIDModifyExisting: GIDModifyExisting,
ModeModifyExisting: modeModifyExisting,
Type: filetype,
Write: write,
}, nil
}
func ReaderToChannel(r io.Reader, bufferSize int) <-chan []byte {
if bufferSize <= 128*1024 {
bufferSize = 128 * 1024
}
ch := make(chan ([]byte))
go func() {
readSize := 128 * 1024
offset := 0
buf := make([]byte, bufferSize)
for {
read := buf[offset : offset+readSize]
nr, err := r.Read(read)
offset += nr
if offset > 0 && (offset+readSize >= bufferSize || err != nil) {
ch <- buf[0:offset]
offset = 0
buf = make([]byte, bufferSize)
}
if err != nil {
close(ch)
break
}
}
}()
return ch
}
// Returns a random hex encoded string from crypto/rand.
func RandomCryptoString() (string, error) {
buf := make([]byte, 32)
n, err := rand.Read(buf)
if err != nil {
return "", err
}
if n != len(buf) {
return "", fmt.Errorf("not enough random bytes read")
}
return hex.EncodeToString(buf), nil
}
func AtoiEmptyDefault(s string, def int) (int, error) {
if s == "" {
return def, nil
}
return strconv.Atoi(s)
}
func ReadStdin() ([]byte, error) {
buf := bufio.NewReader(os.Stdin)
line, _, err := buf.ReadLine()
if err != nil {
return nil, err
}
return line, nil
}
func WriteAll(w io.Writer, data []byte) error {
buf := bytes.NewBuffer(data)
toWrite := int64(buf.Len())
for {
n, err := io.Copy(w, buf)
if err != nil {
return err
}
toWrite -= n
if toWrite <= 0 {
return nil
}
}
}
// QuotaWriter returns an error once a given write quota gets exceeded.
type QuotaWriter struct {
writer io.Writer
quota int64
n int64
}
// NewQuotaWriter returns a new QuotaWriter wrapping the given writer.
//
// If the given quota is negative, then no quota is applied.
func NewQuotaWriter(writer io.Writer, quota int64) *QuotaWriter {
return &QuotaWriter{
writer: writer,
quota: quota,
}
}
// Write implements the Writer interface.
func (w *QuotaWriter) Write(p []byte) (n int, err error) {
if w.quota >= 0 {
w.n += int64(len(p))
if w.n > w.quota {
return 0, fmt.Errorf("reached %d bytes, exceeding quota of %d", w.n, w.quota)
}
}
return w.writer.Write(p)
}
// FileMove tries to move a file by using os.Rename,
// if that fails it tries to copy the file and remove the source.
func FileMove(oldPath string, newPath string) error {
err := os.Rename(oldPath, newPath)
if err == nil {
return nil
}
err = FileCopy(oldPath, newPath)
if err != nil {
return err
}
_ = os.Remove(oldPath)
return nil
}
// FileCopy copies a file, overwriting the target if it exists.
func FileCopy(source string, dest string) error {
fi, err := os.Lstat(source)
if err != nil {
return err
}
_, uid, gid := GetOwnerMode(fi)
if fi.Mode()&os.ModeSymlink != 0 {
target, err := os.Readlink(source)
if err != nil {
return err
}
if PathExists(dest) {
err = os.Remove(dest)
if err != nil {
return err
}
}
err = os.Symlink(target, dest)
if err != nil {
return err
}
if runtime.GOOS != "windows" {
return os.Lchown(dest, uid, gid)
}
return nil
}
s, err := os.Open(source)
if err != nil {
return err
}
defer func() { _ = s.Close() }()
d, err := os.Create(dest)
if err != nil {
if os.IsExist(err) {
d, err = os.OpenFile(dest, os.O_WRONLY, fi.Mode())
if err != nil {
return err
}
} else {
return err
}
}
_, err = io.Copy(d, s)
if err != nil {
return err
}
/* chown not supported on windows */
if runtime.GOOS != "windows" {
err = d.Chown(uid, gid)
if err != nil {
return err
}
}
return d.Close()
}
// DirCopy copies a directory recursively, overwriting the target if it exists.
func DirCopy(source string, dest string) error {
// Get info about source.
info, err := os.Stat(source)
if err != nil {
return fmt.Errorf("failed to get source directory info: %w", err)
}
if !info.IsDir() {
return fmt.Errorf("source is not a directory")
}
// Remove dest if it already exists.
if PathExists(dest) {
err := os.RemoveAll(dest)
if err != nil {
return fmt.Errorf("failed to remove destination directory %s: %w", dest, err)
}
}
// Create dest.
err = os.MkdirAll(dest, info.Mode())
if err != nil {
return fmt.Errorf("failed to create destination directory %s: %w", dest, err)
}
// Copy all files.
entries, err := os.ReadDir(source)
if err != nil {
return fmt.Errorf("failed to read source directory %s: %w", source, err)
}
for _, entry := range entries {
sourcePath := filepath.Join(source, entry.Name())
destPath := filepath.Join(dest, entry.Name())
if entry.IsDir() {
err := DirCopy(sourcePath, destPath)
if err != nil {
return fmt.Errorf("failed to copy sub-directory from %s to %s: %w", sourcePath, destPath, err)
}
} else {
err := FileCopy(sourcePath, destPath)
if err != nil {
return fmt.Errorf("failed to copy file from %s to %s: %w", sourcePath, destPath, err)
}
}
}
return nil
}
type BytesReadCloser struct {
Buf *bytes.Buffer
}
func (r BytesReadCloser) Read(b []byte) (n int, err error) {
return r.Buf.Read(b)
}
func (r BytesReadCloser) Close() error {
/* no-op since we're in memory */
return nil
}
func IsSnapshot(name string) bool {
return strings.Contains(name, SnapshotDelimiter)
}
func MkdirAllOwner(path string, perm os.FileMode, uid int, gid int) error {
// This function is a slightly modified version of MkdirAll from the Go standard library.
// https://golang.org/src/os/path.go?s=488:535#L9
// Fast path: if we can tell whether path is a directory or file, stop with success or error.
dir, err := os.Stat(path)
if err == nil {
if dir.IsDir() {
return nil
}
return fmt.Errorf("path exists but isn't a directory")
}
// Slow path: make sure parent exists and then call Mkdir for path.
i := len(path)
for i > 0 && os.IsPathSeparator(path[i-1]) { // Skip trailing path separator.
i--
}
j := i
for j > 0 && !os.IsPathSeparator(path[j-1]) { // Scan backward over element.
j--
}
if j > 1 {
// Create parent
err = MkdirAllOwner(path[0:j-1], perm, uid, gid)
if err != nil {
return err
}
}
// Parent now exists; invoke Mkdir and use its result.
err = os.Mkdir(path, perm)
err_chown := os.Chown(path, uid, gid)
if err_chown != nil {
return err_chown
}
if err != nil {
// Handle arguments like "foo/." by
// double-checking that directory doesn't exist.
dir, err1 := os.Lstat(path)
if err1 == nil && dir.IsDir() {
return nil
}
return err
}
return nil
}
// HasKey returns true if map has key.
func HasKey[K comparable, V any](key K, m map[K]V) bool {
_, found := m[key]
return found
}
// ValueInSlice returns true if key is in list.
func ValueInSlice[T comparable](key T, list []T) bool {
for _, entry := range list {
if entry == key {
return true
}
}
return false
}
// StringPrefixInSlice returns true if any element in the list has the given prefix.
func StringPrefixInSlice(key string, list []string) bool {
for _, entry := range list {
if strings.HasPrefix(entry, key) {
return true
}
}
return false
}
// RemoveElementsFromSlice returns a slice equivalent to removing the given elements from the given list.
// Elements not present in the list are ignored.
func RemoveElementsFromSlice[T comparable](list []T, elements ...T) []T {
for i := len(elements) - 1; i >= 0; i-- {
element := elements[i]
match := false
for j := len(list) - 1; j >= 0; j-- {
if element == list[j] {
match = true
list = append(list[:j], list[j+1:]...)
break
}
}
if match {
elements = append(elements[:i], elements[i+1:]...)
}
}
return list
}
// StringHasPrefix returns true if value has one of the supplied prefixes.
func StringHasPrefix(value string, prefixes ...string) bool {
for _, prefix := range prefixes {
if strings.HasPrefix(value, prefix) {
return true
}
}
return false
}
// IsTrue returns true if value is "true", "1", "yes" or "on" (case insensitive).
func IsTrue(value string) bool {
return ValueInSlice(strings.ToLower(value), []string{"true", "1", "yes", "on"})
}
// IsTrueOrEmpty returns true if value is empty or if IsTrue() returns true.
func IsTrueOrEmpty(value string) bool {
return value == "" || IsTrue(value)
}
// IsFalse returns true if value is "false", "0", "no" or "off" (case insensitive).
func IsFalse(value string) bool {
return ValueInSlice(strings.ToLower(value), []string{"false", "0", "no", "off"})
}
// IsFalseOrEmpty returns true if value is empty or if IsFalse() returns true.
func IsFalseOrEmpty(value string) bool {
return value == "" || IsFalse(value)
}
func IsUserConfig(key string) bool {
return strings.HasPrefix(key, "user.")
}
// StringMapHasStringKey returns true if any of the supplied keys are present in the map.
func StringMapHasStringKey(m map[string]string, keys ...string) bool {
for _, k := range keys {
_, ok := m[k]
if ok {
return true
}
}
return false
}
func IsBlockdev(fm os.FileMode) bool {
return ((fm&os.ModeDevice != 0) && (fm&os.ModeCharDevice == 0))
}
func IsBlockdevPath(pathName string) bool {
sb, err := os.Stat(pathName)
if err != nil {
return false
}
fm := sb.Mode()
return ((fm&os.ModeDevice != 0) && (fm&os.ModeCharDevice == 0))
}
// DeepCopy copies src to dest by using encoding/gob so its not that fast.
func DeepCopy(src, dest any) error {
buff := new(bytes.Buffer)
enc := gob.NewEncoder(buff)
dec := gob.NewDecoder(buff)
err := enc.Encode(src)
if err != nil {
return err
}
err = dec.Decode(dest)
if err != nil {
return err
}
return nil
}
func RunningInUserNS() bool {
file, err := os.Open("/proc/self/uid_map")
if err != nil {
return false
}
defer func() { _ = file.Close() }()
buf := bufio.NewReader(file)
l, _, err := buf.ReadLine()
if err != nil {
return false
}
line := string(l)
var a, b, c int64
_, _ = fmt.Sscanf(line, "%d %d %d", &a, &b, &c)
if a == 0 && b == 0 && c == 4294967295 {
return false
}
return true
}
// Spawn the editor with a temporary YAML file for editing configs.
func TextEditor(inPath string, inContent []byte) ([]byte, error) {
var f *os.File
var err error
var path string
// Detect the text editor to use
editor := os.Getenv("VISUAL")
if editor == "" {
editor = os.Getenv("EDITOR")
if editor == "" {
for _, p := range []string{"editor", "vi", "emacs", "nano"} {
_, err := exec.LookPath(p)
if err == nil {
editor = p
break
}
}
if editor == "" {
return []byte{}, fmt.Errorf("No text editor found, please set the EDITOR environment variable")
}
}
}
if inPath == "" {
// If provided input, create a new file
f, err = os.CreateTemp("", "lxd_editor_")
if err != nil {
return []byte{}, err
}
revert := revert.New()
defer revert.Fail()
revert.Add(func() {
_ = f.Close()
_ = os.Remove(f.Name())
})
err = os.Chmod(f.Name(), 0600)
if err != nil {
return []byte{}, err
}
_, err = f.Write(inContent)
if err != nil {
return []byte{}, err
}
err = f.Close()
if err != nil {
return []byte{}, err
}
path = fmt.Sprintf("%s.yaml", f.Name())
err = os.Rename(f.Name(), path)
if err != nil {
return []byte{}, err
}
revert.Success()
revert.Add(func() { _ = os.Remove(path) })
} else {
path = inPath
}
cmdParts := strings.Fields(editor)
cmd := exec.Command(cmdParts[0], append(cmdParts[1:], path)...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err = cmd.Run()
if err != nil {
return []byte{}, err
}
content, err := os.ReadFile(path)
if err != nil {
return []byte{}, err
}
return content, nil
}
func ParseMetadata(metadata any) (map[string]any, error) {
newMetadata := make(map[string]any)
s := reflect.ValueOf(metadata)
if !s.IsValid() {
return nil, nil
}
if s.Kind() == reflect.Map {
for _, k := range s.MapKeys() {
if k.Kind() != reflect.String {
return nil, fmt.Errorf("Invalid metadata provided (key isn't a string)")
}
newMetadata[k.String()] = s.MapIndex(k).Interface()
}
} else if s.Kind() == reflect.Ptr && !s.Elem().IsValid() {
return nil, nil
} else {
return nil, fmt.Errorf("Invalid metadata provided (type isn't a map)")
}
return newMetadata, nil
}
// RemoveDuplicatesFromString removes all duplicates of the string 'sep'
// from the specified string 's'. Leading and trailing occurrences of sep
// are NOT removed (duplicate leading/trailing are). Performs poorly if
// there are multiple consecutive redundant separators.
func RemoveDuplicatesFromString(s string, sep string) string {
dup := sep + sep
for s = strings.Replace(s, dup, sep, -1); strings.Contains(s, dup); s = strings.Replace(s, dup, sep, -1) {
}
return s
}
// RunError is the error from the RunCommand family of functions.
type RunError struct {
cmd string
args []string
err error
stdout *bytes.Buffer
stderr *bytes.Buffer
}
func (e RunError) Error() string {
if e.stderr.Len() == 0 {
return fmt.Sprintf("Failed to run: %s %s: %v", e.cmd, strings.Join(e.args, " "), e.err)
}
return fmt.Sprintf("Failed to run: %s %s: %v (%s)", e.cmd, strings.Join(e.args, " "), e.err, strings.TrimSpace(e.stderr.String()))
}
func (e RunError) Unwrap() error {
return e.err
}
// StdOut returns the stdout buffer.
func (e RunError) StdOut() *bytes.Buffer {
return e.stdout
}
// StdErr returns the stdout buffer.
func (e RunError) StdErr() *bytes.Buffer {
return e.stderr
}
// NewRunError returns new RunError.