-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfilesystem.go
1517 lines (1400 loc) · 48.5 KB
/
filesystem.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
// Copyright 2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package state
import (
"fmt"
"path"
"regexp"
"strings"
"github.com/juju/errors"
jujutxn "github.com/juju/txn"
"gopkg.in/juju/charm.v6"
"gopkg.in/juju/names.v3"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"gopkg.in/mgo.v2/txn"
"github.com/juju/juju/core/paths"
"github.com/juju/juju/core/status"
"github.com/juju/juju/storage"
)
// ErrNoBackingVolume is returned by Filesystem.Volume() for filesystems
// without a backing volume.
var ErrNoBackingVolume = errors.New("filesystem has no backing volume")
// Filesystem describes a filesystem in the model. Filesystems may be
// backed by a volume, and managed by Juju; otherwise they are first-class
// entities managed by a filesystem provider.
type Filesystem interface {
GlobalEntity
Lifer
status.StatusGetter
status.StatusSetter
// FilesystemTag returns the tag for the filesystem.
FilesystemTag() names.FilesystemTag
// Storage returns the tag of the storage instance that this
// filesystem is assigned to, if any. If the filesystem is not
// assigned to a storage instance, an error satisfying
// errors.IsNotAssigned will be returned.
//
// A filesystem can be assigned to at most one storage instance, and
// a storage instance can have at most one associated filesystem.
Storage() (names.StorageTag, error)
// Volume returns the tag of the volume backing this filesystem,
// or ErrNoBackingVolume if the filesystem is not backed by a volume
// managed by Juju.
Volume() (names.VolumeTag, error)
// Info returns the filesystem's FilesystemInfo, or a NotProvisioned
// error if the filesystem has not yet been provisioned.
Info() (FilesystemInfo, error)
// Params returns the parameters for provisioning the filesystem,
// if it needs to be provisioned. Params returns true if the returned
// parameters are usable for provisioning, otherwise false.
Params() (FilesystemParams, bool)
// Detachable reports whether or not the filesystem is detachable.
Detachable() bool
// Releasing reports whether or not the filesystem is to be released
// from the model when it is Dying/Dead.
Releasing() bool
}
// FilesystemAttachment describes an attachment of a filesystem to a machine.
type FilesystemAttachment interface {
Lifer
// Filesystem returns the tag of the related Filesystem.
Filesystem() names.FilesystemTag
// Host returns the tag of the entity to which this attachment belongs.
Host() names.Tag
// Info returns the filesystem attachment's FilesystemAttachmentInfo, or a
// NotProvisioned error if the attachment has not yet been made.
//
// Note that the presence of FilesystemAttachmentInfo does not necessarily
// imply that the filesystem is mounted; model storage providers may
// need to prepare a filesystem for attachment to a machine before it can
// be mounted.
Info() (FilesystemAttachmentInfo, error)
// Params returns the parameters for creating the filesystem attachment,
// if it has not already been made. Params returns true if the returned
// parameters are usable for creating an attachment, otherwise false.
Params() (FilesystemAttachmentParams, bool)
}
type filesystem struct {
mb modelBackend
doc filesystemDoc
}
type filesystemAttachment struct {
doc filesystemAttachmentDoc
}
// filesystemDoc records information about a filesystem in the model.
type filesystemDoc struct {
DocID string `bson:"_id"`
FilesystemId string `bson:"filesystemid"`
ModelUUID string `bson:"model-uuid"`
Life Life `bson:"life"`
Releasing bool `bson:"releasing,omitempty"`
StorageId string `bson:"storageid,omitempty"`
VolumeId string `bson:"volumeid,omitempty"`
AttachmentCount int `bson:"attachmentcount"`
Info *FilesystemInfo `bson:"info,omitempty"`
Params *FilesystemParams `bson:"params,omitempty"`
// HostId is the ID of the host that a non-detachable
// volume is initially attached to. We use this to identify
// the filesystem as being non-detachable, and to determine
// which filesystems must be removed along with said machine.
HostId string `bson:"hostid,omitempty"`
}
// filesystemAttachmentDoc records information about a filesystem attachment.
type filesystemAttachmentDoc struct {
// DocID is the machine global key followed by the filesystem name.
DocID string `bson:"_id"`
ModelUUID string `bson:"model-uuid"`
Filesystem string `bson:"filesystemid"`
Host string `bson:"hostid"`
Life Life `bson:"life"`
Info *FilesystemAttachmentInfo `bson:"info,omitempty"`
Params *FilesystemAttachmentParams `bson:"params,omitempty"`
}
// FilesystemParams records parameters for provisioning a new filesystem.
type FilesystemParams struct {
// storage, if non-zero, is the tag of the storage instance
// that the filesystem is to be assigned to.
storage names.StorageTag
// filesystemId, if non-empty, is the provider-allocated unique ID
// of the filesystem. This will be unspecified for filesystems backed
// by volumes. This is only set when creating a filesystem entity
// for an existing, non-volume backed, filesystem.
filesystemId string
// volumeInfo, if non-empty, is the information for an already
// provisioned backing volume. This is only set when creating a
// filesystem entity for an existing volume backed filesystem.
volumeInfo *VolumeInfo
Pool string `bson:"pool"`
Size uint64 `bson:"size"`
}
// FilesystemInfo describes information about a filesystem.
type FilesystemInfo struct {
Size uint64 `bson:"size"`
Pool string `bson:"pool"`
// FilesystemId is the provider-allocated unique ID of the
// filesystem. This will be the string representation of
// the filesystem tag for filesystems backed by volumes.
FilesystemId string `bson:"filesystemid"`
}
// FilesystemAttachmentInfo describes information about a filesystem attachment.
type FilesystemAttachmentInfo struct {
// MountPoint is the path at which the filesystem is mounted on the
// machine. MountPoint may be empty, meaning that the filesystem is
// not mounted yet.
MountPoint string `bson:"mountpoint"`
ReadOnly bool `bson:"read-only"`
}
// FilesystemAttachmentParams records parameters for attaching a filesystem to a
// machine.
type FilesystemAttachmentParams struct {
// locationAutoGenerated records whether or not the Location
// field's value was automatically generated, and thus known
// to be unique. This is used to optimise away mount point
// conflict checks.
locationAutoGenerated bool
Location string `bson:"location"`
ReadOnly bool `bson:"read-only"`
}
// validate validates the contents of the filesystem document.
func (f *filesystemDoc) validate() error {
return nil
}
// globalKey is required to implement GlobalEntity.
func (f *filesystem) globalKey() string {
return filesystemGlobalKey(f.doc.FilesystemId)
}
// Tag is required to implement GlobalEntity.
func (f *filesystem) Tag() names.Tag {
return f.FilesystemTag()
}
// FilesystemTag is required to implement Filesystem.
func (f *filesystem) FilesystemTag() names.FilesystemTag {
return names.NewFilesystemTag(f.doc.FilesystemId)
}
// Life is required to implement Filesystem.
func (f *filesystem) Life() Life {
return f.doc.Life
}
// Storage is required to implement Filesystem.
func (f *filesystem) Storage() (names.StorageTag, error) {
if f.doc.StorageId == "" {
msg := fmt.Sprintf("filesystem %q is not assigned to any storage instance", f.Tag().Id())
return names.StorageTag{}, errors.NewNotAssigned(nil, msg)
}
return names.NewStorageTag(f.doc.StorageId), nil
}
// Volume is required to implement Filesystem.
func (f *filesystem) Volume() (names.VolumeTag, error) {
if f.doc.VolumeId == "" {
return names.VolumeTag{}, ErrNoBackingVolume
}
return names.NewVolumeTag(f.doc.VolumeId), nil
}
// Info is required to implement Filesystem.
func (f *filesystem) Info() (FilesystemInfo, error) {
if f.doc.Info == nil {
return FilesystemInfo{}, errors.NotProvisionedf("filesystem %q", f.doc.FilesystemId)
}
return *f.doc.Info, nil
}
// Params is required to implement Filesystem.
func (f *filesystem) Params() (FilesystemParams, bool) {
if f.doc.Params == nil {
return FilesystemParams{}, false
}
return *f.doc.Params, true
}
// Releasing is required to implement Filesystem.
func (f *filesystem) Releasing() bool {
return f.doc.Releasing
}
// Status is required to implement StatusGetter.
func (f *filesystem) Status() (status.StatusInfo, error) {
return getStatus(f.mb.db(), filesystemGlobalKey(f.FilesystemTag().Id()), "filesystem")
}
// SetStatus is required to implement StatusSetter.
func (f *filesystem) SetStatus(fsStatus status.StatusInfo) error {
switch fsStatus.Status {
case status.Attaching, status.Attached, status.Detaching, status.Detached, status.Destroying:
case status.Error:
if fsStatus.Message == "" {
return errors.Errorf("cannot set status %q without info", fsStatus.Status)
}
case status.Pending:
// If a filesystem is not yet provisioned, we allow its status
// to be set back to pending (when a retry is to occur).
// First refresh.
f, err := getFilesystemByTag(f.mb, f.FilesystemTag())
if err != nil {
return errors.Trace(err)
}
_, err = f.Info()
if errors.IsNotProvisioned(err) {
break
}
return errors.Errorf("cannot set status %q", fsStatus.Status)
default:
return errors.Errorf("cannot set invalid status %q", fsStatus.Status)
}
return setStatus(f.mb.db(), setStatusParams{
badge: "filesystem",
globalKey: filesystemGlobalKey(f.FilesystemTag().Id()),
status: fsStatus.Status,
message: fsStatus.Message,
rawData: fsStatus.Data,
updated: timeOrNow(fsStatus.Since, f.mb.clock()),
})
}
// Filesystem is required to implement FilesystemAttachment.
func (f *filesystemAttachment) Filesystem() names.FilesystemTag {
return names.NewFilesystemTag(f.doc.Filesystem)
}
func storageAttachmentHost(id string) names.Tag {
if names.IsValidUnit(id) {
return names.NewUnitTag(id)
}
return names.NewMachineTag(id)
}
// Host is required to implement FilesystemAttachment.
func (f *filesystemAttachment) Host() names.Tag {
return storageAttachmentHost(f.doc.Host)
}
// Life is required to implement FilesystemAttachment.
func (f *filesystemAttachment) Life() Life {
return f.doc.Life
}
// Info is required to implement FilesystemAttachment.
func (f *filesystemAttachment) Info() (FilesystemAttachmentInfo, error) {
if f.doc.Info == nil {
hostTag := storageAttachmentHost(f.doc.Host)
return FilesystemAttachmentInfo{}, errors.NotProvisionedf(
"filesystem attachment %q on %q", f.doc.Filesystem, names.ReadableString(hostTag))
}
return *f.doc.Info, nil
}
// Params is required to implement FilesystemAttachment.
func (f *filesystemAttachment) Params() (FilesystemAttachmentParams, bool) {
if f.doc.Params == nil {
return FilesystemAttachmentParams{}, false
}
return *f.doc.Params, true
}
// Filesystem returns the Filesystem with the specified name.
func (sb *storageBackend) Filesystem(tag names.FilesystemTag) (Filesystem, error) {
f, err := getFilesystemByTag(sb.mb, tag)
return f, err
}
func getFilesystemByTag(mb modelBackend, tag names.FilesystemTag) (*filesystem, error) {
doc, err := getFilesystemDocByTag(mb.db(), tag)
if err != nil {
return nil, errors.Trace(err)
}
return &filesystem{mb, doc}, nil
}
func (sb *storageBackend) storageInstanceFilesystem(tag names.StorageTag) (*filesystem, error) {
query := bson.D{{"storageid", tag.Id()}}
description := fmt.Sprintf("filesystem for storage instance %q", tag.Id())
return sb.filesystem(query, description)
}
// StorageInstanceFilesystem returns the Filesystem assigned to the specified
// storage instance.
func (sb *storageBackend) StorageInstanceFilesystem(tag names.StorageTag) (Filesystem, error) {
f, err := sb.storageInstanceFilesystem(tag)
return f, err
}
func (sb *storageBackend) volumeFilesystem(tag names.VolumeTag) (*filesystem, error) {
query := bson.D{{"volumeid", tag.Id()}}
description := fmt.Sprintf("filesystem for volume %q", tag.Id())
return sb.filesystem(query, description)
}
// VolumeFilesystem returns the Filesystem backed by the specified volume.
func (sb *storageBackend) VolumeFilesystem(tag names.VolumeTag) (Filesystem, error) {
f, err := sb.volumeFilesystem(tag)
return f, err
}
func (sb *storageBackend) filesystems(query interface{}) ([]*filesystem, error) {
fDocs, err := getFilesystemDocs(sb.mb.db(), query)
if err != nil {
return nil, errors.Trace(err)
}
filesystems := make([]*filesystem, len(fDocs))
for i, doc := range fDocs {
filesystems[i] = &filesystem{sb.mb, doc}
}
return filesystems, nil
}
func (sb *storageBackend) filesystem(query bson.D, description string) (*filesystem, error) {
doc, err := getFilesystemDoc(sb.mb.db(), query, description)
if err != nil {
return nil, errors.Trace(err)
}
return &filesystem{sb.mb, doc}, nil
}
func getFilesystemDocByTag(db Database, tag names.FilesystemTag) (filesystemDoc, error) {
query := bson.D{{"_id", tag.Id()}}
description := fmt.Sprintf("filesystem %q", tag.Id())
return getFilesystemDoc(db, query, description)
}
func getFilesystemDoc(db Database, query bson.D, description string) (filesystemDoc, error) {
coll, cleanup := db.GetCollection(filesystemsC)
defer cleanup()
var doc filesystemDoc
err := coll.Find(query).One(&doc)
if err == mgo.ErrNotFound {
return doc, errors.NotFoundf(description)
} else if err != nil {
return doc, errors.Annotate(err, "cannot get filesystem")
}
if err := doc.validate(); err != nil {
return doc, errors.Annotate(err, "validating filesystem")
}
return doc, nil
}
func getFilesystemDocs(db Database, query interface{}) ([]filesystemDoc, error) {
coll, cleanup := db.GetCollection(filesystemsC)
defer cleanup()
var docs []filesystemDoc
err := coll.Find(query).All(&docs)
if err != nil {
return nil, errors.Trace(err)
}
for _, doc := range docs {
if err := doc.validate(); err != nil {
return nil, errors.Annotate(err, "filesystem validation failed")
}
}
return docs, nil
}
// FilesystemAttachment returns the FilesystemAttachment corresponding to
// the specified filesystem and machine.
func (sb *storageBackend) FilesystemAttachment(host names.Tag, filesystem names.FilesystemTag) (FilesystemAttachment, error) {
coll, cleanup := sb.mb.db().GetCollection(filesystemAttachmentsC)
defer cleanup()
var att filesystemAttachment
err := coll.FindId(filesystemAttachmentId(host.Id(), filesystem.Id())).One(&att.doc)
if err == mgo.ErrNotFound {
return nil, errors.NotFoundf("filesystem %q on %q", filesystem.Id(), names.ReadableString(host))
} else if err != nil {
return nil, errors.Annotatef(err, "getting filesystem %q on %q", filesystem.Id(), names.ReadableString(host))
}
return &att, nil
}
// FilesystemAttachments returns all of the FilesystemAttachments for the
// specified filesystem.
func (sb *storageBackend) FilesystemAttachments(filesystem names.FilesystemTag) ([]FilesystemAttachment, error) {
attachments, err := sb.filesystemAttachments(bson.D{{"filesystemid", filesystem.Id()}})
if err != nil {
return nil, errors.Annotatef(err, "getting attachments for filesystem %q", filesystem.Id())
}
return attachments, nil
}
// MachineFilesystemAttachments returns all of the FilesystemAttachments for the
// specified machine.
func (sb *storageBackend) MachineFilesystemAttachments(machine names.MachineTag) ([]FilesystemAttachment, error) {
attachments, err := sb.filesystemAttachments(bson.D{{"hostid", machine.Id()}})
if err != nil {
return nil, errors.Annotatef(err, "getting filesystem attachments for %q", names.ReadableString(machine))
}
return attachments, nil
}
// UnitFilesystemAttachments returns all of the FilesystemAttachments for the
// specified unit.
func (sb *storageBackend) UnitFilesystemAttachments(unit names.UnitTag) ([]FilesystemAttachment, error) {
attachments, err := sb.filesystemAttachments(bson.D{{"hostid", unit.Id()}})
if err != nil {
return nil, errors.Annotatef(err, "getting filesystem attachments for %q", names.ReadableString(unit))
}
return attachments, nil
}
func (sb *storageBackend) filesystemAttachments(query bson.D) ([]FilesystemAttachment, error) {
coll, cleanup := sb.mb.db().GetCollection(filesystemAttachmentsC)
defer cleanup()
var docs []filesystemAttachmentDoc
err := coll.Find(query).All(&docs)
if err == mgo.ErrNotFound {
return nil, nil
} else if err != nil {
return nil, errors.Trace(err)
}
attachments := make([]FilesystemAttachment, len(docs))
for i, doc := range docs {
attachments[i] = &filesystemAttachment{doc}
}
return attachments, nil
}
// removeMachineFilesystemsOps returns txn.Ops to remove non-persistent filesystems
// attached to the specified machine. This is used when the given machine is
// being removed from state.
func (sb *storageBackend) removeMachineFilesystemsOps(m *Machine) ([]txn.Op, error) {
// A machine cannot transition to Dead if it has any detachable storage
// attached, so any attachments are for machine-bound storage.
//
// Even if a filesystem is "non-detachable", there still exist filesystem
// attachments, and they may be removed independently of the filesystem.
// For example, the user may request that the filesystem be destroyed.
// This will cause the filesystem to become Dying, and the attachment
// to be Dying, then Dead, and finally removed. Only once the attachment
// is removed will the filesystem transition to Dead and then be removed.
// Therefore, there may be filesystems that are bound, but not attached,
// to the machine.
machineFilesystems, err := sb.filesystems(bson.D{{"hostid", m.Id()}})
if err != nil {
return nil, errors.Trace(err)
}
ops := make([]txn.Op, 0, 2*len(machineFilesystems)+len(m.doc.Filesystems))
for _, filesystemId := range m.doc.Filesystems {
ops = append(ops, txn.Op{
C: filesystemAttachmentsC,
Id: filesystemAttachmentId(m.Id(), filesystemId),
Assert: txn.DocExists,
Remove: true,
})
}
for _, f := range machineFilesystems {
if f.doc.StorageId != "" {
// The volume is assigned to a storage instance;
// make sure we also remove the storage instance.
// There should be no storage attachments remaining,
// as the units must have been removed before the
// machine can be; and the storage attachments must
// have been removed before the unit can be.
ops = append(ops,
txn.Op{
C: storageInstancesC,
Id: f.doc.StorageId,
Assert: txn.DocExists,
Remove: true,
},
)
}
fsOps, err := removeFilesystemOps(sb, f, f.doc.Releasing, nil)
if err != nil {
return nil, errors.Trace(err)
}
ops = append(ops, fsOps...)
}
return ops, nil
}
// isDetachableFilesystemTag reports whether or not the filesystem with the
// specified tag is detachable.
func isDetachableFilesystemTag(db Database, tag names.FilesystemTag) (bool, error) {
doc, err := getFilesystemDocByTag(db, tag)
if err != nil {
return false, errors.Trace(err)
}
return doc.HostId == "", nil
}
// Detachable reports whether or not the filesystem is detachable.
func (f *filesystem) Detachable() bool {
return f.doc.HostId == ""
}
func (f *filesystem) pool() string {
if f.doc.Info != nil {
return f.doc.Info.Pool
}
return f.doc.Params.Pool
}
// isDetachableFilesystemPool reports whether or not the given
// storage pool will create a filesystem that is not inherently
// bound to a machine, and therefore can be detached.
func isDetachableFilesystemPool(sb *storageBackend, pool string) (bool, error) {
_, provider, _, err := poolStorageProvider(sb, pool)
if err != nil {
return false, errors.Trace(err)
}
if provider.Scope() == storage.ScopeMachine {
// Any storage created by a machine cannot be detached from
// the machine, and must be destroyed along with it.
return false, nil
}
if !provider.Dynamic() {
// The storage provider only accommodates provisioning storage
// statically along with the machine. Such storage is bound
// to the machine.
return false, nil
}
return true, nil
}
// DetachFilesystem marks the filesystem attachment identified by the specified machine
// and filesystem tags as Dying, if it is Alive. DetachFilesystem will fail for
// inherently machine-bound filesystems.
func (sb *storageBackend) DetachFilesystem(host names.Tag, filesystem names.FilesystemTag) (err error) {
defer errors.DeferredAnnotatef(&err, "detaching filesystem %s from %s", filesystem.Id(), names.ReadableString(host))
buildTxn := func(attempt int) ([]txn.Op, error) {
fsa, err := sb.FilesystemAttachment(host, filesystem)
if err != nil {
return nil, errors.Trace(err)
}
if fsa.Life() != Alive {
return nil, jujutxn.ErrNoOperations
}
detachable, err := isDetachableFilesystemTag(sb.mb.db(), filesystem)
if err != nil {
return nil, errors.Trace(err)
}
if !detachable {
return nil, errors.New("filesystem is not detachable")
}
ops := detachFilesystemOps(host, filesystem)
return ops, nil
}
return sb.mb.db().Run(buildTxn)
}
func (sb *storageBackend) filesystemVolumeAttachment(host names.Tag, f names.FilesystemTag) (VolumeAttachment, error) {
filesystem, err := getFilesystemByTag(sb.mb, f)
if err != nil {
return nil, errors.Trace(err)
}
v, err := filesystem.Volume()
if err != nil {
return nil, errors.Trace(err)
}
return sb.VolumeAttachment(host, v)
}
func detachFilesystemOps(host names.Tag, f names.FilesystemTag) []txn.Op {
return []txn.Op{{
C: filesystemAttachmentsC,
Id: filesystemAttachmentId(host.Id(), f.Id()),
Assert: isAliveDoc,
Update: bson.D{{"$set", bson.D{{"life", Dying}}}},
}}
}
// RemoveFilesystemAttachment removes the filesystem attachment from state.
// Removing a volume-backed filesystem attachment will cause the volume to
// be detached.
func (sb *storageBackend) RemoveFilesystemAttachment(host names.Tag, filesystem names.FilesystemTag) (err error) {
defer errors.DeferredAnnotatef(&err, "removing attachment of filesystem %s from %s", filesystem.Id(), names.ReadableString(host))
buildTxn := func(attempt int) ([]txn.Op, error) {
attachment, err := sb.FilesystemAttachment(host, filesystem)
if errors.IsNotFound(err) && attempt > 0 {
// We only ignore IsNotFound on attempts after the
// first, since we expect the filesystem attachment to
// be there initially.
return nil, jujutxn.ErrNoOperations
}
if err != nil {
return nil, errors.Trace(err)
}
if attachment.Life() != Dying {
return nil, errors.New("filesystem attachment is not dying")
}
f, err := getFilesystemByTag(sb.mb, filesystem)
if err != nil {
return nil, errors.Trace(err)
}
ops, err := removeFilesystemAttachmentOps(sb, host, f)
if err != nil {
return nil, errors.Trace(err)
}
volumeAttachment, err := sb.filesystemVolumeAttachment(host, filesystem)
if err != nil {
if errors.Cause(err) != ErrNoBackingVolume && !errors.IsNotFound(err) {
return nil, errors.Trace(err)
}
} else {
// The filesystem is backed by a volume. Since the
// filesystem has been detached, we should now
// detach the volume as well if it is detachable.
// If the volume is not detachable, we'll just
// destroy it along with the filesystem.
volume := volumeAttachment.Volume()
detachableVolume, err := isDetachableVolumeTag(sb.mb.db(), volume)
if err != nil {
return nil, errors.Trace(err)
}
if detachableVolume {
plans, err := sb.machineVolumeAttachmentPlans(host, volume)
if err != nil {
return nil, errors.Trace(err)
}
// NOTE(gsamfira): if we're upgrading, we might not have plans set up,
// so we check if volume plans were created, and if not, just skip to
// detaching the actual disk
var volOps []txn.Op
if plans == nil || len(plans) == 0 {
volOps = detachVolumeOps(host, volume)
} else {
volOps = detachStorageAttachmentOps(host, volume)
}
ops = append(ops, volOps...)
}
}
return ops, nil
}
return sb.mb.db().Run(buildTxn)
}
func removeFilesystemAttachmentOps(sb *storageBackend, host names.Tag, f *filesystem) ([]txn.Op, error) {
var ops []txn.Op
if f.doc.VolumeId != "" && f.doc.Life == Dying && f.doc.AttachmentCount == 1 {
// Volume-backed filesystems are removed immediately, instead
// of transitioning to Dead.
assert := bson.D{
{"life", Dying},
{"attachmentcount", 1},
}
removeFilesystemOps, err := removeFilesystemOps(sb, f, f.doc.Releasing, assert)
if err != nil {
return nil, errors.Trace(err)
}
ops = removeFilesystemOps
} else {
decrefFilesystemOp := machineStorageDecrefOp(
filesystemsC, f.doc.FilesystemId,
f.doc.AttachmentCount, f.doc.Life,
)
ops = []txn.Op{decrefFilesystemOp}
}
ops = append(ops, txn.Op{
C: filesystemAttachmentsC,
Id: filesystemAttachmentId(host.Id(), f.doc.FilesystemId),
Assert: bson.D{{"life", Dying}},
Remove: true,
})
if host.Kind() == names.MachineTagKind {
ops = append(ops, txn.Op{
C: machinesC,
Id: host.Id(),
Assert: txn.DocExists,
Update: bson.D{{"$pull", bson.D{{"filesystems", f.doc.FilesystemId}}}},
})
}
return ops, nil
}
// DestroyFilesystem ensures that the filesystem and any attachments to it will
// be destroyed and removed from state at some point in the future.
func (sb *storageBackend) DestroyFilesystem(tag names.FilesystemTag) (err error) {
defer errors.DeferredAnnotatef(&err, "destroying filesystem %s", tag.Id())
buildTxn := func(attempt int) ([]txn.Op, error) {
filesystem, err := getFilesystemByTag(sb.mb, tag)
if errors.IsNotFound(err) && attempt > 0 {
// On the first attempt, we expect it to exist.
return nil, jujutxn.ErrNoOperations
} else if err != nil {
return nil, errors.Trace(err)
}
if filesystem.Life() != Alive {
return nil, jujutxn.ErrNoOperations
}
if filesystem.doc.StorageId != "" {
return nil, errors.Errorf(
"filesystem is assigned to %s",
names.ReadableString(names.NewStorageTag(filesystem.doc.StorageId)),
)
}
hasNoStorageAssignment := bson.D{{"$or", []bson.D{
{{"storageid", ""}},
{{"storageid", bson.D{{"$exists", false}}}},
}}}
return destroyFilesystemOps(sb, filesystem, false, hasNoStorageAssignment)
}
return sb.mb.db().Run(buildTxn)
}
func destroyFilesystemOps(sb *storageBackend, f *filesystem, release bool, extraAssert bson.D) ([]txn.Op, error) {
baseAssert := append(isAliveDoc, extraAssert...)
setFields := bson.D{}
if release {
setFields = append(setFields, bson.DocElem{"releasing", true})
}
if f.doc.AttachmentCount == 0 {
hasNoAttachments := bson.D{{"attachmentcount", 0}}
assert := append(hasNoAttachments, baseAssert...)
if f.doc.VolumeId != "" {
// Filesystem is volume-backed, and since it has no
// attachments, it has no provisioner responsible
// for it. Removing the filesystem will destroy the
// backing volume, which effectively destroys the
// filesystem contents anyway.
return removeFilesystemOps(sb, f, release, assert)
}
// The filesystem is not volume-backed, so leave it to the
// storage provisioner to destroy it.
setFields = append(setFields, bson.DocElem{"life", Dead})
return []txn.Op{{
C: filesystemsC,
Id: f.doc.FilesystemId,
Assert: assert,
Update: bson.D{{"$set", setFields}},
}}, nil
}
hasAttachments := bson.D{{"attachmentcount", bson.D{{"$gt", 0}}}}
setFields = append(setFields, bson.DocElem{"life", Dying})
ops := []txn.Op{{
C: filesystemsC,
Id: f.doc.FilesystemId,
Assert: append(hasAttachments, baseAssert...),
Update: bson.D{{"$set", setFields}},
}}
if !f.Detachable() {
// This filesystem cannot be directly detached, so we do
// not issue a cleanup. Since there can (should!) be only
// one attachment for the lifetime of the filesystem, we
// can look it up and destroy it along with the filesystem.
attachments, err := sb.FilesystemAttachments(f.FilesystemTag())
if err != nil {
return nil, errors.Trace(err)
}
if len(attachments) != 1 {
return nil, errors.Errorf(
"expected 1 attachment, found %d",
len(attachments),
)
}
detachOps := detachFilesystemOps(
attachments[0].Host(),
f.FilesystemTag(),
)
ops = append(ops, detachOps...)
} else {
ops = append(ops, newCleanupOp(
cleanupAttachmentsForDyingFilesystem,
f.doc.FilesystemId,
))
}
return ops, nil
}
// RemoveFilesystem removes the filesystem from state. RemoveFilesystem will
// fail if there are any attachments remaining, or if the filesystem is not
// Dying. Removing a volume-backed filesystem will cause the volume to be
// destroyed.
func (sb *storageBackend) RemoveFilesystem(tag names.FilesystemTag) (err error) {
defer errors.DeferredAnnotatef(&err, "removing filesystem %s", tag.Id())
buildTxn := func(attempt int) ([]txn.Op, error) {
filesystem, err := getFilesystemByTag(sb.mb, tag)
if errors.IsNotFound(err) {
return nil, jujutxn.ErrNoOperations
} else if err != nil {
return nil, errors.Trace(err)
}
if filesystem.Life() != Dead {
return nil, errors.New("filesystem is not dead")
}
return removeFilesystemOps(sb, filesystem, false, isDeadDoc)
}
return sb.mb.db().Run(buildTxn)
}
func removeFilesystemOps(sb *storageBackend, filesystem Filesystem, release bool, assert interface{}) ([]txn.Op, error) {
ops := []txn.Op{
{
C: filesystemsC,
Id: filesystem.Tag().Id(),
Assert: assert,
Remove: true,
},
removeModelFilesystemRefOp(sb.mb, filesystem.Tag().Id()),
removeStatusOp(sb.mb, filesystem.globalKey()),
}
// If the filesystem is backed by a volume, the volume should
// be destroyed once the filesystem is removed. The volume must
// not be destroyed before the filesystem is removed.
volumeTag, err := filesystem.Volume()
if err == nil {
volume, err := getVolumeByTag(sb.mb, volumeTag)
if err != nil {
return nil, errors.Trace(err)
}
volOps, err := destroyVolumeOps(sb, volume, release, nil)
if err != nil {
return nil, errors.Trace(err)
}
ops = append(ops, volOps...)
} else if err != ErrNoBackingVolume {
return nil, errors.Trace(err)
}
return ops, nil
}
// AddExistingFilesystem imports an existing, already-provisioned
// filesystem into the model. The model will start out with
// the status "detached". The filesystem and associated backing
// volume (if any) will be associated with the given storage
// name, with the allocated storage tag being returned.
func (sb *storageBackend) AddExistingFilesystem(
info FilesystemInfo,
backingVolume *VolumeInfo,
storageName string,
) (_ names.StorageTag, err error) {
defer errors.DeferredAnnotatef(&err, "cannot add existing filesystem")
if err := validateAddExistingFilesystem(sb, info, backingVolume, storageName); err != nil {
return names.StorageTag{}, errors.Trace(err)
}
storageId, err := newStorageInstanceId(sb.mb, storageName)
if err != nil {
return names.StorageTag{}, errors.Trace(err)
}
storageTag := names.NewStorageTag(storageId)
fsOps, _, volumeTag, err := sb.addFilesystemOps(
FilesystemParams{
Pool: info.Pool,
Size: info.Size,
filesystemId: info.FilesystemId,
volumeInfo: backingVolume,
storage: storageTag,
},
"", // no machine ID
)
if err != nil {
return names.StorageTag{}, errors.Trace(err)
}
if volumeTag != (names.VolumeTag{}) && backingVolume == nil {
return names.StorageTag{}, errors.Errorf("backing volume info missing")
}
ops := []txn.Op{{
C: storageInstancesC,
Id: storageId,
Assert: txn.DocMissing,
Insert: &storageInstanceDoc{
Id: storageId,
Kind: StorageKindFilesystem,
StorageName: storageName,
Constraints: storageInstanceConstraints{
Pool: info.Pool,
Size: info.Size,
},
},
}}
ops = append(ops, fsOps...)
if err := sb.mb.db().RunTransaction(ops); err != nil {
return names.StorageTag{}, errors.Trace(err)
}
return storageTag, nil
}
var storageNameRE = regexp.MustCompile(names.StorageNameSnippet)
func validateAddExistingFilesystem(
sb *storageBackend,
info FilesystemInfo,
backingVolume *VolumeInfo,
storageName string,
) error {
if !storage.IsValidPoolName(info.Pool) {
return errors.NotValidf("pool name %q", info.Pool)
}
if !storageNameRE.MatchString(storageName) {
return errors.NotValidf("storage name %q", storageName)
}
if backingVolume == nil {
if info.FilesystemId == "" {
return errors.NotValidf("empty filesystem ID")
}
} else {
if info.FilesystemId != "" {
return errors.NotValidf("non-empty filesystem ID with backing volume")
}
if backingVolume.VolumeId == "" {
return errors.NotValidf("empty backing volume ID")
}
if backingVolume.Pool != info.Pool {
return errors.Errorf(
"volume pool %q does not match filesystem pool %q",
backingVolume.Pool, info.Pool,
)
}
if backingVolume.Size != info.Size {
return errors.Errorf(
"volume size %d does not match filesystem size %d",
backingVolume.Size, info.Size,
)
}
}
_, provider, _, err := poolStorageProvider(sb, info.Pool)
if err != nil {
return errors.Trace(err)
}
if !provider.Supports(storage.StorageKindFilesystem) {
if backingVolume == nil {
return errors.New("backing volume info missing")
}
} else {
if backingVolume != nil {
return errors.New("unexpected volume info")
}
}
return nil
}