forked from hq6/DBFuse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DBFuse.py
437 lines (366 loc) · 13.1 KB
/
DBFuse.py
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
#!/usr/bin/python
from __future__ import with_statement
import os
import sys
import errno
import locale
import pwd
from time import time,mktime,sleep
from datetime import datetime
from StringIO import StringIO
from threading import Thread
import stat
import tempfile
# pip install --user fusepy
# pip install --user dropbox
# sudo adduser <username> fuse
# Based off of a template for FUSE available at
# http://www.stavros.io/posts/python-fuse-filesystem/
from fuse import FUSE, FuseOSError, Operations
from dropbox import client, rest, session
def debug(trace=False):
"""a decorator for handling authentication and exceptions"""
def decorate(f):
def wrapper(self, *args, **kwargs):
if trace:
print "%s called with args " % f.func_name, args
return f(self, *args, **kwargs)
wrapper.__doc__ = f.__doc__
return wrapper
return decorate
# The part for obtaining the access token is not yet implemented, but it must
# be done interactively against the developer's server, to protect the
# developer's APP_SECRET and APP_KEY
class DBFuse(Operations):
def __init__(self):
try:
accessToken = open("token_store.txt").read()[len('oauth2:'):]
self.api_client = client.DropboxClient(accessToken)
account_info = self.api_client.account_info()
except:
print "Please provide an oauth2 token in token_store.txt"
sys.exit(1)
# Metadata cache
self.metadata = {}
# File handles
self.fileHandles = {}
self.pathToHandle = {}
# Current file number
self.fileNumber = 1
print "Mounting %s's Dropbox account." % account_info['display_name']
print "Account Email Address: %s" % account_info['email']
# Pre-fill the metadata cache
self.curDelta = None
self.refreshDelta()
# Start a new thread to keep the metadata cache up to date
self.runMetaThread = True
self.metaThread = Thread(target=self.refreshMeta)
self.metaThread.daemon = True
self.metaThread.start()
# Populate the metadata from a list of entries, generally obtained from delta
def loadMeta(self, entriesList):
CACHE_TIME = 120
now = time()
timeout = now + CACHE_TIME
for path,meta in entriesList:
self.metadata[path] = (timeout, meta)
def refreshDelta(self):
if self.curDelta:
self.curDelta = self.api_client.delta(self.curDelta['cursor'])
else:
self.curDelta = self.api_client.delta()
self.loadMeta(self.curDelta['entries'])
while self.curDelta['has_more']:
self.curDelta = self.api_client.delta(self.curDelta['cursor'])
self.loadMeta(self.curDelta['entries'])
def refreshMeta(self):
while self.runMetaThread:
response = self.api_client.longpoll_delta(self.curDelta['cursor'], 30)
if response['changes']:
self.refreshDelta()
if 'backoff' in response:
sleep(float(response['backoff']))
# Extend timers on all files in metadata
# TODO: how do we handle new files added needing to invalidate metadata?
# We assume that once invalidated, there will never be a conflict
self.loadMeta((x,y[1]) for x,y in self.metadata.iteritems())
# Helper methods
# ==================
def getMetadata(self, path):
CACHE_TIME = 120
now = time()
timeout = now + CACHE_TIME
if path not in self.metadata or self.metadata[path][0] < now:
try:
meta = self.api_client.metadata(path)
self.metadata[path] = (timeout, meta)
# If successful, we should also cache the metadata for all the
# non-directory entries to avoid additional queries
if 'contents' in meta:
for f in meta['contents']:
if not f['is_dir']:
self.metadata[f['path']] = (timeout, f)
except:
self.metadata[path] = (timeout, None)
return self.metadata[path][1]
def cleanMeta(self,path):
try: del self.metadata[path]
except: pass
try: del self.metadata[os.path.dirname(path)]
except: pass
def moveHelper(self, old, new, func):
# Check for existence of the old
self.access(old)
try:
func(old,new)
self.cleanMeta(old)
self.cleanMeta(new)
except rest.ErrorResponse as e:
if e.status == 403:
raise FuseOSError(errno.EEXIST)
else:
print "An unknown error occured at the dropbox end"
print e
def getHandle(self):
self.fileNumber += 1
return self.fileNumber - 1
def convertToStringIO(self, fh):
f = self.fileHandles[fh]
if not isinstance(f, StringIO):
newF = StringIO(f.read())
self.fileHandles[fh] = newF
return newF
return f
# Filesystem methods
# ==================
# Only possible error is if the path does not exist.
def access(self, path, mode=None):
metadata = self.getMetadata(path)
if not metadata or 'is_deleted' in metadata:
raise FuseOSError(errno.ENOENT)
# This operation is not supported on Dropbox
def chmod(self, path, mode):
pass
# This operation is not supported on Dropbox
def chown(self, path, uid, gid):
pass
# TODO: Let fuse handle the case where path is not legitimate
@debug(False)
def getattr(self, path, fh=None):
# Get userid and groupid for current user.
uid = pwd.getpwuid(os.getuid()).pw_uid
gid = pwd.getpwuid(os.getuid()).pw_gid
# Get current time.
now = int(time())
# Check wether data exists for item.
path = path.strip()
item = self.getMetadata(path)
if not item or 'is_deleted' in item:
raise FuseOSError(errno.ENOENT)
# Handle last modified times.
if 'modified' in item:
modified = item['modified']
modified = mktime(datetime.strptime(modified, '%a, %d %b %Y %H:%M:%S +0000').timetuple())
else:
modified = int(now)
if item['is_dir'] == True:
# Get st_nlink count for directory.
properties = dict(
st_mode=stat.S_IFDIR | 0755,
st_size=0,
st_ctime=modified,
st_mtime=modified,
st_atime=now,
st_uid=uid,
st_gid=gid,
st_nlink=2
)
return properties
properties = dict(
st_mode=stat.S_IFREG | 0755,
st_size=item['bytes'],
st_ctime=modified,
st_mtime=modified,
st_atime=now,
st_uid=uid,
st_gid=gid,
st_nlink=1,
)
return properties
@debug()
def readdir(self, path, fh):
dirents = ['.', '..']
resp = self.getMetadata(path)
if resp and 'contents' in resp:
for f in resp['contents']:
name = os.path.basename(f['path'])
encoding = locale.getdefaultlocale()[1] or 'ascii'
dirents.append(('%s' % name).encode(encoding))
for r in dirents:
yield r
# Dropbox does not support symlinks
@debug()
def readlink(self, path):
raise FuseOSError(errno.EPERM)
# Only supported for creating files and directories
@debug()
def mknod(self, path, mode, dev=None):
if mode != stat.S_IFREG:
raise FuseOSError(errno.EPERM)
# Default to creating a file of empty length by faking it with an empty stringIO
self.api_client.put_file(path, StringIO())
self.cleanMeta(path)
@debug()
def rmdir(self, path):
metadata = self.getMetadata(path)
if not metadata:
raise FuseOSError(errno.ENOENT)
if not metadata['is_dir']:
raise FuseOSError(errno.ENOTDIR)
if 'contents' in metadata and len(metadata['contents']) > 0:
raise FuseOSError(errono.ENOTEMPTY)
try:
self.api_client.file_delete(path)
self.cleanMeta(path)
except Exception as e:
print "Deletion of directory %s failed!" % path
print e
raise FuseOSError(errno.EIO)
# If we succeed in creating, we must invalidate the cached value
@debug()
def mkdir(self, path, mode):
try:
self.api_client.file_create_folder(path)
self.cleanMeta(path)
except rest.ErrorResponse as e:
if e.status == 403:
raise FuseOSError(errno.EEXIST)
else:
print "An unknown error occured at the dropbox end"
################################################################################
# def statfs(self, path):
# full_path = self._full_path(path)
# stv = os.statvfs(full_path)
# return dict((key, getattr(stv, key)) for key in ('f_bavail', 'f_bfree',
# 'f_blocks', 'f_bsize', 'f_favail', 'f_ffree', 'f_files', 'f_flag',
# 'f_frsize', 'f_namemax'))
@debug()
def unlink(self, path):
metadata = self.getMetadata(path)
if not metadata:
raise FuseOSError(errno.ENOENT)
if metadata['is_dir']:
raise FuseOSError(errno.EISDIR)
try:
self.api_client.file_delete(path)
self.cleanMeta(path)
except:
print "Deletion of file %s failed!" % path
raise FuseOSError(errno.EIO)
# Dropbox does not support symlinks
@debug()
def symlink(self, name, target):
raise FuseOSError(errno.EPERM)
@debug()
def rename(self, old, new):
self.moveHelper(old,new, lambda old,new: self.api_client.file_move(old,new))
# Fuse's get_attr interfaces makes ln fail, so it makes little sense to implement this.
@debug()
def link(self, target, name):
raise FuseOSError(errno.EPERM)
# Dropbox does not support Updating timestamps only
@debug()
def utimens(self, path, times=None):
pass
# File methods
# ============
@debug()
def open(self, path, flags=None):
try:
f = self.api_client.get_file(path)
handle = self.getHandle()
self.pathToHandle[path] = handle
self.fileHandles[handle] = f
return handle
except:
if flags & os.O_CREAT or flags & os.O_TRUNC or flags & os.O_RDWR or flags & os.O_WRONLY:
handle = self.getHandle()
self.pathToHandle[path] = handle
self.fileHandles[handle] = StringIO()
return handle
# Raise only if we have no option to create a file
raise FuseOSError(errno.ENOENT)
# If it is not in fileHandles, then it is not legit
@debug()
def create(self, path, mode = None, fi=None):
metadata = self.getMetadata(path)
# Make sure file does not exist already
if metadata and not 'is_deleted' in metadata:
raise FuseOSError(errno.EEXIST)
# Register the new file internally so that get_attr will return something for it
self.mknod(path, stat.S_IFREG)
handle = self.getHandle()
self.pathToHandle[path] = handle
self.fileHandles[handle] = StringIO()
return handle
# We deliberately do not check if the file still exists, because by normal
# read semantics, the file exists if you have already opened it
# TODO: Decide on the correct error to throw if its not there
@debug()
def read(self, path, length, offset, fh):
if fh not in self.fileHandles: raise FuseOSError(errno.EINVAL)
f = self.convertToStringIO(fh)
f.seek(offset)
return f.read(length)
@debug()
def write(self, path, buf, offset, fh):
if fh not in self.fileHandles: raise FuseOSError(errno.EINVAL)
# Need to convert this into a StringIO if it is not already
f = self.convertToStringIO(fh)
f.seek(offset)
f.write(buf)
return len(buf)
@debug()
def truncate(self, path, length, fh=None):
if not fh: fh = self.pathToHandle[path]
if not fh: fh = self.open(path)
f = self.convertToStringIO(fh)
return f.truncate(length)
# Force the data up to Dropbox
@debug()
def flush(self, path, fh):
# First push it to a temporary file, since the API likes to be able to do
# real file operations
with tempfile.TemporaryFile() as TFile:
if isinstance(self.fileHandles[fh], StringIO):
TFile.write(self.fileHandles[fh].getvalue())
else:
f = self.convertToStringIO(fh)
TFile.write(f.getvalue())
TFile.seek(0)
self.api_client.put_file(path, TFile, overwrite=True)
self.cleanMeta(path)
return 0
# Clean up state
@debug()
def release(self, path, fh):
try:
self.fileHandles[fh].close()
del self.fileHandles[fh]
del self.pathToHandle[path]
except:
print "Error occurred when releasing a file handle"
return 0
def fsync(self, path, fdatasync, fh):
return self.flush(path, fh)
def usage():
usageMsg = """
python DBFuse.py <MountPoint>
""".strip()
print usageMsg
sys.exit(1)
def main(mountpoint):
FUSE(DBFuse(), mountpoint, foreground=True)
if __name__ == '__main__':
if len(sys.argv) < 2: usage()
main(sys.argv[1])