/
instances_post.go
1273 lines (1056 loc) · 37.8 KB
/
instances_post.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 (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
petname "github.com/dustinkirkland/golang-petname"
"github.com/gorilla/websocket"
"github.com/lxc/lxd/lxd/archive"
"github.com/lxc/lxd/lxd/backup"
"github.com/lxc/lxd/lxd/cluster"
"github.com/lxc/lxd/lxd/db"
dbCluster "github.com/lxc/lxd/lxd/db/cluster"
"github.com/lxc/lxd/lxd/db/operationtype"
deviceConfig "github.com/lxc/lxd/lxd/device/config"
"github.com/lxc/lxd/lxd/instance"
"github.com/lxc/lxd/lxd/instance/instancetype"
"github.com/lxc/lxd/lxd/instance/operationlock"
"github.com/lxc/lxd/lxd/operations"
"github.com/lxc/lxd/lxd/project"
"github.com/lxc/lxd/lxd/request"
"github.com/lxc/lxd/lxd/response"
"github.com/lxc/lxd/lxd/revert"
"github.com/lxc/lxd/lxd/scriptlet"
"github.com/lxc/lxd/lxd/state"
storagePools "github.com/lxc/lxd/lxd/storage"
"github.com/lxc/lxd/shared"
"github.com/lxc/lxd/shared/api"
apiScriptlet "github.com/lxc/lxd/shared/api/scriptlet"
"github.com/lxc/lxd/shared/logger"
"github.com/lxc/lxd/shared/osarch"
"github.com/lxc/lxd/shared/version"
)
func ensureDownloadedImageFitWithinBudget(s *state.State, r *http.Request, op *operations.Operation, p api.Project, img *api.Image, imgAlias string, source api.InstanceSource, imgType string) (*api.Image, error) {
var autoUpdate bool
var err error
if p.Config["images.auto_update_cached"] != "" {
autoUpdate = shared.IsTrue(p.Config["images.auto_update_cached"])
} else {
autoUpdate = s.GlobalConfig.ImagesAutoUpdateCached()
}
var budget int64
err = s.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
budget, err = project.GetImageSpaceBudget(tx, p.Name)
return err
})
if err != nil {
return nil, err
}
imgDownloaded, err := ImageDownload(r, s, op, &ImageDownloadArgs{
Server: source.Server,
Protocol: source.Protocol,
Certificate: source.Certificate,
Secret: source.Secret,
Alias: imgAlias,
SetCached: true,
Type: imgType,
AutoUpdate: autoUpdate,
Public: false,
PreferCached: true,
ProjectName: p.Name,
Budget: budget,
})
if err != nil {
return nil, err
}
return imgDownloaded, nil
}
func createFromImage(s *state.State, r *http.Request, p api.Project, profiles []api.Profile, img *api.Image, imgAlias string, req *api.InstancesPost) response.Response {
if s.DB.Cluster.LocalNodeIsEvacuated() {
return response.Forbidden(fmt.Errorf("Cluster member is evacuated"))
}
dbType, err := instancetype.New(string(req.Type))
if err != nil {
return response.BadRequest(err)
}
run := func(op *operations.Operation) error {
args := db.InstanceArgs{
Project: p.Name,
Config: req.Config,
Type: dbType,
Description: req.Description,
Devices: deviceConfig.NewDevices(req.Devices),
Ephemeral: req.Ephemeral,
Name: req.Name,
Profiles: profiles,
}
if req.Source.Server != "" {
img, err = ensureDownloadedImageFitWithinBudget(s, r, op, p, img, imgAlias, req.Source, string(req.Type))
if err != nil {
return err
}
} else if img != nil {
err := ensureImageIsLocallyAvailable(s, r, img, args.Project, args.Type)
if err != nil {
return err
}
} else {
return fmt.Errorf("Image not provided for instance creation")
}
args.Architecture, err = osarch.ArchitectureId(img.Architecture)
if err != nil {
return err
}
return instanceCreateFromImage(s, r, img, args, op)
}
resources := map[string][]api.URL{}
resources["instances"] = []api.URL{*api.NewURL().Path(version.APIVersion, "instances", req.Name)}
if dbType == instancetype.Container {
resources["containers"] = resources["instances"]
}
op, err := operations.OperationCreate(s, p.Name, operations.OperationClassTask, operationtype.InstanceCreate, resources, nil, run, nil, nil, r)
if err != nil {
return response.InternalError(err)
}
return operations.OperationResponse(op)
}
func createFromNone(s *state.State, r *http.Request, projectName string, profiles []api.Profile, req *api.InstancesPost) response.Response {
if s.DB.Cluster.LocalNodeIsEvacuated() {
return response.Forbidden(fmt.Errorf("Cluster member is evacuated"))
}
dbType, err := instancetype.New(string(req.Type))
if err != nil {
return response.BadRequest(err)
}
args := db.InstanceArgs{
Project: projectName,
Config: req.Config,
Type: dbType,
Description: req.Description,
Devices: deviceConfig.NewDevices(req.Devices),
Ephemeral: req.Ephemeral,
Name: req.Name,
Profiles: profiles,
}
if req.Architecture != "" {
architecture, err := osarch.ArchitectureId(req.Architecture)
if err != nil {
return response.InternalError(err)
}
args.Architecture = architecture
}
run := func(op *operations.Operation) error {
_, err := instanceCreateAsEmpty(s, args)
return err
}
resources := map[string][]api.URL{}
resources["instances"] = []api.URL{*api.NewURL().Path(version.APIVersion, "instances", req.Name)}
if dbType == instancetype.Container {
resources["containers"] = resources["instances"]
}
op, err := operations.OperationCreate(s, projectName, operations.OperationClassTask, operationtype.InstanceCreate, resources, nil, run, nil, nil, r)
if err != nil {
return response.InternalError(err)
}
return operations.OperationResponse(op)
}
func createFromMigration(s *state.State, r *http.Request, projectName string, profiles []api.Profile, req *api.InstancesPost) response.Response {
if s.DB.Cluster.LocalNodeIsEvacuated() && r.Context().Value(request.CtxProtocol) != "cluster" {
return response.Forbidden(fmt.Errorf("Cluster member is evacuated"))
}
// Validate migration mode.
if req.Source.Mode != "pull" && req.Source.Mode != "push" {
return response.NotImplemented(fmt.Errorf("Mode %q not implemented", req.Source.Mode))
}
// Parse the architecture name
architecture, err := osarch.ArchitectureId(req.Architecture)
if err != nil {
return response.BadRequest(err)
}
dbType, err := instancetype.New(string(req.Type))
if err != nil {
return response.BadRequest(err)
}
if dbType != instancetype.Container && dbType != instancetype.VM {
return response.BadRequest(fmt.Errorf("Instance type not supported %q", req.Type))
}
// Prepare the instance creation request.
args := db.InstanceArgs{
Project: projectName,
Architecture: architecture,
BaseImage: req.Source.BaseImage,
Config: req.Config,
Type: dbType,
Devices: deviceConfig.NewDevices(req.Devices),
Description: req.Description,
Ephemeral: req.Ephemeral,
Name: req.Name,
Profiles: profiles,
Stateful: req.Stateful,
}
storagePool, storagePoolProfile, localRootDiskDeviceKey, localRootDiskDevice, resp := instanceFindStoragePool(s, projectName, req)
if resp != nil {
return resp
}
if storagePool == "" {
return response.BadRequest(fmt.Errorf("Can't find a storage pool for the instance to use"))
}
if localRootDiskDeviceKey == "" && storagePoolProfile == "" {
// Give the container it's own local root disk device with a pool property.
rootDev := map[string]string{}
rootDev["type"] = "disk"
rootDev["path"] = "/"
rootDev["pool"] = storagePool
if args.Devices == nil {
args.Devices = deviceConfig.Devices{}
}
// Make sure that we do not overwrite a device the user is currently using under the
// name "root".
rootDevName := "root"
for i := 0; i < 100; i++ {
if args.Devices[rootDevName] == nil {
break
}
rootDevName = fmt.Sprintf("root%d", i)
continue
}
args.Devices[rootDevName] = rootDev
} else if localRootDiskDeviceKey != "" && localRootDiskDevice["pool"] == "" {
args.Devices[localRootDiskDeviceKey]["pool"] = storagePool
}
var inst instance.Instance
var instOp *operationlock.InstanceOperation
var cleanup revert.Hook
// Decide if this is an internal cluster move request.
var clusterMoveSourceName string
if r != nil && isClusterNotification(r) {
if req.Source.Source == "" {
return response.BadRequest(fmt.Errorf("Source instance name must be provided for cluster member move"))
}
clusterMoveSourceName = req.Source.Source
}
// Early check for refresh and cluster same name move to check instance exists.
if req.Source.Refresh || (clusterMoveSourceName != "" && clusterMoveSourceName == req.Name) {
inst, err = instance.LoadByProjectAndName(s, projectName, req.Name)
if err != nil {
if response.IsNotFoundError(err) {
if clusterMoveSourceName != "" {
// Cluster move doesn't allow renaming as part of migration so fail here.
return response.SmartError(fmt.Errorf("Cluster move doesn't allow renaming"))
}
req.Source.Refresh = false
} else {
return response.SmartError(err)
}
}
}
revert := revert.New()
defer revert.Fail()
instanceOnly := req.Source.InstanceOnly || req.Source.ContainerOnly
if inst == nil {
_, err := storagePools.LoadByName(s, storagePool)
if err != nil {
return response.InternalError(err)
}
// Create the instance DB record for main instance.
// Note: At this stage we do not yet know if snapshots are going to be received and so we cannot
// create their DB records. This will be done if needed in the migrationSink.Do() function called
// as part of the operation below.
inst, instOp, cleanup, err = instance.CreateInternal(s, args, true)
if err != nil {
return response.InternalError(fmt.Errorf("Failed creating instance record: %w", err))
}
revert.Add(cleanup)
} else {
instOp, err = inst.LockExclusive()
if err != nil {
return response.SmartError(fmt.Errorf("Failed getting exclusive access to instance: %w", err))
}
}
revert.Add(func() { instOp.Done(err) })
push := false
var dialer *websocket.Dialer
if req.Source.Mode == "push" {
push = true
} else {
dialer, err = setupWebsocketDialer(req.Source.Certificate)
if err != nil {
return response.SmartError(fmt.Errorf("Failed setting up websocket dialer for migration sink connections: %w", err))
}
}
migrationArgs := migrationSinkArgs{
URL: req.Source.Operation,
Dialer: dialer,
Instance: inst,
Secrets: req.Source.Websockets,
Push: push,
Live: req.Source.Live,
InstanceOnly: instanceOnly,
ClusterMoveSourceName: clusterMoveSourceName,
Refresh: req.Source.Refresh,
}
sink, err := newMigrationSink(&migrationArgs)
if err != nil {
return response.InternalError(err)
}
// Copy reverter so far so we can use it inside run after this function has finished.
runRevert := revert.Clone()
run := func(op *operations.Operation) error {
defer runRevert.Fail()
sink.instance.SetOperation(op)
// And finally run the migration.
err = sink.Do(s, instOp)
if err != nil {
err = fmt.Errorf("Error transferring instance data: %w", err)
instOp.Done(err) // Complete operation that was created earlier, to release lock.
return err
}
instOp.Done(nil) // Complete operation that was created earlier, to release lock.
runRevert.Success()
return nil
}
resources := map[string][]api.URL{}
resources["instances"] = []api.URL{*api.NewURL().Path(version.APIVersion, "instances", req.Name)}
if dbType == instancetype.Container {
resources["containers"] = resources["instances"]
}
var op *operations.Operation
if push {
op, err = operations.OperationCreate(s, projectName, operations.OperationClassWebsocket, operationtype.InstanceCreate, resources, sink.Metadata(), run, nil, sink.Connect, r)
if err != nil {
return response.InternalError(err)
}
} else {
op, err = operations.OperationCreate(s, projectName, operations.OperationClassTask, operationtype.InstanceCreate, resources, nil, run, nil, nil, r)
if err != nil {
return response.InternalError(err)
}
}
revert.Success()
return operations.OperationResponse(op)
}
func createFromCopy(s *state.State, r *http.Request, projectName string, profiles []api.Profile, req *api.InstancesPost) response.Response {
if s.DB.Cluster.LocalNodeIsEvacuated() {
return response.Forbidden(fmt.Errorf("Cluster member is evacuated"))
}
if req.Source.Source == "" {
return response.BadRequest(fmt.Errorf("Must specify a source instance"))
}
sourceProject := req.Source.Project
if sourceProject == "" {
sourceProject = projectName
}
targetProject := projectName
source, err := instance.LoadByProjectAndName(s, sourceProject, req.Source.Source)
if err != nil {
return response.SmartError(err)
}
// Check if we need to redirect to migration
clustered, err := cluster.Enabled(s.DB.Node)
if err != nil {
return response.SmartError(err)
}
// When clustered, use the node name, otherwise use the hostname.
if clustered {
serverName := s.ServerName
if serverName != source.Location() {
// Check if we are copying from a ceph-based container.
_, rootDevice, _ := shared.GetRootDiskDevice(source.ExpandedDevices().CloneNative())
sourcePoolName := rootDevice["pool"]
destPoolName, _, _, _, resp := instanceFindStoragePool(s, targetProject, req)
if resp != nil {
return resp
}
if sourcePoolName != destPoolName {
// Redirect to migration
return clusterCopyContainerInternal(s, r, source, projectName, profiles, req)
}
_, pool, _, err := s.DB.Cluster.GetStoragePoolInAnyState(sourcePoolName)
if err != nil {
err = fmt.Errorf("Failed to fetch instance's pool info: %w", err)
return response.SmartError(err)
}
if pool.Driver != "ceph" {
// Redirect to migration
return clusterCopyContainerInternal(s, r, source, projectName, profiles, req)
}
}
}
// Config override
sourceConfig := source.LocalConfig()
if req.Config == nil {
req.Config = make(map[string]string)
}
for key, value := range sourceConfig {
if !shared.InstanceIncludeWhenCopying(key, false) {
logger.Debug("Skipping key from copy source", logger.Ctx{"key": key, "sourceProject": source.Project().Name, "sourceInstance": source.Name(), "project": targetProject, "instance": req.Name})
continue
}
_, exists := req.Config[key]
if exists {
continue
}
req.Config[key] = value
}
// Devices override
sourceDevices := source.LocalDevices()
if req.Devices == nil {
req.Devices = make(map[string]map[string]string)
}
for key, value := range sourceDevices {
_, exists := req.Devices[key]
if exists {
continue
}
req.Devices[key] = value
}
if req.Stateful {
sourceName, _, _ := api.GetParentAndSnapshotName(source.Name())
if sourceName != req.Name {
return response.BadRequest(fmt.Errorf("Instance name cannot be changed during stateful copy (%q to %q)", sourceName, req.Name))
}
}
dbType, err := instancetype.New(string(req.Type))
if err != nil {
return response.BadRequest(err)
}
// If type isn't specified, match the source type.
if req.Type == "" {
dbType = source.Type()
}
if dbType != instancetype.Any && dbType != source.Type() {
return response.BadRequest(fmt.Errorf("Instance type should not be specified or should match source type"))
}
args := db.InstanceArgs{
Project: targetProject,
Architecture: source.Architecture(),
BaseImage: req.Source.BaseImage,
Config: req.Config,
Type: source.Type(),
Description: req.Description,
Devices: deviceConfig.NewDevices(req.Devices),
Ephemeral: req.Ephemeral,
Name: req.Name,
Profiles: profiles,
Stateful: req.Stateful,
}
run := func(op *operations.Operation) error {
_, err := instanceCreateAsCopy(s, instanceCreateAsCopyOpts{
sourceInstance: source,
targetInstance: args,
instanceOnly: req.Source.InstanceOnly || req.Source.ContainerOnly,
refresh: req.Source.Refresh,
applyTemplateTrigger: true,
allowInconsistent: req.Source.AllowInconsistent,
}, op)
if err != nil {
return err
}
return nil
}
resources := map[string][]api.URL{}
resources["instances"] = []api.URL{*api.NewURL().Path(version.APIVersion, "instances", req.Name), *api.NewURL().Path(version.APIVersion, "instances", req.Source.Source)}
if dbType == instancetype.Container {
resources["containers"] = resources["instances"]
}
op, err := operations.OperationCreate(s, targetProject, operations.OperationClassTask, operationtype.InstanceCreate, resources, nil, run, nil, nil, r)
if err != nil {
return response.InternalError(err)
}
return operations.OperationResponse(op)
}
func createFromBackup(s *state.State, r *http.Request, projectName string, data io.Reader, pool string, instanceName string) response.Response {
revert := revert.New()
defer revert.Fail()
// Create temporary file to store uploaded backup data.
backupFile, err := os.CreateTemp(shared.VarPath("backups"), fmt.Sprintf("%s_", backup.WorkingDirPrefix))
if err != nil {
return response.InternalError(err)
}
defer func() { _ = os.Remove(backupFile.Name()) }()
revert.Add(func() { _ = backupFile.Close() })
// Stream uploaded backup data into temporary file.
_, err = io.Copy(backupFile, data)
if err != nil {
return response.InternalError(err)
}
// Detect squashfs compression and convert to tarball.
_, err = backupFile.Seek(0, io.SeekStart)
if err != nil {
return response.InternalError(err)
}
_, algo, decomArgs, err := shared.DetectCompressionFile(backupFile)
if err != nil {
return response.InternalError(err)
}
if algo == ".squashfs" {
// Pass the temporary file as program argument to the decompression command.
decomArgs := append(decomArgs, backupFile.Name())
// Create temporary file to store the decompressed tarball in.
tarFile, err := os.CreateTemp(shared.VarPath("backups"), fmt.Sprintf("%s_decompress_", backup.WorkingDirPrefix))
if err != nil {
return response.InternalError(err)
}
defer func() { _ = os.Remove(tarFile.Name()) }()
// Decompress to tarFile temporary file.
err = archive.ExtractWithFds(decomArgs[0], decomArgs[1:], nil, nil, s.OS, tarFile)
if err != nil {
return response.InternalError(err)
}
// We don't need the original squashfs file anymore.
_ = backupFile.Close()
_ = os.Remove(backupFile.Name())
// Replace the backup file handle with the handle to the tar file.
backupFile = tarFile
}
// Parse the backup information.
_, err = backupFile.Seek(0, io.SeekStart)
if err != nil {
return response.InternalError(err)
}
logger.Debug("Reading backup file info")
bInfo, err := backup.GetInfo(backupFile, s.OS, backupFile.Name())
if err != nil {
return response.BadRequest(err)
}
bInfo.Project = projectName
// Override pool.
if pool != "" {
bInfo.Pool = pool
}
// Override instance name.
if instanceName != "" {
bInfo.Name = instanceName
}
logger.Debug("Backup file info loaded", logger.Ctx{
"type": bInfo.Type,
"name": bInfo.Name,
"project": bInfo.Project,
"backend": bInfo.Backend,
"pool": bInfo.Pool,
"optimized": *bInfo.OptimizedStorage,
"snapshots": bInfo.Snapshots,
})
// Check storage pool exists.
_, _, _, err = s.DB.Cluster.GetStoragePoolInAnyState(bInfo.Pool)
if response.IsNotFoundError(err) {
// The storage pool doesn't exist. If backup is in binary format (so we cannot alter
// the backup.yaml) or the pool has been specified directly from the user restoring
// the backup then we cannot proceed so return an error.
if *bInfo.OptimizedStorage || pool != "" {
return response.InternalError(fmt.Errorf("Storage pool not found: %w", err))
}
// Otherwise try and restore to the project's default profile pool.
_, profile, err := s.DB.Cluster.GetProfile(bInfo.Project, "default")
if err != nil {
return response.InternalError(fmt.Errorf("Failed to get default profile: %w", err))
}
_, v, err := shared.GetRootDiskDevice(profile.Devices)
if err != nil {
return response.InternalError(fmt.Errorf("Failed to get root disk device: %w", err))
}
// Use the default-profile's root pool.
bInfo.Pool = v["pool"]
} else if err != nil {
return response.InternalError(err)
}
// Copy reverter so far so we can use it inside run after this function has finished.
runRevert := revert.Clone()
run := func(op *operations.Operation) error {
defer func() { _ = backupFile.Close() }()
defer runRevert.Fail()
pool, err := storagePools.LoadByName(s, bInfo.Pool)
if err != nil {
return err
}
// Check if the backup is optimized that the source pool driver matches the target pool driver.
if *bInfo.OptimizedStorage && pool.Driver().Info().Name != bInfo.Backend {
return fmt.Errorf("Optimized backup storage driver %q differs from the target storage pool driver %q", bInfo.Backend, pool.Driver().Info().Name)
}
// Dump tarball to storage. Because the backup file is unpacked and restored onto the storage
// device before the instance is created in the database it is necessary to return two functions;
// a post hook that can be run once the instance has been created in the database to run any
// storage layer finalisations, and a revert hook that can be run if the instance database load
// process fails that will remove anything created thus far.
postHook, revertHook, err := pool.CreateInstanceFromBackup(*bInfo, backupFile, nil)
if err != nil {
return fmt.Errorf("Create instance from backup: %w", err)
}
runRevert.Add(revertHook)
err = internalImportFromBackup(s, bInfo.Project, bInfo.Name, instanceName != "")
if err != nil {
return fmt.Errorf("Failed importing backup: %w", err)
}
inst, err := instance.LoadByProjectAndName(s, bInfo.Project, bInfo.Name)
if err != nil {
return fmt.Errorf("Load instance: %w", err)
}
// Clean up created instance if the post hook fails below.
runRevert.Add(func() { _ = inst.Delete(true) })
// Run the storage post hook to perform any final actions now that the instance has been created
// in the database (this normally includes unmounting volumes that were mounted).
if postHook != nil {
err = postHook(inst)
if err != nil {
return fmt.Errorf("Post hook failed: %w", err)
}
}
runRevert.Success()
return nil
}
resources := map[string][]api.URL{}
resources["instances"] = []api.URL{*api.NewURL().Path(version.APIVersion, "instances", bInfo.Name)}
op, err := operations.OperationCreate(s, bInfo.Project, operations.OperationClassTask, operationtype.BackupRestore, resources, nil, run, nil, nil, r)
if err != nil {
return response.InternalError(err)
}
revert.Success()
return operations.OperationResponse(op)
}
// swagger:operation POST /1.0/instances instances instances_post
//
// Create a new instance
//
// Creates a new instance on LXD.
// Depending on the source, this can create an instance from an existing
// local image, remote image, existing local instance or snapshot, remote
// migration stream or backup file.
//
// ---
// consumes:
// - application/json
// produces:
// - application/json
// parameters:
// - in: query
// name: project
// description: Project name
// type: string
// example: default
// - in: query
// name: target
// description: Cluster member
// type: string
// example: default
// - in: body
// name: instance
// description: Instance request
// required: false
// schema:
// $ref: "#/definitions/InstancesPost"
// - in: body
// name: raw_backup
// description: Raw backup file
// required: false
// responses:
// "202":
// $ref: "#/responses/Operation"
// "400":
// $ref: "#/responses/BadRequest"
// "403":
// $ref: "#/responses/Forbidden"
// "500":
// $ref: "#/responses/InternalServerError"
func instancesPost(d *Daemon, r *http.Request) response.Response {
s := d.State()
targetProjectName := projectParam(r)
clusterNotification := isClusterNotification(r)
logger.Debug("Responding to instance create")
// If we're getting binary content, process separately
if r.Header.Get("Content-Type") == "application/octet-stream" {
return createFromBackup(s, r, targetProjectName, r.Body, r.Header.Get("X-LXD-pool"), r.Header.Get("X-LXD-name"))
}
// Parse the request
req := api.InstancesPost{}
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
return response.BadRequest(err)
}
// Set type from URL if missing
urlType, err := urlInstanceTypeDetect(r)
if err != nil {
return response.InternalError(err)
}
if req.Type == "" && urlType != instancetype.Any {
req.Type = api.InstanceType(urlType.String())
}
if req.Type == "" {
req.Type = api.InstanceTypeContainer // Default to container if not specified.
}
if req.Devices == nil {
req.Devices = map[string]map[string]string{}
}
if req.Config == nil {
req.Config = map[string]string{}
}
if req.InstanceType != "" {
conf, err := instanceParseType(req.InstanceType)
if err != nil {
return response.BadRequest(err)
}
for k, v := range conf {
if req.Config[k] == "" {
req.Config[k] = v
}
}
}
// Check if clustered.
clustered, err := cluster.Enabled(s.DB.Node)
if err != nil {
return response.InternalError(fmt.Errorf("Failed to check for cluster state: %w", err))
}
var targetProject *api.Project
var profiles []api.Profile
var sourceInst *dbCluster.Instance
var sourceImage *api.Image
var sourceImageRef string
var candidateMembers []db.NodeInfo
var targetMemberInfo *db.NodeInfo
err = s.DB.Cluster.Transaction(r.Context(), func(ctx context.Context, tx *db.ClusterTx) error {
target := queryParam(r, "target")
if !clustered && target != "" {
return api.StatusErrorf(http.StatusBadRequest, "Target only allowed when clustered")
}
dbProject, err := dbCluster.GetProject(ctx, tx.Tx(), targetProjectName)
if err != nil {
return fmt.Errorf("Failed loading project: %w", err)
}
targetProject, err = dbProject.ToAPI(ctx, tx.Tx())
if err != nil {
return err
}
var targetGroupName string
var allMembers []db.NodeInfo
if clustered && !clusterNotification {
allMembers, err = tx.GetNodes(ctx)
if err != nil {
return fmt.Errorf("Failed getting cluster members: %w", err)
}
// Check if the given target is allowed and try to resolve the right member or group
targetMemberInfo, targetGroupName, err = project.CheckTarget(ctx, r, tx, targetProject, target, allMembers)
if err != nil {
return err
}
}
profileProject := project.ProfileProjectFromRecord(targetProject)
switch req.Source.Type {
case "copy":
if req.Source.Source == "" {
return api.StatusErrorf(http.StatusBadRequest, "Must specify a source instance")
}
if req.Source.Project == "" {
req.Source.Project = targetProjectName
}
sourceInst, err = instance.LoadInstanceDatabaseObject(ctx, tx, req.Source.Project, req.Source.Source)
if err != nil {
return err
}
req.Type = api.InstanceType(sourceInst.Type.String())
// Use source instance's profiles if no profile override.
if req.Profiles == nil {
sourceInstArgs, err := tx.InstancesToInstanceArgs(ctx, true, *sourceInst)
if err != nil {
return err
}
req.Profiles = make([]string, 0, len(sourceInstArgs[sourceInst.ID].Profiles))
for _, profile := range sourceInstArgs[sourceInst.ID].Profiles {
req.Profiles = append(req.Profiles, profile.Name)
}
}
case "image":
// Check if the image has an entry in the database but fail only if the error
// is different than the image not being found.
sourceImage, err = getSourceImageFromInstanceSource(ctx, s, tx, targetProject.Name, req.Source, &sourceImageRef, string(req.Type))
if err != nil && !api.StatusErrorCheck(err, http.StatusNotFound) {
return err
}
// If image has an entry in the database then use its profiles if no override provided.
if sourceImage != nil && req.Profiles == nil {
req.Architecture = sourceImage.Architecture
req.Profiles = sourceImage.Profiles
}
}
// Use default profile if no profile list specified (not even an empty list).
// This mirrors the logic in instance.CreateInternal() that would occur anyway.
if req.Profiles == nil {
req.Profiles = []string{"default"}
}
// Initialise the profile info list (even if an empty list is provided so this isn't left as nil).
// This way instances can still be created without any profiles by providing a non-nil empty list.
profiles = make([]api.Profile, 0, len(req.Profiles))
// Load profiles.
if len(req.Profiles) > 0 {
profileFilters := make([]dbCluster.ProfileFilter, 0, len(req.Profiles))
for _, profileName := range req.Profiles {
profileName := profileName
profileFilters = append(profileFilters, dbCluster.ProfileFilter{
Project: &profileProject,
Name: &profileName,
})
}
dbProfiles, err := dbCluster.GetProfiles(ctx, tx.Tx(), profileFilters...)
if err != nil {
return err
}
profilesByName := make(map[string]dbCluster.Profile, len(dbProfiles))
for _, dbProfile := range dbProfiles {
profilesByName[dbProfile.Name] = dbProfile
}
for _, profileName := range req.Profiles {
profile, found := profilesByName[profileName]
if !found {
return fmt.Errorf("Requested profile %q doesn't exist", profileName)
}
apiProfile, err := profile.ToAPI(ctx, tx.Tx())
if err != nil {
return err
}
profiles = append(profiles, *apiProfile)
}
}
// Generate automatic instance name if not specified.
if req.Name == "" {
names, err := tx.GetInstanceNames(ctx, targetProjectName)
if err != nil {
return err
}
i := 0
for {
i++
req.Name = strings.ToLower(petname.Generate(2, "-"))
if !shared.StringInSlice(req.Name, names) {
break
}
if i > 100 {
return fmt.Errorf("Couldn't generate a new unique name after 100 tries")