-
-
Notifications
You must be signed in to change notification settings - Fork 156
/
instance_utils.go
1259 lines (1028 loc) · 36 KB
/
instance_utils.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 instance
import (
"bytes"
"context"
"crypto/rand"
"database/sql"
"fmt"
"math/big"
"net/http"
"os"
"path/filepath"
"slices"
"strconv"
"strings"
"time"
"github.com/flosch/pongo2"
"github.com/google/uuid"
liblxc "github.com/lxc/go-lxc"
"github.com/lxc/incus/v6/client"
"github.com/lxc/incus/v6/internal/instance"
"github.com/lxc/incus/v6/internal/migration"
"github.com/lxc/incus/v6/internal/revert"
"github.com/lxc/incus/v6/internal/server/backup"
"github.com/lxc/incus/v6/internal/server/db"
"github.com/lxc/incus/v6/internal/server/db/cluster"
deviceConfig "github.com/lxc/incus/v6/internal/server/device/config"
"github.com/lxc/incus/v6/internal/server/instance/instancetype"
"github.com/lxc/incus/v6/internal/server/instance/operationlock"
"github.com/lxc/incus/v6/internal/server/seccomp"
"github.com/lxc/incus/v6/internal/server/state"
"github.com/lxc/incus/v6/internal/server/sys"
localUtil "github.com/lxc/incus/v6/internal/server/util"
internalUtil "github.com/lxc/incus/v6/internal/util"
"github.com/lxc/incus/v6/internal/version"
"github.com/lxc/incus/v6/shared/api"
"github.com/lxc/incus/v6/shared/idmap"
"github.com/lxc/incus/v6/shared/logger"
"github.com/lxc/incus/v6/shared/osarch"
"github.com/lxc/incus/v6/shared/util"
"github.com/lxc/incus/v6/shared/validate"
)
// ValidDevices is linked from instance/drivers.validDevices to validate device config.
var ValidDevices func(state *state.State, p api.Project, instanceType instancetype.Type, localDevices deviceConfig.Devices, expandedDevices deviceConfig.Devices) error
// Load is linked from instance/drivers.load to allow different instance types to be loaded.
var Load func(s *state.State, args db.InstanceArgs, p api.Project) (Instance, error)
// Create is linked from instance/drivers.create to allow difference instance types to be created.
// Returns a revert fail function that can be used to undo this function if a subsequent step fails.
var Create func(s *state.State, args db.InstanceArgs, p api.Project) (Instance, revert.Hook, error)
func exclusiveConfigKeys(key1 string, key2 string, config map[string]string) (val string, ok bool, err error) {
if config[key1] != "" && config[key2] != "" {
return "", false, fmt.Errorf("Mutually exclusive keys %s and %s are set", key1, key2)
}
val, ok = config[key1]
if ok {
return
}
val, ok = config[key2]
if ok {
return
}
return "", false, nil
}
// ValidConfig validates an instance's config.
func ValidConfig(sysOS *sys.OS, config map[string]string, expanded bool, instanceType instancetype.Type) error {
if config == nil {
return nil
}
for k, v := range config {
if instanceType == instancetype.Any && !expanded && strings.HasPrefix(k, instance.ConfigVolatilePrefix) {
return fmt.Errorf("Volatile keys can only be set on instances")
}
if instanceType == instancetype.Any && !expanded && strings.HasPrefix(k, "image.") {
return fmt.Errorf("Image keys can only be set on instances")
}
err := validConfigKey(sysOS, k, v, instanceType)
if err != nil {
return err
}
}
_, rawSeccomp := config["raw.seccomp"]
_, isAllow, err := exclusiveConfigKeys("security.syscalls.allow", "security.syscalls.whitelist", config)
if err != nil {
return err
}
_, isDeny, err := exclusiveConfigKeys("security.syscalls.deny", "security.syscalls.blacklist", config)
if err != nil {
return err
}
val, _, err := exclusiveConfigKeys("security.syscalls.deny_default", "security.syscalls.blacklist_default", config)
if err != nil {
return err
}
isDenyDefault := util.IsTrue(val)
val, _, err = exclusiveConfigKeys("security.syscalls.deny_compat", "security.syscalls.blacklist_compat", config)
if err != nil {
return err
}
isDenyCompat := util.IsTrue(val)
if rawSeccomp && (isAllow || isDeny || isDenyDefault || isDenyCompat) {
return fmt.Errorf("raw.seccomp is mutually exclusive with security.syscalls*")
}
if isAllow && (isDeny || isDenyDefault || isDenyCompat) {
return fmt.Errorf("security.syscalls.allow is mutually exclusive with security.syscalls.deny*")
}
_, err = seccomp.SyscallInterceptMountFilter(config)
if err != nil {
return err
}
if expanded && (util.IsFalseOrEmpty(config["security.privileged"])) && sysOS.IdmapSet == nil {
return fmt.Errorf("No uid/gid allocation configured. In this mode, only privileged containers are supported")
}
if util.IsTrue(config["security.privileged"]) && util.IsTrue(config["nvidia.runtime"]) {
return fmt.Errorf("nvidia.runtime is incompatible with privileged containers")
}
return nil
}
func validConfigKey(os *sys.OS, key string, value string, instanceType instancetype.Type) error {
f, err := instance.ConfigKeyChecker(key, instanceType.ToAPI())
if err != nil {
return err
}
if err = f(value); err != nil {
return err
}
if key == "raw.lxc" {
return lxcValidConfig(value)
}
if key == "security.syscalls.deny_compat" || key == "security.syscalls.blacklist_compat" {
for _, arch := range os.Architectures {
if arch == osarch.ARCH_64BIT_INTEL_X86 ||
arch == osarch.ARCH_64BIT_ARMV8_LITTLE_ENDIAN ||
arch == osarch.ARCH_64BIT_POWERPC_BIG_ENDIAN {
return nil
}
}
return fmt.Errorf("%s isn't supported on this architecture", key)
}
return nil
}
func lxcParseRawLXC(line string) (string, string, error) {
// Ignore empty lines
if len(line) == 0 {
return "", "", nil
}
// Skip space {"\t", " "}
line = strings.TrimLeft(line, "\t ")
// Ignore comments
if strings.HasPrefix(line, "#") {
return "", "", nil
}
// Ensure the format is valid
membs := strings.SplitN(line, "=", 2)
if len(membs) != 2 {
return "", "", fmt.Errorf("Invalid raw.lxc line: %s", line)
}
key := strings.ToLower(strings.Trim(membs[0], " \t"))
val := strings.Trim(membs[1], " \t")
return key, val, nil
}
func lxcValidConfig(rawLxc string) error {
for _, line := range strings.Split(rawLxc, "\n") {
key, _, err := lxcParseRawLXC(line)
if err != nil {
return err
}
if key == "" {
continue
}
// block some keys
if key == "lxc.logfile" || key == "lxc.log.file" {
return fmt.Errorf("Setting lxc.logfile is not allowed")
}
if key == "lxc.syslog" || key == "lxc.log.syslog" {
return fmt.Errorf("Setting lxc.log.syslog is not allowed")
}
if key == "lxc.ephemeral" {
return fmt.Errorf("Setting lxc.ephemeral is not allowed")
}
if strings.HasPrefix(key, "lxc.prlimit.") {
return fmt.Errorf(`Process limits should be set via ` +
`"limits.kernel.[limit name]" and not ` +
`directly via "lxc.prlimit.[limit name]"`)
}
networkKeyPrefix := "lxc.net."
if !liblxc.RuntimeLiblxcVersionAtLeast(liblxc.Version(), 2, 1, 0) {
networkKeyPrefix = "lxc.network."
}
if strings.HasPrefix(key, networkKeyPrefix) {
fields := strings.Split(key, ".")
if !liblxc.RuntimeLiblxcVersionAtLeast(liblxc.Version(), 2, 1, 0) {
// lxc.network.X.ipv4 or lxc.network.X.ipv6
if len(fields) == 4 && slices.Contains([]string{"ipv4", "ipv6"}, fields[3]) {
continue
}
// lxc.network.X.ipv4.gateway or lxc.network.X.ipv6.gateway
if len(fields) == 5 && slices.Contains([]string{"ipv4", "ipv6"}, fields[3]) && fields[4] == "gateway" {
continue
}
} else {
// lxc.net.X.ipv4.address or lxc.net.X.ipv6.address
if len(fields) == 5 && slices.Contains([]string{"ipv4", "ipv6"}, fields[3]) && fields[4] == "address" {
continue
}
// lxc.net.X.ipv4.gateway or lxc.net.X.ipv6.gateway
if len(fields) == 5 && slices.Contains([]string{"ipv4", "ipv6"}, fields[3]) && fields[4] == "gateway" {
continue
}
}
return fmt.Errorf("Only interface-specific ipv4/ipv6 %s keys are allowed", networkKeyPrefix)
}
}
return nil
}
// AllowedUnprivilegedOnlyMap checks that root user is not mapped into instance.
func AllowedUnprivilegedOnlyMap(rawIdmap string) error {
rawMaps, err := idmap.NewSetFromIncusIDMap(rawIdmap)
if err != nil {
return err
}
for _, ent := range rawMaps.Entries {
if ent.HostID == 0 {
return fmt.Errorf("Cannot map root user into container as the server was configured to only allow unprivileged containers")
}
}
return nil
}
// LoadByID loads an instance by ID.
func LoadByID(s *state.State, id int) (Instance, error) {
var project string
var name string
err := s.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
var err error
// Get the DB record
project, name, err = tx.GetInstanceProjectAndName(ctx, id)
if err != nil {
return fmt.Errorf("Failed getting instance project and name: %w", err)
}
return nil
})
if err != nil {
return nil, err
}
return LoadByProjectAndName(s, project, name)
}
// LoadInstanceDatabaseObject loads a db.Instance object, accounting for snapshots.
func LoadInstanceDatabaseObject(ctx context.Context, tx *db.ClusterTx, project, name string) (*cluster.Instance, error) {
var container *cluster.Instance
var err error
if strings.Contains(name, instance.SnapshotDelimiter) {
parts := strings.SplitN(name, instance.SnapshotDelimiter, 2)
instanceName := parts[0]
snapshotName := parts[1]
instance, err := cluster.GetInstance(ctx, tx.Tx(), project, instanceName)
if err != nil {
return nil, fmt.Errorf("Failed to fetch instance %q in project %q: %w", name, project, err)
}
snapshot, err := cluster.GetInstanceSnapshot(ctx, tx.Tx(), project, instanceName, snapshotName)
if err != nil {
return nil, fmt.Errorf("Failed to fetch snapshot %q of instance %q in project %q: %w", snapshotName, instanceName, project, err)
}
c := snapshot.ToInstance(instance.Name, instance.Node, instance.Type, instance.Architecture)
container = &c
} else {
container, err = cluster.GetInstance(ctx, tx.Tx(), project, name)
if err != nil {
return nil, fmt.Errorf("Failed to fetch instance %q in project %q: %w", name, project, err)
}
}
return container, nil
}
// LoadByProjectAndName loads an instance by project and name.
func LoadByProjectAndName(s *state.State, projectName string, instanceName string) (Instance, error) {
// Get the DB record
var args db.InstanceArgs
var p *api.Project
err := s.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
proj, err := cluster.GetProject(ctx, tx.Tx(), projectName)
if err != nil {
return err
}
p, err = proj.ToAPI(ctx, tx.Tx())
if err != nil {
return err
}
inst, err := LoadInstanceDatabaseObject(ctx, tx, projectName, instanceName)
if err != nil {
return err
}
instArgs, err := tx.InstancesToInstanceArgs(ctx, true, *inst)
if err != nil {
return err
}
args = instArgs[inst.ID]
return nil
})
if err != nil {
return nil, err
}
inst, err := Load(s, args, *p)
if err != nil {
return nil, fmt.Errorf("Failed to load instance: %w", err)
}
return inst, nil
}
// LoadNodeAll loads all instances on this server.
func LoadNodeAll(s *state.State, instanceType instancetype.Type) ([]Instance, error) {
var err error
var instances []Instance
filter := cluster.InstanceFilter{Type: instanceType.Filter()}
if s.ServerName != "" {
filter.Node = &s.ServerName
}
err = s.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
return tx.InstanceList(ctx, func(dbInst db.InstanceArgs, p api.Project) error {
inst, err := Load(s, dbInst, p)
if err != nil {
return fmt.Errorf("Failed loading instance %q in project %q: %w", dbInst.Name, dbInst.Project, err)
}
instances = append(instances, inst)
return nil
}, filter)
})
if err != nil {
return nil, err
}
return instances, nil
}
// LoadFromBackup loads from a mounted instance's backup file.
// If applyProfiles is false, then the profiles property will be cleared to prevent profile enrichment from DB.
// Then the expanded config and expanded devices from the backup file will be applied to the local config and
// local devices respectively. This is done to allow an expanded instance to be returned without needing the DB.
func LoadFromBackup(s *state.State, projectName string, instancePath string, applyProfiles bool) (Instance, error) {
var inst Instance
backupYamlPath := filepath.Join(instancePath, "backup.yaml")
backupConf, err := backup.ParseConfigYamlFile(backupYamlPath)
if err != nil {
return nil, fmt.Errorf("Failed parsing instance backup file from %q: %w", backupYamlPath, err)
}
instDBArgs, err := backup.ConfigToInstanceDBArgs(s, backupConf, projectName, applyProfiles)
if err != nil {
return nil, err
}
if !applyProfiles {
// Stop instance.Load() from expanding profile config from DB, and apply expanded config from
// backup file to local config. This way we can still see the devices even if DB not available.
instDBArgs.Config = backupConf.Container.ExpandedConfig
instDBArgs.Devices = deviceConfig.NewDevices(backupConf.Container.ExpandedDevices)
}
var p *api.Project
err = s.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
proj, err := cluster.GetProject(ctx, tx.Tx(), projectName)
if err != nil {
return err
}
p, err = proj.ToAPI(ctx, tx.Tx())
if err != nil {
return err
}
return nil
})
if err != nil {
return nil, err
}
inst, err = Load(s, *instDBArgs, *p)
if err != nil {
return nil, fmt.Errorf("Failed loading instance from backup file %q: %w", backupYamlPath, err)
}
return inst, nil
}
// DeviceNextInterfaceHWAddr generates a random MAC address.
func DeviceNextInterfaceHWAddr() (string, error) {
// Generate a new random MAC address using the usual prefix
ret := bytes.Buffer{}
for _, c := range "00:16:3e:xx:xx:xx" {
if c == 'x' {
c, err := rand.Int(rand.Reader, big.NewInt(16))
if err != nil {
return "", err
}
ret.WriteString(fmt.Sprintf("%x", c.Int64()))
} else {
ret.WriteString(string(c))
}
}
return ret.String(), nil
}
// BackupLoadByName load an instance backup from the database.
func BackupLoadByName(s *state.State, project, name string) (*backup.InstanceBackup, error) {
var args db.InstanceBackup
// Get the backup database record
err := s.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
var err error
args, err = tx.GetInstanceBackup(ctx, project, name)
return err
})
if err != nil {
return nil, err
}
// Load the instance it belongs to
instance, err := LoadByID(s, args.InstanceID)
if err != nil {
return nil, err
}
return backup.NewInstanceBackup(s, instance, args.ID, name, args.CreationDate, args.ExpiryDate, args.InstanceOnly, args.OptimizedStorage), nil
}
// ResolveImage takes an instance source and returns a hash suitable for instance creation or download.
func ResolveImage(ctx context.Context, tx *db.ClusterTx, projectName string, source api.InstanceSource) (string, error) {
if source.Fingerprint != "" {
return source.Fingerprint, nil
}
if source.Alias != "" {
if source.Server != "" {
return source.Alias, nil
}
_, alias, err := tx.GetImageAlias(ctx, projectName, source.Alias, true)
if err != nil {
return "", err
}
return alias.Target, nil
}
if source.Properties != nil {
if source.Server != "" {
return "", fmt.Errorf("Property match is only supported for local images")
}
hashes, err := tx.GetImagesFingerprints(ctx, projectName, false)
if err != nil {
return "", err
}
var image *api.Image
for _, imageHash := range hashes {
_, img, err := tx.GetImageByFingerprintPrefix(ctx, imageHash, cluster.ImageFilter{Project: &projectName})
if err != nil {
continue
}
if image != nil && img.CreatedAt.Before(image.CreatedAt) {
continue
}
match := true
for key, value := range source.Properties {
if img.Properties[key] != value {
match = false
break
}
}
if !match {
continue
}
image = img
}
if image != nil {
return image.Fingerprint, nil
}
return "", fmt.Errorf("No matching image could be found")
}
return "", fmt.Errorf("Must specify one of alias, fingerprint or properties for init from image")
}
// SuitableArchitectures returns a slice of architecture ids based on an instance create request.
//
// An empty list indicates that the request may be handled by any architecture.
// A nil list indicates that we can't tell at this stage, typically for private images.
func SuitableArchitectures(ctx context.Context, s *state.State, tx *db.ClusterTx, projectName string, sourceInst *cluster.Instance, sourceImageRef string, req api.InstancesPost) ([]int, error) {
// Handle cases where the architecture is already provided.
if slices.Contains([]string{"migration", "none"}, req.Source.Type) && req.Architecture != "" {
id, err := osarch.ArchitectureId(req.Architecture)
if err != nil {
return nil, err
}
return []int{id}, nil
}
// For migration, an architecture must be specified in the req.
if req.Source.Type == "migration" && req.Architecture == "" {
return nil, api.StatusErrorf(http.StatusBadRequest, "An architecture must be specified in migration requests")
}
// For none, allow any architecture.
if req.Source.Type == "none" {
return []int{}, nil
}
// For copy, always use the source architecture.
if req.Source.Type == "copy" {
return []int{sourceInst.Architecture}, nil
}
// For image, things get a bit more complicated.
if req.Source.Type == "image" {
// Handle local images.
if req.Source.Server == "" {
_, img, err := tx.GetImageByFingerprintPrefix(ctx, sourceImageRef, cluster.ImageFilter{Project: &projectName})
if err != nil {
return nil, err
}
id, err := osarch.ArchitectureId(img.Architecture)
if err != nil {
return nil, err
}
return []int{id}, nil
}
// Handle remote images.
if req.Source.Server != "" {
if req.Source.Secret != "" {
// We can't retrieve a private image, defer to later processing.
return nil, nil
}
var err error
var remote incus.ImageServer
if slices.Contains([]string{"", "incus", "lxd"}, req.Source.Protocol) {
// Remote image server.
remote, err = incus.ConnectPublicIncus(req.Source.Server, &incus.ConnectionArgs{
TLSServerCert: req.Source.Certificate,
UserAgent: version.UserAgent,
Proxy: s.Proxy,
CachePath: s.OS.CacheDir,
CacheExpiry: time.Hour,
})
if err != nil {
return nil, err
}
} else if req.Source.Protocol == "simplestreams" {
// Remote simplestreams image server.
remote, err = incus.ConnectSimpleStreams(req.Source.Server, &incus.ConnectionArgs{
TLSServerCert: req.Source.Certificate,
UserAgent: version.UserAgent,
Proxy: s.Proxy,
CachePath: s.OS.CacheDir,
CacheExpiry: time.Hour,
})
if err != nil {
return nil, err
}
} else {
return nil, api.StatusErrorf(http.StatusBadRequest, "Unsupported remote image server protocol %q", req.Source.Protocol)
}
// Look for a matching alias.
entries, err := remote.GetImageAliasArchitectures(string(req.Type), sourceImageRef)
if err != nil {
// Look for a matching image by fingerprint.
img, _, err := remote.GetImage(sourceImageRef)
if err != nil {
return nil, err
}
id, err := osarch.ArchitectureId(img.Architecture)
if err != nil {
return nil, err
}
return []int{id}, nil
}
architectures := []int{}
for arch := range entries {
id, err := osarch.ArchitectureId(arch)
if err != nil {
return nil, err
}
architectures = append(architectures, id)
}
return architectures, nil
}
}
// No other known types
return nil, api.StatusErrorf(http.StatusBadRequest, "Unknown instance source type %q", req.Source.Type)
}
// ValidName validates an instance name. There are different validation rules for instance snapshot names
// so it takes an argument indicating whether the name is to be used for a snapshot or not.
func ValidName(instanceName string, isSnapshot bool) error {
if isSnapshot {
parentName, snapshotName, _ := api.GetParentAndSnapshotName(instanceName)
err := validate.IsHostname(parentName)
if err != nil {
return fmt.Errorf("Invalid instance name: %w", err)
}
// Snapshot part is more flexible, but doesn't allow space or / character.
if strings.ContainsAny(snapshotName, " /") {
return fmt.Errorf("Invalid instance snapshot name: Cannot contain space or / characters")
}
} else {
if strings.Contains(instanceName, instance.SnapshotDelimiter) {
return fmt.Errorf("The character %q is reserved for snapshots", instance.SnapshotDelimiter)
}
err := validate.IsHostname(instanceName)
if err != nil {
return fmt.Errorf("Invalid instance name: %w", err)
}
}
return nil
}
// CreateInternal creates an instance record and storage volume record in the database and sets up devices.
// Accepts a reverter that revert steps this function does will be added to. It is up to the caller to
// call the revert's Fail() or Success() function as needed.
// Returns the created instance, along with a "create" operation lock that needs to be marked as Done once the
// instance is fully completed, and a revert fail function that can be used to undo this function if a subsequent
// step fails.
func CreateInternal(s *state.State, args db.InstanceArgs, clearLogDir bool, checkArchitecture bool) (Instance, *operationlock.InstanceOperation, revert.Hook, error) {
revert := revert.New()
defer revert.Fail()
// Check instance type requested is supported by this machine.
err := s.InstanceTypes[args.Type]
if err != nil {
return nil, nil, nil, fmt.Errorf("Instance type %q is not supported on this server: %w", args.Type, err)
}
// Set default values.
if args.Project == "" {
args.Project = api.ProjectDefaultName
}
if args.Profiles == nil {
err = s.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
args.Profiles, err = tx.GetProfiles(ctx, args.Project, []string{"default"})
return err
})
if err != nil {
return nil, nil, nil, fmt.Errorf("Failed to get default profile for new instance")
}
}
if args.Config == nil {
args.Config = map[string]string{}
}
if args.BaseImage != "" {
args.Config["volatile.base_image"] = args.BaseImage
}
if args.Config["volatile.uuid"] == "" {
args.Config["volatile.uuid"] = uuid.New().String()
}
args.Config["volatile.uuid.generation"] = args.Config["volatile.uuid"]
if args.Devices == nil {
args.Devices = deviceConfig.Devices{}
}
if args.Architecture == 0 {
args.Architecture = s.OS.Architectures[0]
}
err = ValidName(args.Name, args.Snapshot)
if err != nil {
return nil, nil, nil, err
}
if !args.Snapshot {
// Unset expiry date since instances don't expire.
args.ExpiryDate = time.Time{}
// Generate a cloud-init instance-id if not provided.
//
// This is generated here rather than in startCommon as only new
// instances or those which get modified should receive an instance-id.
// Existing instances will keep using their instance name as instance-id to
// avoid triggering cloud-init on upgrade.
if args.Config["volatile.cloud-init.instance-id"] == "" {
args.Config["volatile.cloud-init.instance-id"] = uuid.New().String()
}
}
// Validate instance config.
err = ValidConfig(s.OS, args.Config, false, args.Type)
if err != nil {
return nil, nil, nil, err
}
// Leave validating devices to Create function call below.
// Validate architecture.
_, err = osarch.ArchitectureName(args.Architecture)
if err != nil {
return nil, nil, nil, err
}
if checkArchitecture && !slices.Contains(s.OS.Architectures, args.Architecture) {
return nil, nil, nil, fmt.Errorf("Requested architecture isn't supported by this host")
}
var profiles []string
err = s.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
// Validate profiles.
profiles, err = tx.GetProfileNames(ctx, args.Project)
return err
})
if err != nil {
return nil, nil, nil, err
}
checkedProfiles := map[string]bool{}
for _, profile := range args.Profiles {
if !slices.Contains(profiles, profile.Name) {
return nil, nil, nil, fmt.Errorf("Requested profile %q doesn't exist", profile.Name)
}
if checkedProfiles[profile.Name] {
return nil, nil, nil, fmt.Errorf("Duplicate profile found in request")
}
checkedProfiles[profile.Name] = true
}
if args.CreationDate.IsZero() {
args.CreationDate = time.Now().UTC()
}
if args.LastUsedDate.IsZero() {
args.LastUsedDate = time.Unix(0, 0).UTC()
}
// Prevent concurrent create requests for same instance.
op, err := operationlock.Create(args.Project, args.Name, operationlock.ActionCreate, false, false)
if err != nil {
return nil, nil, nil, err
}
revert.Add(func() { op.Done(err) })
var dbInst cluster.Instance
var p *api.Project
err = s.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
proj, err := cluster.GetProject(ctx, tx.Tx(), args.Project)
if err != nil {
return err
}
p, err = proj.ToAPI(ctx, tx.Tx())
if err != nil {
return err
}
devices, err := cluster.APIToDevices(args.Devices.CloneNative())
if err != nil {
return err
}
if args.Snapshot {
parts := strings.SplitN(args.Name, instance.SnapshotDelimiter, 2)
instanceName := parts[0]
snapshotName := parts[1]
instance, err := cluster.GetInstance(ctx, tx.Tx(), args.Project, instanceName)
if err != nil {
return fmt.Errorf("Get instance %q in project %q", instanceName, args.Project)
}
snapshot := cluster.InstanceSnapshot{
Project: args.Project,
Instance: instanceName,
Name: snapshotName,
CreationDate: args.CreationDate,
Stateful: args.Stateful,
Description: args.Description,
ExpiryDate: sql.NullTime{Time: args.ExpiryDate, Valid: true},
}
id, err := cluster.CreateInstanceSnapshot(ctx, tx.Tx(), snapshot)
if err != nil {
return fmt.Errorf("Add snapshot info to the database: %w", err)
}
err = cluster.CreateInstanceSnapshotConfig(ctx, tx.Tx(), id, args.Config)
if err != nil {
return err
}
err = cluster.CreateInstanceSnapshotDevices(ctx, tx.Tx(), id, devices)
if err != nil {
return err
}
// Read back the snapshot, to get ID and creation time.
s, err := cluster.GetInstanceSnapshot(ctx, tx.Tx(), args.Project, instanceName, snapshotName)
if err != nil {
return fmt.Errorf("Fetch created snapshot from the database: %w", err)
}
dbInst = s.ToInstance(instance.Name, instance.Node, instance.Type, instance.Architecture)
newArgs, err := tx.InstancesToInstanceArgs(ctx, false, dbInst)
if err != nil {
return err
}
// Populate profile info that was already loaded.
newInstArgs := newArgs[dbInst.ID]
newInstArgs.Profiles = args.Profiles
args = newInstArgs
return nil
}
// Create the instance entry.
dbInst = cluster.Instance{
Project: args.Project,
Name: args.Name,
Node: s.ServerName,
Type: args.Type,
Snapshot: args.Snapshot,
Architecture: args.Architecture,
Ephemeral: args.Ephemeral,
CreationDate: args.CreationDate,
Stateful: args.Stateful,
LastUseDate: sql.NullTime{Time: args.LastUsedDate, Valid: true},
Description: args.Description,
ExpiryDate: sql.NullTime{Time: args.ExpiryDate, Valid: true},
}
instanceID, err := cluster.CreateInstance(ctx, tx.Tx(), dbInst)
if err != nil {
return fmt.Errorf("Add instance info to the database: %w", err)
}
err = cluster.CreateInstanceDevices(ctx, tx.Tx(), instanceID, devices)
if err != nil {
return err
}
err = cluster.CreateInstanceConfig(ctx, tx.Tx(), instanceID, args.Config)
if err != nil {
return err
}
profileNames := make([]string, 0, len(args.Profiles))
for _, profile := range args.Profiles {
profileNames = append(profileNames, profile.Name)
}
err = cluster.UpdateInstanceProfiles(ctx, tx.Tx(), int(instanceID), dbInst.Project, profileNames)
if err != nil {
return err
}
// Read back the instance, to get ID and creation time.
dbRow, err := cluster.GetInstance(ctx, tx.Tx(), args.Project, args.Name)
if err != nil {
return fmt.Errorf("Fetch created instance from the database: %w", err)
}
dbInst = *dbRow
if dbInst.ID < 1 {
return fmt.Errorf("Unexpected instance database ID %d: %w", dbInst.ID, err)
}
newArgs, err := tx.InstancesToInstanceArgs(ctx, false, dbInst)
if err != nil {
return err
}
// Populate profile info that was already loaded.
newInstArgs := newArgs[dbInst.ID]
newInstArgs.Profiles = args.Profiles
args = newInstArgs
return nil
})
if err != nil {
if err == db.ErrAlreadyDefined {
thing := "Instance"
if instance.IsSnapshot(args.Name) {
thing = "Snapshot"
}
return nil, nil, nil, fmt.Errorf("%s %q already exists", thing, args.Name)
}
return nil, nil, nil, err
}
revert.Add(func() {
_ = s.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
return tx.DeleteInstance(ctx, dbInst.Project, dbInst.Name)
})