forked from zach-klippenstein/adbfs
/
main.go
221 lines (184 loc) · 5.22 KB
/
main.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
/*
Another FUSE filesystem that can mount any device visible to your adb server.
Uses github.com/zach-klippenstein/goadb to interface with the server directly
instead of calling out to the adb client program.
See package adbfs for the filesystem implementation.
*/
package main
import (
"errors"
"fmt"
_ "net/http/pprof"
"os"
"os/signal"
"path/filepath"
"time"
"github.com/hanwen/go-fuse/fuse"
"github.com/hanwen/go-fuse/fuse/nodefs"
"github.com/hanwen/go-fuse/fuse/pathfs"
fs "github.com/Henri-J-Norden/adbfs"
"github.com/Henri-J-Norden/adbfs/internal/cli"
. "github.com/Henri-J-Norden/adbfs/internal/util"
"github.com/zach-klippenstein/goadb"
)
const StartTimeout = 5 * time.Second
var (
config cli.AdbfsConfig
server *fuse.Server
mounted AtomicBool
// Prevents trying to unmount the server multiple times.
unmounted AtomicBool
)
func init() {
cli.RegisterAdbfsFlags(&config)
}
func main() {
cli.Initialize("adbfs", &config.BaseConfig)
if config.DeviceSerial == "" {
cli.Log.Fatalln("Device serial must be specified. Run with -h.")
}
if config.Mountpoint == "" {
cli.Log.Fatalln("Mountpoint must be specified. Run with -h.")
}
absoluteMountpoint, err := filepath.Abs(config.Mountpoint)
if err != nil {
cli.Log.Fatal(err)
}
if err = checkValidMountpoint(absoluteMountpoint); err != nil {
cli.Log.Fatal(err)
}
cache := initializeCache(config.CacheTtl)
adbServer, err := adb.NewServer(config.ServerConfig())
if err != nil {
cli.Log.Fatal(err)
}
fs := initializeFileSystem(adbServer, absoluteMountpoint, cache)
go watchForDeviceDisconnected(adbServer, config.DeviceSerial)
server, _, err = nodefs.MountRoot(absoluteMountpoint, fs.Root(), nil)
if err != nil {
cli.Log.Fatal(err)
}
serverDone, err := startServer(StartTimeout)
if err != nil {
cli.Log.Fatal(err)
}
cli.Log.Printf("mounted %s on %s", config.DeviceSerial, absoluteMountpoint)
mounted.CompareAndSwap(false, true)
defer unmountServer()
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Interrupt, os.Kill)
for {
select {
case signal := <-signals:
cli.Log.Println("got signal", signal)
switch signal {
case os.Kill, os.Interrupt:
cli.Log.Println("exiting...")
return
}
case <-serverDone:
cli.Log.Debugln("server done channel closed.")
return
}
}
}
func initializeCache(ttl time.Duration) fs.DirEntryCache {
cli.Log.Infoln("stat cache ttl:", ttl)
return fs.NewDirEntryCache(ttl)
}
func initializeFileSystem(server adb.Server, mountpoint string, cache fs.DirEntryCache) *pathfs.PathNodeFs {
clientFactory := fs.NewCachingDeviceClientFactory(cache,
fs.NewGoadbDeviceClientFactory(server, config.DeviceSerial, handleDeviceDisconnected))
var fsImpl pathfs.FileSystem
fsImpl, err := fs.NewAdbFileSystem(fs.Config{
DeviceSerial: config.DeviceSerial,
Mountpoint: mountpoint,
ClientFactory: clientFactory,
ConnectionPoolSize: config.ConnectionPoolSize,
DeviceRoot: config.DeviceRoot,
ReadOnly: config.ReadOnly,
})
if err != nil {
cli.Log.Fatal(err)
}
return pathfs.NewPathNodeFs(fsImpl, nil)
}
func watchForDeviceDisconnected(server adb.Server, serial string) {
watcher := adb.NewDeviceWatcher(server)
defer watcher.Shutdown()
for {
select {
case event, ok := <-watcher.C():
if !ok {
// Channel closed.
break
}
if event.Serial == serial && event.WentOffline() {
cli.Log.Infoln("device disconnected:", serial)
handleDeviceDisconnected()
}
}
}
if err := watcher.Err(); err != nil {
cli.Log.Warn("DeviceWatcher disconnected with error:", err)
}
}
func startServer(startTimeout time.Duration) (<-chan struct{}, error) {
serverDone := make(chan struct{})
go func() {
defer close(serverDone)
server.Serve()
cli.Log.Println("server finished.")
return
}()
// Wait for OS to finish initializing the mount.
// If server.Serve() fails (e.g. mountpoint doesn't exist), WaitMount() won't
// ever return. Running it in a separate goroutine allows us to detect that case.
serverReady := make(chan struct{})
go func() {
defer close(serverReady)
server.WaitMount()
}()
select {
case <-serverReady:
cli.Log.Println("server ready.")
return serverDone, nil
case <-serverDone:
return nil, errors.New("unknown error")
case <-time.After(startTimeout):
return nil, errors.New(fmt.Sprint("server failed to start after", startTimeout))
}
}
func unmountServer() {
if server == nil {
panic("attempted to unmount server before creating it")
}
if !mounted.Value() {
panic("attempted to unmount server before mounting it")
}
if unmounted.CompareAndSwap(false, true) {
cli.Log.Println("unmounting...")
server.Unmount()
cli.Log.Println("unmounted.")
}
}
// handleDeviceDisconnected is called either when the DeviceWatcher or the adb.DeviceClient detect
// a device is disconnected.
func handleDeviceDisconnected() {
if !mounted.Value() || unmounted.Value() {
// May be called before mounting if device watcher detects disconnection.
return
}
cli.Log.Infoln("device disconnected, unmounting...")
unmountServer()
}
func checkValidMountpoint(path string) error {
info, err := os.Stat(path)
if err != nil {
return err
}
if !info.IsDir() {
return errors.New(fmt.Sprint("path is not a directory:", path))
}
return nil
}