-
Notifications
You must be signed in to change notification settings - Fork 909
/
driver_common.go
1617 lines (1320 loc) · 46.4 KB
/
driver_common.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 drivers
import (
"context"
"errors"
"fmt"
"net/http"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
"github.com/google/uuid"
"github.com/canonical/lxd/lxd/backup"
"github.com/canonical/lxd/lxd/db"
dbCluster "github.com/canonical/lxd/lxd/db/cluster"
"github.com/canonical/lxd/lxd/device"
deviceConfig "github.com/canonical/lxd/lxd/device/config"
"github.com/canonical/lxd/lxd/device/nictype"
"github.com/canonical/lxd/lxd/instance"
"github.com/canonical/lxd/lxd/instance/instancetype"
"github.com/canonical/lxd/lxd/instance/operationlock"
"github.com/canonical/lxd/lxd/lifecycle"
"github.com/canonical/lxd/lxd/locking"
"github.com/canonical/lxd/lxd/maas"
"github.com/canonical/lxd/lxd/operations"
"github.com/canonical/lxd/lxd/project"
"github.com/canonical/lxd/lxd/state"
storagePools "github.com/canonical/lxd/lxd/storage"
"github.com/canonical/lxd/shared"
"github.com/canonical/lxd/shared/api"
"github.com/canonical/lxd/shared/entity"
"github.com/canonical/lxd/shared/logger"
"github.com/canonical/lxd/shared/revert"
)
// ErrExecCommandNotFound indicates the command is not found.
var ErrExecCommandNotFound = api.StatusErrorf(http.StatusBadRequest, "Command not found")
// ErrExecCommandNotExecutable indicates the command is not executable.
var ErrExecCommandNotExecutable = api.StatusErrorf(http.StatusBadRequest, "Command not executable")
// ErrInstanceIsStopped indicates that the instance is stopped.
var ErrInstanceIsStopped error = api.StatusErrorf(http.StatusBadRequest, "The instance is already stopped")
// deviceManager is an interface that allows managing device lifecycle.
type deviceManager interface {
deviceAdd(dev device.Device, instanceRunning bool) error
deviceRemove(dev device.Device, instanceRunning bool) error
deviceStart(dev device.Device, instanceRunning bool) (*deviceConfig.RunConfig, error)
deviceStop(dev device.Device, instanceRunning bool, stopHookNetnsPath string) error
}
// common provides structure common to all instance types.
type common struct {
op *operations.Operation
state *state.State
architecture int
creationDate time.Time
dbType instancetype.Type
description string
ephemeral bool
expandedConfig map[string]string
expandedDevices deviceConfig.Devices
expiryDate time.Time
id int
lastUsedDate time.Time
localConfig map[string]string
localDevices deviceConfig.Devices
logger logger.Logger
name string
node string
profiles []api.Profile
project api.Project
isSnapshot bool
stateful bool
// Cached handles.
// Do not use these variables directly, instead use their associated get functions so they
// will be initialised on demand.
storagePool storagePools.Pool
// volatileSetPersistDisable indicates whether the VolatileSet function should persist changes to the DB.
volatileSetPersistDisable bool
}
//
// SECTION: property getters
//
// Architecture returns the instance's architecture.
func (d *common) Architecture() int {
return d.architecture
}
// CreationDate returns the instance's creation date.
func (d *common) CreationDate() time.Time {
return d.creationDate
}
// Type returns the instance's type.
func (d *common) Type() instancetype.Type {
return d.dbType
}
// Description returns the instance's description.
func (d *common) Description() string {
return d.description
}
// IsEphemeral returns whether the instanc is ephemeral or not.
func (d *common) IsEphemeral() bool {
return d.ephemeral
}
// ExpandedConfig returns instance's expanded config.
func (d *common) ExpandedConfig() map[string]string {
return d.expandedConfig
}
// ExpandedDevices returns instance's expanded device config.
func (d *common) ExpandedDevices() deviceConfig.Devices {
return d.expandedDevices
}
// ExpiryDate returns when this snapshot expires.
func (d *common) ExpiryDate() time.Time {
if d.isSnapshot {
return d.expiryDate
}
// Return zero time if the instance is not a snapshot.
return time.Time{}
}
// ID gets instances's ID.
func (d *common) ID() int {
return d.id
}
// LastUsedDate returns the instance's last used date.
func (d *common) LastUsedDate() time.Time {
return d.lastUsedDate
}
// LocalConfig returns the instance's local config.
func (d *common) LocalConfig() map[string]string {
return d.localConfig
}
// LocalDevices returns the instance's local device config.
func (d *common) LocalDevices() deviceConfig.Devices {
return d.localDevices
}
// Name returns the instance's name.
func (d *common) Name() string {
return d.name
}
// CloudInitID returns the cloud-init instance-id.
func (d *common) CloudInitID() string {
id := d.LocalConfig()["volatile.cloud-init.instance-id"]
if id != "" {
return id
}
return d.name
}
// Location returns instance's location.
func (d *common) Location() string {
return d.node
}
// Profiles returns the instance's profiles.
func (d *common) Profiles() []api.Profile {
return d.profiles
}
// Project returns instance's project.
func (d *common) Project() api.Project {
return d.project
}
// IsSnapshot returns whether instance is snapshot or not.
func (d *common) IsSnapshot() bool {
return d.isSnapshot
}
// IsStateful returns whether instance is stateful or not.
func (d *common) IsStateful() bool {
return d.stateful
}
// Operation returns the instance's current operation.
func (d *common) Operation() *operations.Operation {
return d.op
}
//
// SECTION: general functions
//
// Backups returns a list of backups.
func (d *common) Backups() ([]backup.InstanceBackup, error) {
var backupNames []string
// Get all the backups
err := d.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
var err error
backupNames, err = tx.GetInstanceBackups(ctx, d.project.Name, d.name)
return err
})
if err != nil {
return nil, err
}
// Build the backup list
backups := []backup.InstanceBackup{}
for _, backupName := range backupNames {
backup, err := instance.BackupLoadByName(d.state, d.project.Name, backupName)
if err != nil {
return nil, err
}
backups = append(backups, *backup)
}
return backups, nil
}
// DeferTemplateApply records a template trigger to apply on next instance start.
func (d *common) DeferTemplateApply(trigger instance.TemplateTrigger) error {
// Avoid over-writing triggers that have already been set.
if d.localConfig["volatile.apply_template"] != "" {
return nil
}
err := d.VolatileSet(map[string]string{"volatile.apply_template": string(trigger)})
if err != nil {
return fmt.Errorf("Failed to set apply_template volatile key: %w", err)
}
return nil
}
// SetOperation sets the current operation.
func (d *common) SetOperation(op *operations.Operation) {
d.op = op
}
// Snapshots returns a list of snapshots.
func (d *common) Snapshots() ([]instance.Instance, error) {
if d.isSnapshot {
return []instance.Instance{}, nil
}
var snapshotArgs map[int]db.InstanceArgs
// Get all the snapshots for instance.
err := d.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
filter := dbCluster.InstanceSnapshotFilter{
Project: &d.project.Name,
Instance: &d.name,
}
dbSnapshots, err := dbCluster.GetInstanceSnapshots(ctx, tx.Tx(), filter)
if err != nil {
return err
}
dbInstances := make([]dbCluster.Instance, len(dbSnapshots))
for i, s := range dbSnapshots {
dbInstances[i] = s.ToInstance(d.name, d.node, d.dbType, d.architecture)
}
snapshotArgs, err = tx.InstancesToInstanceArgs(ctx, false, dbInstances...)
if err != nil {
return err
}
return nil
})
if err != nil {
return nil, err
}
snapshots := make([]instance.Instance, 0, len(snapshotArgs))
for _, snapshotArg := range snapshotArgs {
// Populate profile info that was already loaded.
snapshotArg.Profiles = d.profiles
snapInst, err := instance.Load(d.state, snapshotArg, d.project)
if err != nil {
return nil, err
}
snapshots = append(snapshots, instance.Instance(snapInst))
}
sort.SliceStable(snapshots, func(i, j int) bool {
iCreation := snapshots[i].CreationDate()
jCreation := snapshots[j].CreationDate()
// Prefer sorting by creation date.
if iCreation.Before(jCreation) {
return true
}
// But if creation date is the same, then sort by ID.
if iCreation.Equal(jCreation) && snapshots[i].ID() < snapshots[j].ID() {
return true
}
return false
})
return snapshots, nil
}
// VolatileSet sets one or more volatile config keys.
func (d *common) VolatileSet(changes map[string]string) error {
// Quick check.
for key := range changes {
if !strings.HasPrefix(key, instancetype.ConfigVolatilePrefix) {
return fmt.Errorf("Only volatile keys can be modified with VolatileSet")
}
}
// Update the database if required.
if !d.volatileSetPersistDisable {
var err error
if d.isSnapshot {
err = d.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
return tx.UpdateInstanceSnapshotConfig(d.id, changes)
})
} else {
err = d.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
return tx.UpdateInstanceConfig(d.id, changes)
})
}
if err != nil {
return fmt.Errorf("Failed to set volatile config: %w", err)
}
}
// Apply the change locally.
for key, value := range changes {
if value == "" {
delete(d.expandedConfig, key)
delete(d.localConfig, key)
continue
}
d.expandedConfig[key] = value
d.localConfig[key] = value
}
return nil
}
//
// SECTION: path getters
//
// ConsoleBufferLogPath returns the instance's console buffer log path.
func (d *common) ConsoleBufferLogPath() string {
return filepath.Join(d.LogPath(), "console.log")
}
// DevicesPath returns the instance's devices path.
func (d *common) DevicesPath() string {
name := project.Instance(d.project.Name, d.name)
return shared.VarPath("devices", name)
}
// LogPath returns the instance's log path.
func (d *common) LogPath() string {
name := project.Instance(d.project.Name, d.name)
return shared.LogPath(name)
}
// Path returns the instance's path.
func (d *common) Path() string {
return storagePools.InstancePath(d.dbType, d.project.Name, d.name, d.isSnapshot)
}
// ExecOutputPath returns the instance's exec output path.
func (d *common) ExecOutputPath() string {
return filepath.Join(d.Path(), "exec-output")
}
// RootfsPath returns the instance's rootfs path.
func (d *common) RootfsPath() string {
return filepath.Join(d.Path(), "rootfs")
}
// ShmountsPath returns the instance's shared mounts path.
func (d *common) ShmountsPath() string {
name := project.Instance(d.project.Name, d.name)
return shared.VarPath("shmounts", name)
}
// StatePath returns the instance's state path.
func (d *common) StatePath() string {
return filepath.Join(d.Path(), "state")
}
// TemplatesPath returns the instance's templates path.
func (d *common) TemplatesPath() string {
return filepath.Join(d.Path(), "templates")
}
// StoragePool returns the storage pool name.
func (d *common) StoragePool() (string, error) {
pool, err := d.getStoragePool()
if err != nil {
return "", err
}
return pool.Name(), nil
}
//
// SECTION: internal functions
//
// deviceVolatileReset resets a device's volatile data when its removed or updated in such a way
// that it is removed then added immediately afterwards.
func (d *common) deviceVolatileReset(devName string, oldConfig, newConfig deviceConfig.Device) error {
volatileClear := make(map[string]string)
devicePrefix := fmt.Sprintf("volatile.%s.", devName)
newNICType, err := nictype.NICType(d.state, d.project.Name, newConfig)
if err != nil {
return err
}
oldNICType, err := nictype.NICType(d.state, d.project.Name, oldConfig)
if err != nil {
return err
}
// If the device type has changed, remove all old volatile keys.
// This will occur if the newConfig is empty (i.e the device is actually being removed) or
// if the device type is being changed but keeping the same name.
if newConfig["type"] != oldConfig["type"] || newNICType != oldNICType {
for k := range d.localConfig {
if !strings.HasPrefix(k, devicePrefix) {
continue
}
volatileClear[k] = ""
}
return d.VolatileSet(volatileClear)
}
// If the device type remains the same, then just remove any volatile keys that have
// the same key name present in the new config (i.e the new config is replacing the
// old volatile key).
for k := range d.localConfig {
if !strings.HasPrefix(k, devicePrefix) {
continue
}
devKey := strings.TrimPrefix(k, devicePrefix)
_, found := newConfig[devKey]
if found {
volatileClear[k] = ""
}
}
return d.VolatileSet(volatileClear)
}
// deviceVolatileGetFunc returns a function that retrieves a named device's volatile config and
// removes its device prefix from the keys.
func (d *common) deviceVolatileGetFunc(devName string) func() map[string]string {
return func() map[string]string {
volatile := make(map[string]string)
prefix := fmt.Sprintf("volatile.%s.", devName)
for k, v := range d.localConfig {
if strings.HasPrefix(k, prefix) {
volatile[strings.TrimPrefix(k, prefix)] = v
}
}
return volatile
}
}
// deviceVolatileSetFunc returns a function that can be called to save a named device's volatile
// config using keys that do not have the device's name prefixed.
func (d *common) deviceVolatileSetFunc(devName string) func(save map[string]string) error {
return func(save map[string]string) error {
volatileSave := make(map[string]string)
for k, v := range save {
volatileSave[fmt.Sprintf("volatile.%s.%s", devName, k)] = v
}
return d.VolatileSet(volatileSave)
}
}
// expandConfig applies the config of each profile in order, followed by the local config.
func (d *common) expandConfig() error {
var globalConfigDump map[string]string
if d.state.GlobalConfig != nil {
globalConfigDump = d.state.GlobalConfig.Dump()
}
d.expandedConfig = instancetype.ExpandInstanceConfig(globalConfigDump, d.localConfig, d.profiles)
d.expandedDevices = instancetype.ExpandInstanceDevices(d.localDevices, d.profiles)
return nil
}
// restartCommon handles the common part of instance restarts.
func (d *common) restartCommon(inst instance.Instance, timeout time.Duration) error {
// Setup a new operation for the stop/shutdown phase.
op, err := operationlock.Create(d.Project().Name, d.Name(), operationlock.ActionRestart, true, true)
if err != nil {
return fmt.Errorf("Create restart operation: %w", err)
}
// Handle ephemeral instances.
ephemeral := inst.IsEphemeral()
ctxMap := logger.Ctx{
"action": "shutdown",
"created": d.creationDate,
"ephemeral": ephemeral,
"used": d.lastUsedDate,
"timeout": timeout}
d.logger.Info("Restarting instance", ctxMap)
if ephemeral {
// Unset ephemeral flag
args := db.InstanceArgs{
Architecture: inst.Architecture(),
Config: inst.LocalConfig(),
Description: inst.Description(),
Devices: inst.LocalDevices(),
Ephemeral: false,
Profiles: inst.Profiles(),
Project: inst.Project().Name,
Type: inst.Type(),
Snapshot: inst.IsSnapshot(),
}
err := inst.Update(args, false)
if err != nil {
return err
}
// On function return, set the flag back on
defer func() {
args.Ephemeral = ephemeral
_ = inst.Update(args, false)
}()
}
if timeout == 0 {
err := inst.Stop(false)
if err != nil {
op.Done(err)
return err
}
} else {
if inst.IsFrozen() {
err = fmt.Errorf("Instance is not running")
op.Done(err)
return err
}
err := inst.Shutdown(timeout)
if err != nil {
op.Done(err)
return err
}
}
// Setup a new operation for the start phase.
op, err = operationlock.Create(d.Project().Name, d.Name(), operationlock.ActionRestart, true, true)
if err != nil {
return fmt.Errorf("Create restart (for start) operation: %w", err)
}
err = inst.Start(false)
if err != nil {
op.Done(err)
return err
}
d.logger.Info("Restarted instance", ctxMap)
d.state.Events.SendLifecycle(d.project.Name, lifecycle.InstanceRestarted.Event(d, nil))
return nil
}
// rebuildCommon handles the common part of instance rebuilds.
func (d *common) rebuildCommon(inst instance.Instance, img *api.Image, op *operations.Operation) error {
instLocalConfig := d.localConfig
// Reset the "image.*" keys.
for k := range instLocalConfig {
if strings.HasPrefix(k, "image.") {
delete(instLocalConfig, k)
}
}
delete(instLocalConfig, "volatile.base_image")
if img != nil {
for k, v := range img.Properties {
instLocalConfig[fmt.Sprintf("image.%s", k)] = v
}
instLocalConfig["volatile.base_image"] = img.Fingerprint
instLocalConfig["volatile.uuid.generation"] = instLocalConfig["volatile.uuid"]
}
// Reset relevant volatile keys.
delete(instLocalConfig, "volatile.idmap.next")
delete(instLocalConfig, "volatile.last_state.idmap")
pool, err := d.getStoragePool()
if err != nil {
return err
}
err = pool.DeleteInstance(inst, op)
if err != nil {
return err
}
// Rebuild as empty if there is no image provided.
if img == nil {
err = pool.CreateInstance(inst, nil)
if err != nil {
return err
}
} else {
err = pool.CreateInstanceFromImage(inst, img.Fingerprint, op)
if err != nil {
return err
}
}
err = d.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
err = dbCluster.UpdateInstanceConfig(ctx, tx.Tx(), int64(inst.ID()), instLocalConfig)
if err != nil {
return err
}
if img != nil {
err = tx.UpdateImageLastUseDate(ctx, inst.Project().Name, img.Fingerprint, time.Now().UTC())
if err != nil {
return err
}
}
return nil
})
if err != nil {
return err
}
d.localConfig = instLocalConfig
return nil
}
// runHooks executes the callback functions returned from a function.
func (d *common) runHooks(hooks []func() error) error {
// Run any post start hooks.
for _, hook := range hooks {
err := hook()
if err != nil {
return err
}
}
return nil
}
// snapshot handles the common part of the snapshoting process.
func (d *common) snapshotCommon(inst instance.Instance, name string, expiry time.Time, stateful bool) error {
revert := revert.New()
defer revert.Fail()
// Setup the arguments.
args := db.InstanceArgs{
Project: inst.Project().Name,
Architecture: inst.Architecture(),
Config: inst.LocalConfig(),
Type: inst.Type(),
Snapshot: true,
Devices: inst.LocalDevices(),
Ephemeral: inst.IsEphemeral(),
Name: inst.Name() + shared.SnapshotDelimiter + name,
Profiles: inst.Profiles(),
Stateful: stateful,
ExpiryDate: expiry,
}
// Create the snapshot.
snap, snapInstOp, cleanup, err := instance.CreateInternal(d.state, args, true)
if err != nil {
return fmt.Errorf("Failed creating instance snapshot record %q: %w", name, err)
}
revert.Add(cleanup)
defer snapInstOp.Done(err)
pool, err := storagePools.LoadByInstance(d.state, snap)
if err != nil {
return err
}
err = pool.CreateInstanceSnapshot(snap, inst, d.op)
if err != nil {
return fmt.Errorf("Create instance snapshot: %w", err)
}
revert.Add(func() { _ = snap.Delete(true) })
// Mount volume for backup.yaml writing.
_, err = pool.MountInstance(inst, d.op)
if err != nil {
return fmt.Errorf("Create instance snapshot (mount source): %w", err)
}
defer func() { _ = pool.UnmountInstance(inst, d.op) }()
// Attempt to update backup.yaml for instance.
err = inst.UpdateBackupFile()
if err != nil {
return err
}
revert.Success()
return nil
}
// updateProgress updates the operation metadata with a new progress string.
func (d *common) updateProgress(progress string) {
if d.op == nil {
return
}
meta := d.op.Metadata()
if meta == nil {
meta = make(map[string]any)
}
if meta["container_progress"] != progress {
meta["container_progress"] = progress
_ = d.op.UpdateMetadata(meta)
}
}
// insertConfigkey function attempts to insert the instance config key into the database. If the insert fails
// then the database is queried to check whether another query inserted the same key. If the key is still
// unpopulated then the insert querty is retried until it succeeds or a retry limit is reached.
// If the insert succeeds or the key is found to have been populated then the value of the key is returned.
func (d *common) insertConfigkey(key string, value string) (string, error) {
err := d.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
err := tx.CreateInstanceConfig(ctx, d.id, map[string]string{key: value})
if err == nil {
return nil
}
// Check if something else filled it in behind our back.
existingValue, errCheckExists := tx.GetInstanceConfig(ctx, d.id, key)
if errCheckExists != nil {
return err
}
value = existingValue
return nil
})
if err != nil {
return "", err
}
return value, nil
}
// isRunningStatusCode returns if instance is running from status code.
func (d *common) isRunningStatusCode(statusCode api.StatusCode) bool {
return statusCode != api.Error && statusCode != api.Stopped
}
// isStartableStatusCode returns an error if the status code means the instance cannot be started currently.
func (d *common) isStartableStatusCode(statusCode api.StatusCode) error {
if d.isRunningStatusCode(statusCode) {
return fmt.Errorf("The instance is already running")
}
// If the instance process exists but is crashed, don't allow starting until its been cleaned up, as it
// would likely fail to start anyway or leave the old process untracked.
if statusCode == api.Error {
return fmt.Errorf("The instance cannot be started as in %s status", statusCode)
}
return nil
}
// getStartupSnapNameAndExpiry returns the name and expiry for a snapshot to be taken at startup.
func (d *common) getStartupSnapNameAndExpiry(inst instance.Instance) (string, *time.Time, error) {
schedule := strings.ToLower(d.expandedConfig["snapshots.schedule"])
if schedule == "" {
return "", nil, nil
}
triggers := strings.Split(schedule, ", ")
if !shared.ValueInSlice("@startup", triggers) {
return "", nil, nil
}
expiry, err := shared.GetExpiry(time.Now(), d.expandedConfig["snapshots.expiry"])
if err != nil {
return "", nil, err
}
name, err := instance.NextSnapshotName(d.state, inst, "snap%d")
if err != nil {
return "", nil, err
}
return name, &expiry, nil
}
// Internal MAAS handling.
func (d *common) maasUpdate(inst instance.Instance, oldDevices map[string]map[string]string) error {
// Check if MAAS is configured
maasURL, _ := d.state.GlobalConfig.MAASController()
if maasURL == "" {
return nil
}
// Check if there's something that uses MAAS
interfaces, err := d.maasInterfaces(inst, d.expandedDevices.CloneNative())
if err != nil {
return err
}
var oldInterfaces []maas.ContainerInterface
if oldDevices != nil {
oldInterfaces, err = d.maasInterfaces(inst, oldDevices)
if err != nil {
return err
}
}
if len(interfaces) == 0 && len(oldInterfaces) == 0 {
return nil
}
// See if we're connected to MAAS
if d.state.MAAS == nil {
return fmt.Errorf("Can't perform the operation because MAAS is currently unavailable")
}
exists, err := d.state.MAAS.DefinedContainer(d)
if err != nil {
return err
}
if exists {
if len(interfaces) == 0 && len(oldInterfaces) > 0 {
return d.state.MAAS.DeleteContainer(d)
}
return d.state.MAAS.UpdateContainer(d, interfaces)
}
return d.state.MAAS.CreateContainer(d, interfaces)
}
func (d *common) maasInterfaces(inst instance.Instance, devices map[string]map[string]string) ([]maas.ContainerInterface, error) {
interfaces := []maas.ContainerInterface{}
for k, m := range devices {
if m["type"] != "nic" {
continue
}
if m["maas.subnet.ipv4"] == "" && m["maas.subnet.ipv6"] == "" {
continue
}
m, err := inst.FillNetworkDevice(k, m)
if err != nil {
return nil, err
}
subnets := []maas.ContainerInterfaceSubnet{}
// IPv4
if m["maas.subnet.ipv4"] != "" {
subnet := maas.ContainerInterfaceSubnet{
Name: m["maas.subnet.ipv4"],
Address: m["ipv4.address"],
}
subnets = append(subnets, subnet)
}
// IPv6
if m["maas.subnet.ipv6"] != "" {
subnet := maas.ContainerInterfaceSubnet{
Name: m["maas.subnet.ipv6"],
Address: m["ipv6.address"],
}
subnets = append(subnets, subnet)
}
iface := maas.ContainerInterface{
Name: m["name"],
MACAddress: m["hwaddr"],
Subnets: subnets,
}
interfaces = append(interfaces, iface)
}
return interfaces, nil
}
func (d *common) maasRename(inst instance.Instance, newName string) error {
maasURL, _ := d.state.GlobalConfig.MAASController()
if maasURL == "" {
return nil
}
interfaces, err := d.maasInterfaces(inst, d.expandedDevices.CloneNative())
if err != nil {
return err
}
if len(interfaces) == 0 {
return nil
}
if d.state.MAAS == nil {
return fmt.Errorf("Can't perform the operation because MAAS is currently unavailable")
}
exists, err := d.state.MAAS.DefinedContainer(d)
if err != nil {
return err
}
if !exists {
return d.maasUpdate(inst, nil)
}
return d.state.MAAS.RenameContainer(d, newName)
}
func (d *common) maasDelete(inst instance.Instance) error {
maasURL, _ := d.state.GlobalConfig.MAASController()
if maasURL == "" {
return nil
}
interfaces, err := d.maasInterfaces(inst, d.expandedDevices.CloneNative())
if err != nil {
return err
}
if len(interfaces) == 0 {
return nil
}
if d.state.MAAS == nil {
return fmt.Errorf("Can't perform the operation because MAAS is currently unavailable")
}
exists, err := d.state.MAAS.DefinedContainer(d)
if err != nil {
return err
}
if !exists {
return nil
}
return d.state.MAAS.DeleteContainer(d)
}