sshfs-offline 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sshfs-offline/__init__.py +0 -0
- sshfs-offline/cli.py +340 -0
- sshfs-offline/data.py +166 -0
- sshfs-offline/log.py +49 -0
- sshfs-offline/metadata.py +166 -0
- sshfs-offline/metrics.py +64 -0
- sshfs-offline/sftp.py +188 -0
- sshfs_offline-0.0.1.dist-info/METADATA +161 -0
- sshfs_offline-0.0.1.dist-info/RECORD +13 -0
- sshfs_offline-0.0.1.dist-info/WHEEL +5 -0
- sshfs_offline-0.0.1.dist-info/entry_points.txt +2 -0
- sshfs_offline-0.0.1.dist-info/licenses/LICENSE +21 -0
- sshfs_offline-0.0.1.dist-info/top_level.txt +1 -0
|
File without changes
|
sshfs-offline/cli.py
ADDED
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
|
|
3
|
+
import errno
|
|
4
|
+
from logging import getLogger
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
import getpass
|
|
9
|
+
import sys
|
|
10
|
+
|
|
11
|
+
import metrics
|
|
12
|
+
import sftp
|
|
13
|
+
from sftp import fixPath
|
|
14
|
+
|
|
15
|
+
from fuse import FUSE, FuseOSError, Operations
|
|
16
|
+
|
|
17
|
+
import data
|
|
18
|
+
import metadata
|
|
19
|
+
import log
|
|
20
|
+
|
|
21
|
+
class Main(Operations):
|
|
22
|
+
'''
|
|
23
|
+
A simple SFTP filesystem. Requires paramiko: http://www.lag.net/paramiko/
|
|
24
|
+
|
|
25
|
+
You need to be able to login o remote host without entering a password.
|
|
26
|
+
'''
|
|
27
|
+
|
|
28
|
+
HOME_DIR = str(Path.home())
|
|
29
|
+
CACHE_TIMEOUT = 5 * 60
|
|
30
|
+
|
|
31
|
+
def __init__(self, args):
|
|
32
|
+
self.debug = args.debug
|
|
33
|
+
host = args.host
|
|
34
|
+
user = args.user
|
|
35
|
+
remotedir = args.remotedir
|
|
36
|
+
port = args.port
|
|
37
|
+
|
|
38
|
+
self.log = getLogger(log.MAIN)
|
|
39
|
+
|
|
40
|
+
metrics.counts = metrics.Metrics()
|
|
41
|
+
sftp.manager = sftp.SFTPManager(host, user, remotedir, port)
|
|
42
|
+
metadata.cache = metadata.Metadata(host, remotedir, args.cachetimeout)
|
|
43
|
+
data.cache = data.Data(host, remotedir)
|
|
44
|
+
|
|
45
|
+
sftp.manager.sftp() # verify connection to host
|
|
46
|
+
|
|
47
|
+
def init(self, path):
|
|
48
|
+
metrics.counts.incr('init')
|
|
49
|
+
metrics.counts.start()
|
|
50
|
+
log.Log().setupConfig(self.debug)
|
|
51
|
+
sftp.manager.startKeepalive()
|
|
52
|
+
|
|
53
|
+
def chmod(self, path, mode):
|
|
54
|
+
try:
|
|
55
|
+
self.log.debug('-> chmod: %s %s', path, mode)
|
|
56
|
+
metrics.counts.incr('chmod')
|
|
57
|
+
metadata.cache.deleteMetadata(path)
|
|
58
|
+
sftp.manager.sftp().chmod(fixPath(path), mode)
|
|
59
|
+
self.log.debug('<- chmod: %s', path)
|
|
60
|
+
except Exception as e:
|
|
61
|
+
self.log.error('<- chmod: %s %s', path, mode)
|
|
62
|
+
metrics.counts.incr('chmod_except')
|
|
63
|
+
raise e
|
|
64
|
+
|
|
65
|
+
def chown(self, path, uid, gid):
|
|
66
|
+
try:
|
|
67
|
+
self.log.debug('-> chown: %s %s %s', path, uid, gid)
|
|
68
|
+
metrics.counts.incr('chown')
|
|
69
|
+
metadata.cache.deleteMetadata(path)
|
|
70
|
+
sftp.manager.sftp().chown(fixPath(path), uid, gid)
|
|
71
|
+
self.log.debug('<- chown: %s', path)
|
|
72
|
+
except Exception as e:
|
|
73
|
+
self.log.error('<- chown: %s %s %s', path, uid, gid)
|
|
74
|
+
metrics.counts.incr('chown_except')
|
|
75
|
+
raise e
|
|
76
|
+
|
|
77
|
+
def create(self, path, mode):
|
|
78
|
+
try:
|
|
79
|
+
self.log.debug('-> create: %s %s', path, mode)
|
|
80
|
+
metrics.counts.incr('create')
|
|
81
|
+
metadata.cache.deleteMetadata(path)
|
|
82
|
+
metadata.cache.deleteParentMetadata(path)
|
|
83
|
+
f = sftp.manager.sftp().open(fixPath(path), 'w')
|
|
84
|
+
f.chmod(mode)
|
|
85
|
+
f.close()
|
|
86
|
+
self.log.debug('<- create: %s', path)
|
|
87
|
+
return 0
|
|
88
|
+
except Exception as e:
|
|
89
|
+
self.log.error('<- create: %s %s', path, mode)
|
|
90
|
+
metrics.counts.incr('create_except')
|
|
91
|
+
raise e
|
|
92
|
+
|
|
93
|
+
def destroy(self, path):
|
|
94
|
+
try:
|
|
95
|
+
self.log.debug('-> destroy: %s', path)
|
|
96
|
+
metrics.counts.incr('destroy')
|
|
97
|
+
sftp.manager.sftp().close()
|
|
98
|
+
self.log.debug('<- destroy: %s', path)
|
|
99
|
+
except Exception as e:
|
|
100
|
+
self.log.error('<- destroy: %s', path)
|
|
101
|
+
metrics.counts.incr('destroy_except')
|
|
102
|
+
raise e
|
|
103
|
+
finally:
|
|
104
|
+
metrics.counts.stop()
|
|
105
|
+
sftp.manager.stop()
|
|
106
|
+
|
|
107
|
+
def getattr(self, path, fh=None):
|
|
108
|
+
try:
|
|
109
|
+
self.log.debug('-> getattr: %s', path)
|
|
110
|
+
metrics.counts.incr('getattr')
|
|
111
|
+
d = metadata.cache.getattr(path)
|
|
112
|
+
if d != None:
|
|
113
|
+
if d == {}:
|
|
114
|
+
raise FuseOSError(errno.ENOENT)
|
|
115
|
+
else:
|
|
116
|
+
self.log.debug('<- getattr: %s', path)
|
|
117
|
+
return d # cache hit
|
|
118
|
+
|
|
119
|
+
try:
|
|
120
|
+
st = sftp.manager.sftp().lstat(fixPath(path))
|
|
121
|
+
except IOError as e:
|
|
122
|
+
metadata.cache.getattr_save(path, {}) # negative cache entry
|
|
123
|
+
raise FuseOSError(errno.ENOENT)
|
|
124
|
+
|
|
125
|
+
d = dict((key, getattr(st, key)) for key in (
|
|
126
|
+
'st_atime', 'st_gid', 'st_mode', 'st_mtime', 'st_size', 'st_uid'))
|
|
127
|
+
metadata.cache.getattr_save(path, d)
|
|
128
|
+
self.log.debug('<- getattr: %s %s', path, d)
|
|
129
|
+
return d
|
|
130
|
+
except Exception as e:
|
|
131
|
+
if not isinstance(e, OSError) and OSError(e).errno != errno.ENOENT:
|
|
132
|
+
self.log.error('<- getattr: %s %s', path, e)
|
|
133
|
+
metrics.counts.incr('getattr_except')
|
|
134
|
+
raise e
|
|
135
|
+
|
|
136
|
+
def statfs(self, path):
|
|
137
|
+
try:
|
|
138
|
+
self.log.debug('-> statfs: %s', path)
|
|
139
|
+
metrics.counts.incr('statfs')
|
|
140
|
+
stv = data.cache.statvfs(path)
|
|
141
|
+
dic = dict((key, getattr(stv, key)) for key in ('f_bavail', 'f_bfree',
|
|
142
|
+
'f_blocks', 'f_bsize', 'f_favail', 'f_ffree', 'f_files', 'f_flag',
|
|
143
|
+
'f_frsize', 'f_namemax'))
|
|
144
|
+
self.log.debug('<- statfs: %s %s', path, dic)
|
|
145
|
+
return dic
|
|
146
|
+
except Exception as e:
|
|
147
|
+
self.log.error('<- statfs: %s', path)
|
|
148
|
+
metrics.counts.incr('statfs_except')
|
|
149
|
+
raise e
|
|
150
|
+
|
|
151
|
+
def mkdir(self, path, mode):
|
|
152
|
+
try:
|
|
153
|
+
self.log.debug('-> mkdir: %s %s', path, mode)
|
|
154
|
+
metrics.counts.incr('mkdir')
|
|
155
|
+
metadata.cache.deleteMetadata(path)
|
|
156
|
+
metadata.cache.deleteParentMetadata(path)
|
|
157
|
+
sftp.manager.sftp().mkdir(fixPath(path), mode)
|
|
158
|
+
self.log.debug('<- mkdir: %s', path)
|
|
159
|
+
except Exception as e:
|
|
160
|
+
self.log.error('<- mkdir: %s %s', path, mode)
|
|
161
|
+
metrics.counts.incr('mkdir_except')
|
|
162
|
+
raise e
|
|
163
|
+
|
|
164
|
+
def read(self, path, size, offset, fh):
|
|
165
|
+
try:
|
|
166
|
+
self.log.debug('-> read: %s size=%d offset=%d', path, size, offset)
|
|
167
|
+
metrics.counts.incr('read')
|
|
168
|
+
|
|
169
|
+
buf = data.cache.read(path, size, offset, fh)
|
|
170
|
+
|
|
171
|
+
self.log.debug('<- read: %s %d', path, len(buf))
|
|
172
|
+
return buf
|
|
173
|
+
except Exception as e:
|
|
174
|
+
self.log.error('<- read: %s %s %d', path, size, offset)
|
|
175
|
+
metrics.counts.incr('read_except')
|
|
176
|
+
raise e
|
|
177
|
+
|
|
178
|
+
def readdir(self, path, fh):
|
|
179
|
+
try:
|
|
180
|
+
self.log.debug('-> readdir: %s', path)
|
|
181
|
+
metrics.counts.incr('readdir')
|
|
182
|
+
s = metadata.cache.readdir(path)
|
|
183
|
+
if s != None:
|
|
184
|
+
self.log.debug('<- readdir: %s %d', path, len(s))
|
|
185
|
+
return s
|
|
186
|
+
s = ['.', '..'] + [name
|
|
187
|
+
for name in sftp.manager.sftp().listdir(fixPath(path))]
|
|
188
|
+
metadata.cache.readdir_save(path, s)
|
|
189
|
+
s = metadata.cache.readdir(path)
|
|
190
|
+
self.log.debug('<- readdir: %s %d', path, len(s))
|
|
191
|
+
return s
|
|
192
|
+
except Exception as e:
|
|
193
|
+
self.log.error('<- readdir: %s', path)
|
|
194
|
+
metrics.counts.incr('readdir_except')
|
|
195
|
+
raise e
|
|
196
|
+
|
|
197
|
+
def readlink(self, path):
|
|
198
|
+
try:
|
|
199
|
+
self.log.debug('-> readlink: %s', path)
|
|
200
|
+
metrics.counts.incr('readlink')
|
|
201
|
+
link = metadata.cache.readlink(path)
|
|
202
|
+
if link == None:
|
|
203
|
+
link = sftp.manager.sftp().readlink(fixPath(path))
|
|
204
|
+
metadata.cache.readlink_save(path, link)
|
|
205
|
+
|
|
206
|
+
self.log.debug('<- readlink: %s %s', path, link)
|
|
207
|
+
return link
|
|
208
|
+
except Exception as e:
|
|
209
|
+
self.log.error('<- readlink: %s', path)
|
|
210
|
+
metrics.counts.incr('readlink_except')
|
|
211
|
+
raise e
|
|
212
|
+
|
|
213
|
+
def rename(self, old, new):
|
|
214
|
+
try:
|
|
215
|
+
self.log.debug('-> rename: %s %s', old, new)
|
|
216
|
+
metrics.counts.incr('rename')
|
|
217
|
+
metadata.cache.deleteMetadata(old)
|
|
218
|
+
sftp.manager.sftp().rename(fixPath(old), fixPath(new))
|
|
219
|
+
self.log.debug('<- rename: %s %s', old, new)
|
|
220
|
+
except Exception as e:
|
|
221
|
+
self.log.error('<- rename: %s %s', old, new)
|
|
222
|
+
metrics.counts.incr('rename_except')
|
|
223
|
+
raise e
|
|
224
|
+
|
|
225
|
+
def rmdir(self, path):
|
|
226
|
+
try:
|
|
227
|
+
self.log.debug('-> rmdir: %s', path)
|
|
228
|
+
metrics.counts.incr('rmdir')
|
|
229
|
+
metadata.cache.deleteMetadata(path)
|
|
230
|
+
metadata.cache.deleteParentMetadata(path)
|
|
231
|
+
sftp.manager.sftp().rmdir(fixPath(path))
|
|
232
|
+
self.log.debug('<- rmdir: %s', path)
|
|
233
|
+
except Exception as e:
|
|
234
|
+
self.log.error('<- rmdir: %s', path)
|
|
235
|
+
metrics.counts.incr('rmdir_except')
|
|
236
|
+
raise e
|
|
237
|
+
|
|
238
|
+
def symlink(self, target, source):
|
|
239
|
+
try:
|
|
240
|
+
self.log.debug('-> symlink: %s %s', target, source)
|
|
241
|
+
metrics.counts.incr('symlink')
|
|
242
|
+
sftp.manager.sftp().symlink(fixPath(source), fixPath(target))
|
|
243
|
+
self.log.debug('<- symlink: %s %s', target, source)
|
|
244
|
+
except Exception as e:
|
|
245
|
+
self.log.error('<- symlink: %s %s', target, source)
|
|
246
|
+
metrics.counts.incr('symlink_except')
|
|
247
|
+
raise e
|
|
248
|
+
|
|
249
|
+
def truncate(self, path, length, fh=None):
|
|
250
|
+
try:
|
|
251
|
+
self.log.debug('-> truncate: %s %d', path, length)
|
|
252
|
+
metrics.counts.incr('truncate')
|
|
253
|
+
metadata.cache.deleteMetadata(path)
|
|
254
|
+
data.cache.deleteStaleFile(path)
|
|
255
|
+
sftp.manager.sftp().truncate(fixPath(path), length)
|
|
256
|
+
self.log.debug('<- truncate: %s', path)
|
|
257
|
+
except Exception as e:
|
|
258
|
+
self.log.error('<- truncate: %s %d', path, length)
|
|
259
|
+
metrics.counts.incr('truncate_except')
|
|
260
|
+
raise e
|
|
261
|
+
|
|
262
|
+
def unlink(self, path):
|
|
263
|
+
try:
|
|
264
|
+
self.log.debug('-> unlink: %s', path)
|
|
265
|
+
metrics.counts.incr('unlink')
|
|
266
|
+
metadata.cache.deleteMetadata(path)
|
|
267
|
+
metadata.cache.deleteParentMetadata(path)
|
|
268
|
+
data.cache.deleteStaleFile(path)
|
|
269
|
+
sftp.manager.sftp().unlink(fixPath(path))
|
|
270
|
+
self.log.debug('<- unlink: %s', path)
|
|
271
|
+
except Exception as e:
|
|
272
|
+
self.log.error('<- unlink: %s', path)
|
|
273
|
+
metrics.counts.incr('unlink_except')
|
|
274
|
+
raise e
|
|
275
|
+
|
|
276
|
+
def utimens(self, path, times=None):
|
|
277
|
+
try:
|
|
278
|
+
self.log.debug('-> utimens: %s', path)
|
|
279
|
+
metrics.counts.incr('utimens')
|
|
280
|
+
metadata.cache.deleteMetadata(path)
|
|
281
|
+
data.cache.deleteStaleFile(path)
|
|
282
|
+
sftp.manager.sftp().utime(fixPath(path), times)
|
|
283
|
+
self.log.debug('<- utimens: %s', path)
|
|
284
|
+
except Exception as e:
|
|
285
|
+
self.log.error('<- utimens: %s', path)
|
|
286
|
+
metrics.counts.incr('utimens_except')
|
|
287
|
+
raise e
|
|
288
|
+
|
|
289
|
+
def write(self, path, buf, offset, fh):
|
|
290
|
+
try:
|
|
291
|
+
self.log.debug('-> write: %s %d', path, offset)
|
|
292
|
+
metrics.counts.incr('write')
|
|
293
|
+
metadata.cache.deleteMetadata(path)
|
|
294
|
+
data.cache.removeStaleBlocks(path)
|
|
295
|
+
#self.log.debug('write: write to remote file %s %d', path, offset)
|
|
296
|
+
with sftp.manager.sftp().open(fixPath(path), 'r+') as file:
|
|
297
|
+
file.seek(offset, 0)
|
|
298
|
+
file.write(buf)
|
|
299
|
+
file.close()
|
|
300
|
+
self.log.debug('<- write: %s %d', path, len(buf))
|
|
301
|
+
return len(buf)
|
|
302
|
+
except Exception as e:
|
|
303
|
+
self.log.error('<- write: %s %d', path, offset)
|
|
304
|
+
metrics.counts.incr('write_except')
|
|
305
|
+
raise e
|
|
306
|
+
|
|
307
|
+
def main():
|
|
308
|
+
import argparse
|
|
309
|
+
parser = argparse.ArgumentParser()
|
|
310
|
+
parser.description = 'To unmount use: fusermount -u mountpoint'
|
|
311
|
+
parser.add_argument('host', help='remote host name')
|
|
312
|
+
parser.add_argument('mountpoint', help='local mount point (eg, ~/mnt)')
|
|
313
|
+
parser.add_argument('-p', '--port', help='port number (default=22)', default=22)
|
|
314
|
+
parser.add_argument('-u', '--user', help='user on remote host', default=getpass.getuser())
|
|
315
|
+
parser.add_argument('-d', '--remotedir', help='directory on remote host (eg, ~/)', default=Main.HOME_DIR)
|
|
316
|
+
parser.add_argument('--debug', help='run in debug mode', action='store_true')
|
|
317
|
+
parser.add_argument('--cachetimeout', type=int, help='duration in seconds to keep metadata cached (default is 5 minutes)', default=Main.CACHE_TIMEOUT)
|
|
318
|
+
|
|
319
|
+
args = parser.parse_args()
|
|
320
|
+
|
|
321
|
+
log.Log().setupConfig(debug=args.debug)
|
|
322
|
+
|
|
323
|
+
main = Main(args)
|
|
324
|
+
|
|
325
|
+
#print(args.host, args.login)
|
|
326
|
+
#exit()
|
|
327
|
+
#breakpoint()
|
|
328
|
+
try:
|
|
329
|
+
fuse = FUSE(
|
|
330
|
+
main,
|
|
331
|
+
args.mountpoint,
|
|
332
|
+
foreground=args.debug,
|
|
333
|
+
nothreads=False,
|
|
334
|
+
allow_other=True,
|
|
335
|
+
)
|
|
336
|
+
except Exception as e:
|
|
337
|
+
pass
|
|
338
|
+
|
|
339
|
+
if __name__ == '__main__':
|
|
340
|
+
main()
|
sshfs-offline/data.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
|
|
2
|
+
import math
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
import os
|
|
5
|
+
import log
|
|
6
|
+
|
|
7
|
+
from logging import getLogger
|
|
8
|
+
import queue
|
|
9
|
+
import threading
|
|
10
|
+
import time
|
|
11
|
+
|
|
12
|
+
import metrics
|
|
13
|
+
import sftp
|
|
14
|
+
from sftp import fixPath
|
|
15
|
+
|
|
16
|
+
from errno import ENOENT
|
|
17
|
+
|
|
18
|
+
import metadata
|
|
19
|
+
|
|
20
|
+
from fuse import FuseOSError
|
|
21
|
+
|
|
22
|
+
class Data:
|
|
23
|
+
'''
|
|
24
|
+
On demand data file cache. The files are cached in 64k chunks (blocks). Only the blocks of the file that is read by
|
|
25
|
+
the user are cached. Subsequent reads for the same data block are very fast.
|
|
26
|
+
'''
|
|
27
|
+
DATA_DIR = os.path.join(Path.home(), '.sshfs-offline', 'data')
|
|
28
|
+
BLOCK_SIZE = sftp.BLOCK_SIZE
|
|
29
|
+
|
|
30
|
+
def __init__(self, host: str, basedir: str):
|
|
31
|
+
self.log = getLogger(log.DATA)
|
|
32
|
+
|
|
33
|
+
# make data cache directory ~/.sshfs-offline/data
|
|
34
|
+
self.dataDir = os.path.join(Data.DATA_DIR, host, os.path.splitroot(basedir)[-1])
|
|
35
|
+
if not os.path.exists(self.dataDir):
|
|
36
|
+
os.makedirs(self.dataDir)
|
|
37
|
+
|
|
38
|
+
self.fileReaderQueue = queue.Queue()
|
|
39
|
+
|
|
40
|
+
threading.Thread(target=self.fileReaderThread).start()
|
|
41
|
+
|
|
42
|
+
def _dataPath(self, path: str) -> str:
|
|
43
|
+
#p = path.replace('/','%').replace('\\', '%')
|
|
44
|
+
return os.path.join(self.dataDir, path[1:])
|
|
45
|
+
|
|
46
|
+
def statvfs(self, path: str):
|
|
47
|
+
self.log.debug('statvfs: %s', path)
|
|
48
|
+
dataPath = self._dataPath(path)
|
|
49
|
+
|
|
50
|
+
if os.path.exists(dataPath):
|
|
51
|
+
return os.statvfs(dataPath)
|
|
52
|
+
|
|
53
|
+
def deleteStaleFile(self, path, mtime: float=None ):
|
|
54
|
+
self.log.debug('deleteStaleFile: %s', path)
|
|
55
|
+
if not sftp.manager.isConnected():
|
|
56
|
+
return
|
|
57
|
+
|
|
58
|
+
dataPath = self._dataPath(path)
|
|
59
|
+
|
|
60
|
+
if os.path.exists(dataPath) and os.path.isfile(path):
|
|
61
|
+
if (mtime == None or os.lstat(dataPath).st_ctime < mtime):
|
|
62
|
+
self.log.debug('deleteStaleFile: deleting %s', path)
|
|
63
|
+
metrics.counts.incr('deleteStaleFile')
|
|
64
|
+
os.unlink(dataPath)
|
|
65
|
+
metadata.cache.deleteMetadata(path, [metadata.Metadata.BLOCKMAP])
|
|
66
|
+
|
|
67
|
+
def read(self, path, size, offset, fh):
|
|
68
|
+
#self.log.debug('read: %s input: size=%d offset=%d fd=%d', path, size, offset, fh)
|
|
69
|
+
|
|
70
|
+
buf = bytearray()
|
|
71
|
+
|
|
72
|
+
dataPath = self._dataPath(path)
|
|
73
|
+
d = os.path.dirname(dataPath)
|
|
74
|
+
if not os.path.exists(d):
|
|
75
|
+
os.makedirs(d)
|
|
76
|
+
if not os.path.exists(dataPath):
|
|
77
|
+
with open(dataPath, 'wb') as file:
|
|
78
|
+
fileSize = 0
|
|
79
|
+
st = metadata.cache.getattr(path)
|
|
80
|
+
if st != None:
|
|
81
|
+
fileSize = st['st_size']
|
|
82
|
+
else:
|
|
83
|
+
fileSize = sftp.manager.sftp().lstat(fixPath(path)).st_size
|
|
84
|
+
file.truncate(fileSize)
|
|
85
|
+
|
|
86
|
+
blockMap = metadata.cache.blockmap(path)
|
|
87
|
+
blockNumSlice = range(math.floor(offset / Data.BLOCK_SIZE) , min(math.ceil((offset + size) / Data.BLOCK_SIZE), len(blockMap)))
|
|
88
|
+
|
|
89
|
+
try:
|
|
90
|
+
if not 1 in blockMap[blockNumSlice[0]:blockNumSlice[-1]+1]:
|
|
91
|
+
with sftp.manager.sftp().open(fixPath(path), 'rb') as file:
|
|
92
|
+
file.seek(blockNumSlice[0]*Data.BLOCK_SIZE)
|
|
93
|
+
tempBuf = file.read(len(blockNumSlice)*Data.BLOCK_SIZE)
|
|
94
|
+
|
|
95
|
+
with open(dataPath, 'rb+') as file:
|
|
96
|
+
file.seek(blockNumSlice[0]*Data.BLOCK_SIZE)
|
|
97
|
+
file.write(tempBuf)
|
|
98
|
+
|
|
99
|
+
for blockNum in blockNumSlice:
|
|
100
|
+
blockMap[blockNum] = 1
|
|
101
|
+
metadata.cache.blockmap_save(path, blockMap)
|
|
102
|
+
|
|
103
|
+
blockOffset = offset%Data.BLOCK_SIZE
|
|
104
|
+
buf = tempBuf[blockOffset:min(len(tempBuf), blockOffset+size)]
|
|
105
|
+
|
|
106
|
+
# More unread blocks?
|
|
107
|
+
if 0 in blockMap:
|
|
108
|
+
self.fileReaderQueue.put(path)
|
|
109
|
+
else:
|
|
110
|
+
for blockNum in blockNumSlice:
|
|
111
|
+
if blockMap[blockNum] == 0:
|
|
112
|
+
#self.log.debug('read: %s get block %d from remote', path, blockNum)
|
|
113
|
+
with sftp.manager.sftp().open(fixPath(path), 'rb') as file:
|
|
114
|
+
file.seek(blockNum*Data.BLOCK_SIZE)
|
|
115
|
+
block = file.read(Data.BLOCK_SIZE)
|
|
116
|
+
|
|
117
|
+
with open(dataPath, 'rb+') as file:
|
|
118
|
+
file.seek(blockNum*Data.BLOCK_SIZE)
|
|
119
|
+
file.write(block)
|
|
120
|
+
|
|
121
|
+
blockMap[blockNum] = 1
|
|
122
|
+
metadata.cache.blockmap_save(path, blockMap)
|
|
123
|
+
|
|
124
|
+
if len(buf) == 0:
|
|
125
|
+
blockOffset = offset%Data.BLOCK_SIZE
|
|
126
|
+
buf = block[blockOffset : min(Data.BLOCK_SIZE, blockOffset+size)]
|
|
127
|
+
else:
|
|
128
|
+
buf += block[0 : min(Data.BLOCK_SIZE, size-len(buf))]
|
|
129
|
+
else:
|
|
130
|
+
with open(dataPath, 'rb') as file:
|
|
131
|
+
if len(buf) == 0:
|
|
132
|
+
file.seek(offset)
|
|
133
|
+
buf = file.read(min(size, Data.BLOCK_SIZE-offset%Data.BLOCK_SIZE))
|
|
134
|
+
else:
|
|
135
|
+
file.seek(blockNum*Data.BLOCK_SIZE)
|
|
136
|
+
buf += file.read(min(Data.BLOCK_SIZE, size-len(buf)))
|
|
137
|
+
except Exception as e:
|
|
138
|
+
self.log.error('read: %s size=%d offset=%d', path, size, offset)
|
|
139
|
+
self.log.error('read: %s blockMap=%s', path, blockMap)
|
|
140
|
+
self.log.error('read: %s blockMap=%s', path, blockNumSlice)
|
|
141
|
+
raise e
|
|
142
|
+
|
|
143
|
+
#self.log.debug('read: %s %d', path,= len(buf))
|
|
144
|
+
return bytes(buf)
|
|
145
|
+
|
|
146
|
+
def fileReaderThread(self):
|
|
147
|
+
while True:
|
|
148
|
+
path = self.fileReaderQueue.get()
|
|
149
|
+
self.log.debug('-> fileReaderThread %s', path)
|
|
150
|
+
blockMap = metadata.cache.blockmap(path)
|
|
151
|
+
unreadBlockFound = False
|
|
152
|
+
for i in range(0, len(blockMap)):
|
|
153
|
+
if blockMap[i] == 0:
|
|
154
|
+
size = Data.BLOCK_SIZE
|
|
155
|
+
offset = i * Data.BLOCK_SIZE
|
|
156
|
+
self.log.debug('<- fileReaderThread %s size=%s offset=%s', path, size, offset)
|
|
157
|
+
self.read(path, size, offset, 0)
|
|
158
|
+
unreadBlockFound = True
|
|
159
|
+
break
|
|
160
|
+
|
|
161
|
+
if unreadBlockFound:
|
|
162
|
+
metrics.counts.incr('fileReaderThread')
|
|
163
|
+
else:
|
|
164
|
+
self.log.debug('<- fileReaderThread %s all blocks read', path)
|
|
165
|
+
|
|
166
|
+
cache: Data = None
|
sshfs-offline/log.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
|
|
2
|
+
import logging
|
|
3
|
+
import os
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
MAIN = 'main '
|
|
7
|
+
SFTP = 'sftp '
|
|
8
|
+
METADATA = 'metadata'
|
|
9
|
+
DATA = 'data '
|
|
10
|
+
METRICS = 'metrics'
|
|
11
|
+
|
|
12
|
+
FUSE = 'fuse'
|
|
13
|
+
PARAMIKO = 'paramiko'
|
|
14
|
+
|
|
15
|
+
class Log:
|
|
16
|
+
def __init__(self):
|
|
17
|
+
self.logDir = os.path.join(Path.home(), '.sshfs-offline')
|
|
18
|
+
if not os.path.exists(self.logDir):
|
|
19
|
+
os.makedirs(self.logDir)
|
|
20
|
+
self.formatter = logging.Formatter('%(asctime)s:%(levelname)s:%(name)s %(message)s')
|
|
21
|
+
|
|
22
|
+
def setupConfig(self, debug: bool):
|
|
23
|
+
|
|
24
|
+
## debug logging
|
|
25
|
+
if debug:
|
|
26
|
+
logging.getLogger(FUSE).setLevel(logging.WARNING)
|
|
27
|
+
logging.getLogger(PARAMIKO).setLevel(logging.WARNING)
|
|
28
|
+
logging.basicConfig(
|
|
29
|
+
format='%(asctime)s:%(levelname)s:%(name)s %(message)s',
|
|
30
|
+
datefmt='%H:%M:%S',
|
|
31
|
+
level=logging.DEBUG
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
# error logging
|
|
35
|
+
for name in [MAIN, SFTP, METADATA, DATA, FUSE, PARAMIKO]:
|
|
36
|
+
logger = logging.getLogger(name)
|
|
37
|
+
errorHandler = logging.FileHandler(os.path.join(self.logDir, 'error.log'), mode='w')
|
|
38
|
+
errorHandler.setFormatter(self.formatter)
|
|
39
|
+
errorHandler.setLevel(logging.ERROR)
|
|
40
|
+
logger.addHandler(errorHandler)
|
|
41
|
+
if not debug:
|
|
42
|
+
logger.setLevel(logging.ERROR)
|
|
43
|
+
|
|
44
|
+
# metrics logging
|
|
45
|
+
metricsHandler = logging.FileHandler(os.path.join(self.logDir, 'metrics.log'), mode='w')
|
|
46
|
+
metricsHandler.setFormatter(self.formatter)
|
|
47
|
+
logger = logging.getLogger(METRICS)
|
|
48
|
+
logger.addHandler(metricsHandler)
|
|
49
|
+
logger.setLevel(logging.DEBUG)
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
|
|
2
|
+
import math
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
import os
|
|
5
|
+
import log
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
from logging import getLogger
|
|
9
|
+
|
|
10
|
+
import shutil
|
|
11
|
+
import time
|
|
12
|
+
|
|
13
|
+
from errno import ENOENT
|
|
14
|
+
|
|
15
|
+
import data
|
|
16
|
+
import metrics
|
|
17
|
+
import sftp
|
|
18
|
+
|
|
19
|
+
from fuse import FuseOSError
|
|
20
|
+
|
|
21
|
+
class Metadata:
|
|
22
|
+
'''
|
|
23
|
+
Metadata cache for getattr, readdir and read link operations.
|
|
24
|
+
'''
|
|
25
|
+
METADATA_DIR = os.path.join(Path.home(), '.sshfs-offline', 'metadata')
|
|
26
|
+
GETATTR = 'getattr'
|
|
27
|
+
READDIR = 'readdir'
|
|
28
|
+
READLINK = 'readlink'
|
|
29
|
+
BLOCKMAP = 'blockmap'
|
|
30
|
+
|
|
31
|
+
def __init__(self, host: str, basedir: str, cachetimeout: float):
|
|
32
|
+
self.log = getLogger(log.METADATA)
|
|
33
|
+
|
|
34
|
+
self.cachetimeout = cachetimeout
|
|
35
|
+
|
|
36
|
+
self.metadataDir = os.path.join(Metadata.METADATA_DIR, host, os.path.splitroot(basedir)[-1])
|
|
37
|
+
if not os.path.exists(self.metadataDir):
|
|
38
|
+
os.makedirs(self.metadataDir)
|
|
39
|
+
|
|
40
|
+
def deleteMetadata(self, path, files=[GETATTR, READDIR, READLINK]):
|
|
41
|
+
if not sftp.manager.isConnected():
|
|
42
|
+
return
|
|
43
|
+
|
|
44
|
+
mdPath = self._metadataPath(path)
|
|
45
|
+
if os.path.exists(mdPath):
|
|
46
|
+
for file in files:
|
|
47
|
+
filePath = os.path.join(mdPath, file)
|
|
48
|
+
if os.path.exists(filePath):
|
|
49
|
+
metrics.counts.incr('deleteMetadata')
|
|
50
|
+
os.unlink(filePath)
|
|
51
|
+
|
|
52
|
+
def deleteParentMetadata(self, path):
|
|
53
|
+
if not sftp.manager.isConnected():
|
|
54
|
+
return
|
|
55
|
+
|
|
56
|
+
p = os.path.split(path)[0]
|
|
57
|
+
self.deleteMetadata(p)
|
|
58
|
+
|
|
59
|
+
# 'st_atime', 'st_gid', 'st_mode', 'st_mtime', 'st_size', 'st_uid'
|
|
60
|
+
def getattr(self, path)-> dict:
|
|
61
|
+
return self._readCache(path, Metadata.GETATTR)
|
|
62
|
+
|
|
63
|
+
def getattr_save(self, path, dic: dict):
|
|
64
|
+
if dic == {}:
|
|
65
|
+
data.cache.deleteStaleFile(path)
|
|
66
|
+
self._storeCache(path, Metadata.GETATTR, dic)
|
|
67
|
+
elif dic != None:
|
|
68
|
+
data.cache.deleteStaleFile(path, dic['st_mtime'])
|
|
69
|
+
self._storeCache(path, Metadata.GETATTR, dic)
|
|
70
|
+
|
|
71
|
+
def readdir(self, path)-> list[str]:
|
|
72
|
+
return self._readCache(path, Metadata.READDIR)
|
|
73
|
+
|
|
74
|
+
def readdir_save(self, path, s: list[str]=None):
|
|
75
|
+
self._storeCache(path, Metadata.READDIR, s)
|
|
76
|
+
|
|
77
|
+
def readlink(self, path:str) -> str | None:
|
|
78
|
+
return self._readCache(path, Metadata.READLINK)
|
|
79
|
+
|
|
80
|
+
def readlink_save(self, path:str, link: str=None):
|
|
81
|
+
self._storeCache(path, Metadata.READLINK, link)
|
|
82
|
+
|
|
83
|
+
def blockmap(self, path:str) -> bytearray | None:
|
|
84
|
+
bm = self._readCache(path, Metadata.BLOCKMAP)
|
|
85
|
+
metrics.counts.incr('blockmap')
|
|
86
|
+
# not sure how the blockMap can be zero length?
|
|
87
|
+
if bm != None and len(bm) == 0:
|
|
88
|
+
bm = None
|
|
89
|
+
self.log.warning('blockmap: %s zero length blockMap?', path)
|
|
90
|
+
|
|
91
|
+
if bm == None:
|
|
92
|
+
fileSize = 0
|
|
93
|
+
st = self.getattr(path)
|
|
94
|
+
if st != None:
|
|
95
|
+
fileSize = st['st_size']
|
|
96
|
+
else:
|
|
97
|
+
fileSize = sftp.manager.sftp().lstat(sftp.fixPath(path)).st_size
|
|
98
|
+
|
|
99
|
+
bm = bytearray(math.ceil(fileSize/data.cache.BLOCK_SIZE))
|
|
100
|
+
|
|
101
|
+
return bm
|
|
102
|
+
|
|
103
|
+
def blockmap_save(self, path:str, blockMap: bytearray):
|
|
104
|
+
metrics.counts.incr('blockmap_save')
|
|
105
|
+
self._storeCache(path, Metadata.BLOCKMAP, blockMap)
|
|
106
|
+
|
|
107
|
+
#
|
|
108
|
+
# Private methods:
|
|
109
|
+
#
|
|
110
|
+
|
|
111
|
+
def _metadataPath(self, path: str, operation: str=None) -> str:
|
|
112
|
+
p = path.replace('/','%').replace('\\', '%')
|
|
113
|
+
d = os.path.join(self.metadataDir, p)
|
|
114
|
+
if not os.path.exists(d):
|
|
115
|
+
os.mkdir(d)
|
|
116
|
+
if operation == None:
|
|
117
|
+
return d
|
|
118
|
+
else:
|
|
119
|
+
return os.path.join(d, operation)
|
|
120
|
+
|
|
121
|
+
def _storeCache(self, path, operation, d: dict | list[str] | str | bytearray):
|
|
122
|
+
self.log.debug('_storeCace.%s: %s', operation, path)
|
|
123
|
+
if not sftp.manager.isConnected():
|
|
124
|
+
return
|
|
125
|
+
|
|
126
|
+
p = self._metadataPath(path, operation)
|
|
127
|
+
if operation == Metadata.BLOCKMAP:
|
|
128
|
+
with open(p, "wb") as file:
|
|
129
|
+
file.write(bytes(d))
|
|
130
|
+
else:
|
|
131
|
+
with open(p, "w") as file:
|
|
132
|
+
if d == ENOENT:
|
|
133
|
+
json.dump(d, None)
|
|
134
|
+
else:
|
|
135
|
+
json.dump(d, file, indent=4)
|
|
136
|
+
|
|
137
|
+
def _readCache(self, path, operation) -> dict | list[str] | str | bytearray:
|
|
138
|
+
metadataPath = self._metadataPath(path, operation)
|
|
139
|
+
if os.path.exists(metadataPath):
|
|
140
|
+
if operation == Metadata.BLOCKMAP:
|
|
141
|
+
with open(metadataPath, 'rb') as file:
|
|
142
|
+
buf = file.read()
|
|
143
|
+
self.log.debug('_readCache.%s: %s %s', operation, path, str(buf))
|
|
144
|
+
metrics.counts.incr('blockmap_hit')
|
|
145
|
+
return bytearray(buf)
|
|
146
|
+
else:
|
|
147
|
+
if time.time() > os.lstat(metadataPath).st_ctime + self.cachetimeout and sftp.manager.isConnected():
|
|
148
|
+
self.log.debug('_readCache.%s: expired %s', operation, path)
|
|
149
|
+
os.unlink(metadataPath)
|
|
150
|
+
metrics.counts.incr(operation+'_expired')
|
|
151
|
+
return None
|
|
152
|
+
else:
|
|
153
|
+
with open(metadataPath, 'r') as file:
|
|
154
|
+
d = json.load(file)
|
|
155
|
+
logMd = ''
|
|
156
|
+
if operation != Metadata.READDIR:
|
|
157
|
+
logMd = d
|
|
158
|
+
self.log.debug('_readCache.%s: %s %s', operation, path, logMd)
|
|
159
|
+
metrics.counts.incr(operation+'_hit')
|
|
160
|
+
return d
|
|
161
|
+
|
|
162
|
+
self.log.debug('readCache.%s: not found %s', operation, path)
|
|
163
|
+
return None
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
cache: Metadata = None
|
sshfs-offline/metrics.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
|
|
2
|
+
from logging import getLogger
|
|
3
|
+
import copy
|
|
4
|
+
import logging
|
|
5
|
+
import threading
|
|
6
|
+
import time
|
|
7
|
+
import log
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Metrics:
|
|
11
|
+
def __init__(self):
|
|
12
|
+
self.log = getLogger(log.METRICS)
|
|
13
|
+
self.counts: dict[str,int] = dict()
|
|
14
|
+
self.prevCounts: dict[str, int] = dict()
|
|
15
|
+
self.stopped = False
|
|
16
|
+
|
|
17
|
+
def start(self):
|
|
18
|
+
threading.Thread(target=self.captureLoop).start()
|
|
19
|
+
|
|
20
|
+
def incr(self, name: str):
|
|
21
|
+
if name in self.counts:
|
|
22
|
+
self.counts[name] += 1
|
|
23
|
+
else:
|
|
24
|
+
self.counts[name] = 1
|
|
25
|
+
|
|
26
|
+
def _logCounts(self):
|
|
27
|
+
lines: list[str] = []
|
|
28
|
+
diff = 0
|
|
29
|
+
keys = list(self.counts.keys())
|
|
30
|
+
keys.sort()
|
|
31
|
+
for key in keys:
|
|
32
|
+
if key in self.prevCounts:
|
|
33
|
+
diff = self.counts[key] - self.prevCounts[key]
|
|
34
|
+
else:
|
|
35
|
+
diff = self.counts[key]
|
|
36
|
+
if diff > 0:
|
|
37
|
+
lines.append('\n {}: {}'.format(key.ljust(16), diff))
|
|
38
|
+
|
|
39
|
+
self.prevCounts = copy.deepcopy(self.counts)
|
|
40
|
+
|
|
41
|
+
if len(lines) > 0:
|
|
42
|
+
self.log.info(''.join(lines))
|
|
43
|
+
|
|
44
|
+
def captureLoop(self):
|
|
45
|
+
try:
|
|
46
|
+
while True:
|
|
47
|
+
time.sleep(10)
|
|
48
|
+
if self.stopped:
|
|
49
|
+
break
|
|
50
|
+
self._logCounts()
|
|
51
|
+
except Exception as e:
|
|
52
|
+
self.log.error('Exception: %s', e)
|
|
53
|
+
|
|
54
|
+
def stop(self):
|
|
55
|
+
self.log.info('metrics_stop')
|
|
56
|
+
self.stopped = True
|
|
57
|
+
|
|
58
|
+
counts: Metrics
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
|
sshfs-offline/sftp.py
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import errno
|
|
2
|
+
from logging import getLogger
|
|
3
|
+
import logging
|
|
4
|
+
import os
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
import time
|
|
7
|
+
from typing import Iterator
|
|
8
|
+
import paramiko
|
|
9
|
+
import threading
|
|
10
|
+
|
|
11
|
+
import getpass
|
|
12
|
+
import socket
|
|
13
|
+
|
|
14
|
+
from fuse import FuseOSError
|
|
15
|
+
|
|
16
|
+
import metrics
|
|
17
|
+
import log
|
|
18
|
+
|
|
19
|
+
BLOCK_SIZE = 131072
|
|
20
|
+
WINDOW_SIZE = 1073741824
|
|
21
|
+
|
|
22
|
+
def fixPath(path):
|
|
23
|
+
return os.path.splitroot(path)[-1]
|
|
24
|
+
|
|
25
|
+
class Connection:
|
|
26
|
+
def __init__(self, sshClient: paramiko.SSHClient, sftpClient: paramiko.SFTPClient):
|
|
27
|
+
self.sshClient: paramiko.SSHClient = sshClient
|
|
28
|
+
self.sftpClient: paramiko.SFTPClient = sftpClient
|
|
29
|
+
self.offline = False
|
|
30
|
+
|
|
31
|
+
class SftpOffline:
|
|
32
|
+
def close(self) -> None:
|
|
33
|
+
pass
|
|
34
|
+
def listdir(self, path: str = ".") -> list[str]:
|
|
35
|
+
raise FuseOSError(errno.ENETDOWN)
|
|
36
|
+
def listdir_attr(self, path: str = ".") -> list[paramiko.SFTPAttributes]:
|
|
37
|
+
raise FuseOSError(errno.ENETDOWN)
|
|
38
|
+
def listdir_iter(self, path: bytes | str = ".", read_aheads: int = 50) -> Iterator[paramiko.SFTPAttributes]:
|
|
39
|
+
raise FuseOSError(errno.ENETDOWN)
|
|
40
|
+
def open(self, filename: bytes | str, mode: str = "r", bufsize: int = -1) -> paramiko.SFTPFile:
|
|
41
|
+
raise FuseOSError(errno.ENETDOWN)
|
|
42
|
+
file = open
|
|
43
|
+
def remove(self, path: bytes | str) -> None:
|
|
44
|
+
raise FuseOSError(errno.ENETDOWN)
|
|
45
|
+
unlink = remove
|
|
46
|
+
def rename(self, oldpath: bytes | str, newpath: bytes | str) -> None:
|
|
47
|
+
raise FuseOSError(errno.ENETDOWN)
|
|
48
|
+
def posix_rename(self, oldpath: bytes | str, newpath: bytes | str) -> None:
|
|
49
|
+
raise FuseOSError(errno.ENETDOWN)
|
|
50
|
+
def mkdir(self, path: bytes | str, mode: int = 511) -> None:
|
|
51
|
+
raise FuseOSError(errno.ENETDOWN)
|
|
52
|
+
def rmdir(self, path: bytes | str) -> None:
|
|
53
|
+
raise FuseOSError(errno.ENETDOWN)
|
|
54
|
+
def stat(self, path: bytes | str) -> paramiko.SFTPAttributes:
|
|
55
|
+
raise FuseOSError(errno.ENETDOWN)
|
|
56
|
+
def lstat(self, path: bytes | str) -> paramiko.SFTPAttributes:
|
|
57
|
+
raise FuseOSError(errno.ENETDOWN)
|
|
58
|
+
def symlink(self, source: bytes | str, dest: bytes | str) -> None:
|
|
59
|
+
raise FuseOSError(errno.ENETDOWN)
|
|
60
|
+
def chmod(self, path: bytes | str, mode: int) -> None:
|
|
61
|
+
raise FuseOSError(errno.ENETDOWN)
|
|
62
|
+
def chown(self, path: bytes | str, uid: int, gid: int) -> None:
|
|
63
|
+
raise FuseOSError(errno.ENETDOWN)
|
|
64
|
+
def utime(self, path: bytes | str, times: tuple[float, float] | None) -> None:
|
|
65
|
+
raise FuseOSError(errno.ENETDOWN)
|
|
66
|
+
def truncate(self, path: bytes | str, size: int) -> None:
|
|
67
|
+
raise FuseOSError(errno.ENETDOWN)
|
|
68
|
+
def readlink(self, path: bytes | str) -> str | None:
|
|
69
|
+
raise FuseOSError(errno.ENETDOWN)
|
|
70
|
+
def normalize(self, path: bytes | str) -> str:
|
|
71
|
+
raise FuseOSError(errno.ENETDOWN)
|
|
72
|
+
def chdir(self, path: None | bytes | str = None) -> None:
|
|
73
|
+
raise FuseOSError(errno.ENETDOWN)
|
|
74
|
+
def getcwd(self) -> str | None:
|
|
75
|
+
raise FuseOSError(errno.ENETDOWN)
|
|
76
|
+
|
|
77
|
+
class SFTPManager:
|
|
78
|
+
def __init__(self, host, user, remotedir, port):
|
|
79
|
+
self.log = getLogger(log.SFTP)
|
|
80
|
+
self.host = host
|
|
81
|
+
self.user = user
|
|
82
|
+
self.password = None
|
|
83
|
+
self.remotedir = remotedir
|
|
84
|
+
self.port = port
|
|
85
|
+
self.local = threading.local()
|
|
86
|
+
self.connections: dict[str, Connection] = dict()
|
|
87
|
+
self.offline = False
|
|
88
|
+
self.keepaliveStarted = False
|
|
89
|
+
self.keepaliveStopped = False
|
|
90
|
+
|
|
91
|
+
def isConnected(self):
|
|
92
|
+
return not isinstance(self.sftp(), SftpOffline) and not self.offline
|
|
93
|
+
|
|
94
|
+
def sftp(self) -> paramiko.SFTPClient | SftpOffline:
|
|
95
|
+
threadId = threading.get_native_id()
|
|
96
|
+
if self.offline:
|
|
97
|
+
if threadId in self.connections:
|
|
98
|
+
self.sftpClose()
|
|
99
|
+
return SftpOffline()
|
|
100
|
+
|
|
101
|
+
if (threadId not in self.connections or
|
|
102
|
+
not (self.connections[threadId].sshClient.get_transport().is_active() and
|
|
103
|
+
self.connections[threadId].sshClient.get_transport().is_alive())):
|
|
104
|
+
if threadId in self.connections:
|
|
105
|
+
self.sftpClose()
|
|
106
|
+
sshClient = paramiko.SSHClient()
|
|
107
|
+
sshClient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
|
108
|
+
sshClient.load_system_host_keys()
|
|
109
|
+
try:
|
|
110
|
+
sshClient.connect(self.host, port=self.port, username=self.user, password=self.password)
|
|
111
|
+
#sshClient.get_transport().set_keepalive(60)
|
|
112
|
+
except socket.gaierror:
|
|
113
|
+
self.log.debug('sftp: Cannot connect to host '+self.host)
|
|
114
|
+
print('Cannot connect to host ' + self.host + '. Only cached data will be available.')
|
|
115
|
+
metrics.counts.incr('sftp_connect_err')
|
|
116
|
+
return SftpOffline()
|
|
117
|
+
except OSError as e:
|
|
118
|
+
self.log.debug('sftp: %s', e)
|
|
119
|
+
print('{}. Only cached data will be available.'.format(e))
|
|
120
|
+
metrics.counts.incr('sftp_network_err')
|
|
121
|
+
return SftpOffline()
|
|
122
|
+
except paramiko.ssh_exception.AuthenticationException:
|
|
123
|
+
self.password = getpass.getpass("Enter password: ")
|
|
124
|
+
try:
|
|
125
|
+
sshClient.connect(self.host, port=self.port, username=self.user, password=self.password)
|
|
126
|
+
except paramiko.ssh_exception.AuthenticationException:
|
|
127
|
+
self.log.debug("sftp: Authentication failed")
|
|
128
|
+
print('Invalid user or password')
|
|
129
|
+
metrics.counts.incr('sftp_auth_err')
|
|
130
|
+
exit(1)
|
|
131
|
+
|
|
132
|
+
metrics.counts.incr('sftp_connected')
|
|
133
|
+
sshClient.get_transport().default_window_size = WINDOW_SIZE
|
|
134
|
+
self.connections[threadId] = Connection(sshClient, sshClient.open_sftp())
|
|
135
|
+
self.connections[threadId].sftpClient.SFTP_FILE_OBJECT_BLOCK_SIZE = BLOCK_SIZE
|
|
136
|
+
try:
|
|
137
|
+
self.connections[threadId].sftpClient.chdir(self.remotedir)
|
|
138
|
+
metrics.counts.incr('sftp_chdir')
|
|
139
|
+
except IOError:
|
|
140
|
+
self.log.debug('--remotedir '+self.remotedir+' not found on host '+self.host)
|
|
141
|
+
print('--remotedir '+self.remotedir+' not found on host '+self.host)
|
|
142
|
+
metrics.counts.incr('sftp_chdir_err')
|
|
143
|
+
exit(1)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
return self.connections[threadId].sftpClient
|
|
147
|
+
|
|
148
|
+
def sftpClose(self):
|
|
149
|
+
metrics.counts.incr('sftp_close')
|
|
150
|
+
threadId = threading.get_native_id()
|
|
151
|
+
val = self.connections.pop(threadId)
|
|
152
|
+
val.sftpClient.close()
|
|
153
|
+
val.sshClient.close()
|
|
154
|
+
|
|
155
|
+
def startKeepalive(self):
|
|
156
|
+
if self.keepaliveStarted == False:
|
|
157
|
+
metrics.counts.incr('sftp_start')
|
|
158
|
+
self.keepaliveStarted = True
|
|
159
|
+
threading.Thread(target=self.keepaliveThread).start()
|
|
160
|
+
|
|
161
|
+
def keepaliveThread(self):
|
|
162
|
+
metrics.counts.incr('sftp_keepaliveThread')
|
|
163
|
+
while True:
|
|
164
|
+
if self.keepaliveStopped:
|
|
165
|
+
metrics.counts.incr('sftp_stopped')
|
|
166
|
+
break
|
|
167
|
+
time.sleep(10)
|
|
168
|
+
sshClient = paramiko.SSHClient()
|
|
169
|
+
sshClient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
|
170
|
+
sshClient.load_system_host_keys()
|
|
171
|
+
try:
|
|
172
|
+
sshClient.connect(self.host, port=self.port, username=self.user, password=self.password)
|
|
173
|
+
except Exception as e:
|
|
174
|
+
if self.offline == False:
|
|
175
|
+
self.offline = True
|
|
176
|
+
metrics.counts.incr('sftp_offline')
|
|
177
|
+
else:
|
|
178
|
+
if self.offline:
|
|
179
|
+
metrics.counts.incr('sftp_online')
|
|
180
|
+
self.offline = False
|
|
181
|
+
sshClient.close()
|
|
182
|
+
|
|
183
|
+
def stop(self):
|
|
184
|
+
self.log.info('sftp_stop')
|
|
185
|
+
metrics.counts.incr('sftp_stop')
|
|
186
|
+
self.keepaliveStopped = True
|
|
187
|
+
|
|
188
|
+
manager: SFTPManager = None
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: sshfs-offline
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: SSH File System with offline access to cached files.
|
|
5
|
+
Author-email: Dave Christenson <davechri58@gmail.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Keywords: offline,cache,sshfs,fuse-filesystem,fuse
|
|
8
|
+
Classifier: Development Status :: 4 - Beta
|
|
9
|
+
Classifier: Topic :: System :: Filesystems
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Intended Audience :: End Users/Desktop
|
|
13
|
+
Classifier: Operating System :: MacOS :: MacOS X
|
|
14
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
15
|
+
Classifier: Programming Language :: Python
|
|
16
|
+
Classifier: Programming Language :: Python :: 2.7
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.4
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.5
|
|
20
|
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
|
21
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Dynamic: license-file
|
|
25
|
+
|
|
26
|
+
sshfs-offline
|
|
27
|
+
=============
|
|
28
|
+
|
|
29
|
+
SSH File System with offline access to cached files.
|
|
30
|
+
|
|
31
|
+
Features:
|
|
32
|
+
|
|
33
|
+
- Based on FUSE (Filesystem in Userspace framework for Linux)
|
|
34
|
+
|
|
35
|
+
- Metadata and Data are cached locally to improve performance.
|
|
36
|
+
|
|
37
|
+
- Offline access to cached data when the remote host is not reachable
|
|
38
|
+
|
|
39
|
+
- Read/Write file system
|
|
40
|
+
|
|
41
|
+
Install Script:
|
|
42
|
+
===============
|
|
43
|
+
|
|
44
|
+
```sh
|
|
45
|
+
$ pip install sshfs-offline
|
|
46
|
+
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
How to mount a filesystem
|
|
50
|
+
=========================
|
|
51
|
+
|
|
52
|
+
Usage:
|
|
53
|
+
|
|
54
|
+
```sh
|
|
55
|
+
usage: sshfs-offline [-h] [-p PORT] [-u USER] [-d REMOTEDIR] [--debug] [--cachetimeout CACHETIMEOUT] host mountpoint
|
|
56
|
+
|
|
57
|
+
To unmount use: fusermount -u mountpoint
|
|
58
|
+
|
|
59
|
+
positional arguments:
|
|
60
|
+
host remote host name
|
|
61
|
+
mountpoint local mount point (eg, ~/mnt)
|
|
62
|
+
|
|
63
|
+
options:
|
|
64
|
+
-h, --help show this help message and exit
|
|
65
|
+
-p PORT, --port PORT port number (default=22)
|
|
66
|
+
-u USER, --user USER user on remote host
|
|
67
|
+
-d REMOTEDIR, --remotedir REMOTEDIR
|
|
68
|
+
directory on remote host (eg, ~/)
|
|
69
|
+
--debug run in debug mode
|
|
70
|
+
--cachetimeout CACHETIMEOUT
|
|
71
|
+
duration in seconds to keep metadata cached (default is 5 minutes)
|
|
72
|
+
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
Example:
|
|
76
|
+
|
|
77
|
+
```sh
|
|
78
|
+
sshfs-offline localhost ~/mnt
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
Note, that it's recommended to run it as user, not as root. For this
|
|
82
|
+
to work the mountpoint must be owned by the user. If the username is
|
|
83
|
+
different on the host you are connecting to, then use the --user option.
|
|
84
|
+
|
|
85
|
+
If you need to enter a password sshfs-offline will ask for it.
|
|
86
|
+
You can also specify a remote directory using --remotedir. The default
|
|
87
|
+
is your home directory.
|
|
88
|
+
|
|
89
|
+
The cache timeout defaults to 5 minutes, and can be set with the -cachetimeout option.
|
|
90
|
+
|
|
91
|
+
To unmount the filesystem:
|
|
92
|
+
|
|
93
|
+
fusermount -u mountpoint
|
|
94
|
+
|
|
95
|
+
Cache Implementation
|
|
96
|
+
====================
|
|
97
|
+
|
|
98
|
+
The data and metadata are cached in the **.sshfs-offline** directory. In this example, the **test/myfile.txt** file has two 132K blocks. The data is cached in the **data** sub-directory, and the metadata is cached in the **metadata** sub-directory.
|
|
99
|
+
|
|
100
|
+
```sh
|
|
101
|
+
➜ .sshfs-offline
|
|
102
|
+
├── data
|
|
103
|
+
│ └── localhost # host name
|
|
104
|
+
│ └── home
|
|
105
|
+
│ └── dave
|
|
106
|
+
│ └── test
|
|
107
|
+
│ └── myfile.txt
|
|
108
|
+
└── metadata
|
|
109
|
+
└── localhost # host name
|
|
110
|
+
└── home
|
|
111
|
+
└── user
|
|
112
|
+
├── %test # test direcotry
|
|
113
|
+
│ ├── getattr # lstat status for directory
|
|
114
|
+
│ └── readdir # directory entries
|
|
115
|
+
└── %test%myfile.txt # test/myfile.txt file
|
|
116
|
+
├── blockmap # track blocks that are cached
|
|
117
|
+
└── getattr # lstat status for file
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
Debugging
|
|
121
|
+
=========
|
|
122
|
+
|
|
123
|
+
* Metrics are logged to the **~/.sshfs-offline/metrics.log** file.
|
|
124
|
+
* In production (--debug=False), the log level is set to **warning**, and logs are writtend to the **~/.sshfs-offline/error.log** file.
|
|
125
|
+
* If the --debug option is specified, the log level is set to **debug**, the process is run in the foreground, and logs are written to stdout.
|
|
126
|
+
|
|
127
|
+
Using the tail command to follow the metrics:
|
|
128
|
+
```sh
|
|
129
|
+
$ tail -f ~/.sshfs-offline
|
|
130
|
+
2025-09-23 07:26:19,237:INFO:metrics
|
|
131
|
+
getattr : 181
|
|
132
|
+
getattr_hit : 181
|
|
133
|
+
init : 1
|
|
134
|
+
readdir : 26
|
|
135
|
+
readdir_hit : 26
|
|
136
|
+
readlink : 104
|
|
137
|
+
readlink_hit : 104
|
|
138
|
+
sftp_chdir : 1
|
|
139
|
+
sftp_connected : 1
|
|
140
|
+
sftp_healthThread: 1
|
|
141
|
+
sftp_start : 1
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
Development
|
|
145
|
+
===========
|
|
146
|
+
|
|
147
|
+
Create Virtual Environment:
|
|
148
|
+
|
|
149
|
+
```sh
|
|
150
|
+
$ python3 -m venv my-venv-name
|
|
151
|
+
$ source ~/my-venv-name/bin/activate
|
|
152
|
+
$ pip install -r requirements.txt
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
Mount filesystem:
|
|
156
|
+
|
|
157
|
+
```sh
|
|
158
|
+
$ ./sshfs-offline/cli.py localhost ~/mnt
|
|
159
|
+
|
|
160
|
+
```
|
|
161
|
+
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
sshfs-offline/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
sshfs-offline/cli.py,sha256=-CHus9EJbC0D4UoPrqSnff8PmMiM7kqQZCgyp37yKZ8,12755
|
|
3
|
+
sshfs-offline/data.py,sha256=PiOheuWASrKLVqwBI2BmDl7FzFkU0x5-yCiWxZ9AFQI,6863
|
|
4
|
+
sshfs-offline/log.py,sha256=l32kcFTl8Tpu6r7WbOoIHRCzjqRglKB1LGWxntalr8Q,1768
|
|
5
|
+
sshfs-offline/metadata.py,sha256=cIkUDBLw4VLHLg7ydKzovv86HTIClgGGJEtafqCAGLo,6009
|
|
6
|
+
sshfs-offline/metrics.py,sha256=KfYR9lKYvuN1EBttY_0AKfHSpJ-RJQKDivn4II_eugc,1553
|
|
7
|
+
sshfs-offline/sftp.py,sha256=-kSFhRm8w-PCaUmMNiE67pKEA4KwLWfkffgnucpgsIM,7967
|
|
8
|
+
sshfs_offline-0.0.1.dist-info/licenses/LICENSE,sha256=w1JMi3ef157H69w-vQjh4eV-7ZohqZBOuLZ2DA8-whg,1074
|
|
9
|
+
sshfs_offline-0.0.1.dist-info/METADATA,sha256=3EKwDJJ0HPAlXDAdHlCpgxC0ZbNGag-DIwnXfkQ7paU,4865
|
|
10
|
+
sshfs_offline-0.0.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
11
|
+
sshfs_offline-0.0.1.dist-info/entry_points.txt,sha256=jnvW0_UWvhp8GejltsEbnxSRxWEfKD9VFNDFOmdSfNY,57
|
|
12
|
+
sshfs_offline-0.0.1.dist-info/top_level.txt,sha256=bPyPvvBdF2qxSh7IdS8nGelR9d9tMix5NYhHMZaqmpQ,14
|
|
13
|
+
sshfs_offline-0.0.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 David Christenson
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
sshfs-offline
|