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.encodingutil import quote_output, get_filesystem_encoding
12 from allmydata.util.fileutil import abspath_expanduser_unicode
13 from allmydata.immutable.upload import FileName
16 class DropUploader(service.MultiService):
19 def __init__(self, client, upload_dircap, local_dir_utf8, inotify=None):
20 service.MultiService.__init__(self)
23 local_dir_u = abspath_expanduser_unicode(local_dir_utf8.decode('utf-8'))
24 if sys.platform == "win32":
25 local_dir = local_dir_u
27 local_dir = local_dir_u.encode(get_filesystem_encoding())
28 except (UnicodeEncodeError, UnicodeDecodeError):
29 raise AssertionError("The '[drop_upload] local.directory' parameter %s was not valid UTF-8 or "
30 "could not be represented in the filesystem encoding."
31 % quote_output(local_dir_utf8))
34 self._stats_provider = client.stats_provider
35 self._convergence = client.convergence
36 self._local_path = FilePath(local_dir)
38 self.is_upload_ready = False
41 from twisted.internet import inotify
42 self._inotify = inotify
44 if not self._local_path.exists():
45 raise AssertionError("The '[drop_upload] local.directory' parameter was %s but there is no directory at that location." % quote_output(local_dir_u))
46 if not self._local_path.isdir():
47 raise AssertionError("The '[drop_upload] local.directory' parameter was %s but the thing at that location is not a directory." % quote_output(local_dir_u))
49 # TODO: allow a path rather than a cap URI.
50 self._parent = self._client.create_node_from_uri(upload_dircap)
51 if not IDirectoryNode.providedBy(self._parent):
52 raise AssertionError("The URI in 'private/drop_upload_dircap' does not refer to a directory.")
53 if self._parent.is_unknown() or self._parent.is_readonly():
54 raise AssertionError("The URI in 'private/drop_upload_dircap' is not a writecap to a directory.")
56 self._uploaded_callback = lambda ign: None
58 self._notifier = inotify.INotify()
60 # We don't watch for IN_CREATE, because that would cause us to read and upload a
61 # possibly-incomplete file before the application has closed it. There should always
62 # be an IN_CLOSE_WRITE after an IN_CREATE (I think).
63 # TODO: what about IN_MOVE_SELF or IN_UNMOUNT?
64 mask = inotify.IN_CLOSE_WRITE | inotify.IN_MOVED_TO | inotify.IN_ONLYDIR
65 self._notifier.watch(self._local_path, mask=mask, callbacks=[self._notify])
67 def startService(self):
68 service.MultiService.startService(self)
69 d = self._notifier.startReading()
70 self._stats_provider.count('drop_upload.dirs_monitored', 1)
73 def upload_ready(self):
74 """upload_ready is used to signal us to start
75 processing the upload items...
77 self.is_upload_ready = True
79 def _notify(self, opaque, path, events_mask):
80 self._log("inotify event %r, %r, %r\n" % (opaque, path, ', '.join(self._inotify.humanReadableMask(events_mask))))
82 self._stats_provider.count('drop_upload.files_queued', 1)
83 eventually(self._process, opaque, path, events_mask)
85 def _process(self, opaque, path, events_mask):
86 d = defer.succeed(None)
88 # FIXME: if this already exists as a mutable file, we replace the directory entry,
89 # but we should probably modify the file (as the SFTP frontend does).
91 name = path.basename()
92 # on Windows the name is already Unicode
93 if not isinstance(name, unicode):
94 name = name.decode(get_filesystem_encoding())
96 u = FileName(path.path, self._convergence)
97 return self._parent.add_file(name, u)
98 d.addCallback(_add_file)
101 self._stats_provider.count('drop_upload.files_queued', -1)
102 self._stats_provider.count('drop_upload.files_uploaded', 1)
104 self._stats_provider.count('drop_upload.files_queued', -1)
106 self._log("drop-upload: %r failed to upload due to %r" % (path.path, f))
107 self._stats_provider.count('drop_upload.files_failed', 1)
110 self._log("drop-upload: notified file %r disappeared "
111 "(this is normal for temporary files): %r" % (path.path, f))
112 self._stats_provider.count('drop_upload.files_disappeared', 1)
114 d.addCallbacks(_succeeded, _failed)
115 d.addBoth(self._uploaded_callback)
118 def set_uploaded_callback(self, callback):
119 """This sets a function that will be called after a file has been uploaded."""
120 self._uploaded_callback = callback
122 def finish(self, for_tests=False):
123 self._notifier.stopReading()
124 self._stats_provider.count('drop_upload.dirs_monitored', -1)
125 if for_tests and hasattr(self._notifier, 'wait_until_stopped'):
126 return self._notifier.wait_until_stopped()
128 return defer.succeed(None)
131 self._client.log(msg)
132 #open("events", "ab+").write(msg)