4 from twisted.internet import defer
5 from twisted.python.filepath import FilePath
6 from twisted.application import service
7 from foolscap.api import eventually
9 from allmydata.interfaces import IDirectoryNode
11 from allmydata.util.fileutil import abspath_expanduser_unicode, precondition_abspath
12 from allmydata.util.encodingutil import listdir_unicode, to_filepath, \
13 unicode_from_filepath, quote_local_unicode_path, FilenameEncodingError
14 from allmydata.immutable.upload import FileName
15 from allmydata.scripts import backupdb
18 class DropUploader(service.MultiService):
21 def __init__(self, client, upload_dircap, local_dir, dbfile, inotify=None):
22 precondition_abspath(local_dir)
24 service.MultiService.__init__(self)
25 self._local_dir = abspath_expanduser_unicode(local_dir)
27 self._stats_provider = client.stats_provider
28 self._convergence = client.convergence
29 self._local_path = to_filepath(self._local_dir)
32 self.is_upload_ready = False
35 from twisted.internet import inotify
36 self._inotify = inotify
38 if not self._local_path.exists():
39 raise AssertionError("The '[drop_upload] local.directory' parameter was %s "
40 "but there is no directory at that location."
41 % quote_local_unicode_path(local_dir))
42 if not self._local_path.isdir():
43 raise AssertionError("The '[drop_upload] local.directory' parameter was %s "
44 "but the thing at that location is not a directory."
45 % quote_local_unicode_path(local_dir))
47 # TODO: allow a path rather than a cap URI.
48 self._parent = self._client.create_node_from_uri(upload_dircap)
49 if not IDirectoryNode.providedBy(self._parent):
50 raise AssertionError("The URI in 'private/drop_upload_dircap' does not refer to a directory.")
51 if self._parent.is_unknown() or self._parent.is_readonly():
52 raise AssertionError("The URI in 'private/drop_upload_dircap' is not a writecap to a directory.")
54 self._uploaded_callback = lambda ign: None
56 self._notifier = inotify.INotify()
58 # We don't watch for IN_CREATE, because that would cause us to read and upload a
59 # possibly-incomplete file before the application has closed it. There should always
60 # be an IN_CLOSE_WRITE after an IN_CREATE (I think).
61 # TODO: what about IN_MOVE_SELF or IN_UNMOUNT?
62 mask = inotify.IN_CLOSE_WRITE | inotify.IN_MOVED_TO | inotify.IN_ONLYDIR
63 self._notifier.watch(self._local_path, mask=mask, callbacks=[self._notify])
65 def _check_db_file(self, childpath):
66 # returns True if the file must be uploaded.
67 assert self._db != None
68 r = self._db.check_file(childpath)
69 filecap = r.was_uploaded()
73 def startService(self):
74 self._db = backupdb.get_backupdb(self._dbfile)
76 return Failure(Exception('ERROR: Unable to load magic folder db.'))
78 service.MultiService.startService(self)
79 d = self._notifier.startReading()
80 self._stats_provider.count('drop_upload.dirs_monitored', 1)
83 def upload_ready(self):
84 """upload_ready is used to signal us to start
85 processing the upload items...
87 self.is_upload_ready = True
89 def _notify(self, opaque, path, events_mask):
90 self._log("inotify event %r, %r, %r\n" % (opaque, path, ', '.join(self._inotify.humanReadableMask(events_mask))))
92 self._stats_provider.count('drop_upload.files_queued', 1)
93 eventually(self._process, opaque, path, events_mask)
95 def _process(self, opaque, path, events_mask):
96 d = defer.succeed(None)
98 # FIXME: if this already exists as a mutable file, we replace the directory entry,
99 # but we should probably modify the file (as the SFTP frontend does).
101 name = path.basename()
102 # on Windows the name is already Unicode
103 if not isinstance(name, unicode):
104 name = name.decode(get_filesystem_encoding())
106 u = FileName(path.path, self._convergence)
107 return self._parent.add_file(name, u)
108 d.addCallback(_add_file)
111 self._stats_provider.count('drop_upload.files_queued', -1)
112 self._stats_provider.count('drop_upload.files_uploaded', 1)
114 self._stats_provider.count('drop_upload.files_queued', -1)
116 self._log("drop-upload: %r failed to upload due to %r" % (path.path, f))
117 self._stats_provider.count('drop_upload.files_failed', 1)
120 self._log("drop-upload: notified file %r disappeared "
121 "(this is normal for temporary files): %r" % (path.path, f))
122 self._stats_provider.count('drop_upload.files_disappeared', 1)
124 d.addCallbacks(_succeeded, _failed)
125 d.addBoth(self._uploaded_callback)
128 def set_uploaded_callback(self, callback):
129 """This sets a function that will be called after a file has been uploaded."""
130 self._uploaded_callback = callback
132 def finish(self, for_tests=False):
133 self._notifier.stopReading()
134 self._stats_provider.count('drop_upload.dirs_monitored', -1)
135 if for_tests and hasattr(self._notifier, 'wait_until_stopped'):
136 return self._notifier.wait_until_stopped()
138 return defer.succeed(None)
141 self._client.log(msg)
142 #open("events", "ab+").write(msg)