-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
mount_interrupter.go
82 lines (73 loc) · 1.96 KB
/
mount_interrupter.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
// Copyright 2017 Keybase Inc. All rights reserved.
// Use of this source code is governed by a BSD
// license that can be found in the LICENSE file.
package libfs
import (
"errors"
"sync"
"github.com/keybase/client/go/logger"
)
// Mounter is the interface for filesystems to be mounted by MountInterrupter.
type Mounter interface {
// Mount a filesystem.
Mount() error
// Unmount a mounted filesystem.
Unmount() error
}
// MountInterrupter is for managing mounts with cancelation.
type MountInterrupter struct {
// can be locked from external code too.
sync.Mutex
once sync.Once
done chan struct{}
fun func() error
log logger.Logger
}
// NewMountInterrupter creates a new MountInterrupter.
func NewMountInterrupter(log logger.Logger) *MountInterrupter {
return &MountInterrupter{done: make(chan struct{}), log: log}
}
// MountAndSetUnmount calls Mount and sets the unmount function
// to be called once if mount succeeds.
// If Done has already been called MountAndSetUnmount returns
// an error.
func (mi *MountInterrupter) MountAndSetUnmount(mounter Mounter) error {
mi.log.Debug("Starting to mount the filesystem")
mi.Lock()
defer mi.Unlock()
select {
case <-mi.done:
return errors.New("MountInterrupter already done")
default:
}
err := mounter.Mount()
if err != nil {
mi.log.Errorf("Mounting the filesystem failed: %v", err)
return err
}
mi.fun = mounter.Unmount
mi.log.Info("Mounting the filesystem was a success")
return nil
}
// Done signals Wait and runs the unmounter if set by MountAndSetUnmount.
// It can be called multiple times with no harm. Each call triggers a call to
// the unmounter.
func (mi *MountInterrupter) Done() error {
mi.Lock()
defer mi.Unlock()
if mi.fun != nil {
err := mi.fun()
if err != nil {
mi.log.Errorf("Mount interrupter callback failed: %v", err)
return err
}
}
mi.once.Do(func() {
close(mi.done)
})
return nil
}
// Wait waits till Done is called.
func (mi *MountInterrupter) Wait() {
<-mi.done
}