]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/frontends/drop_upload.py
drop-upload.py: fix error messages.
[tahoe-lafs/tahoe-lafs.git] / src / allmydata / frontends / drop_upload.py
1
2 import sys
3
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
8
9 from allmydata.interfaces import IDirectoryNode
10
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
14
15
16 class DropUploader(service.MultiService):
17     name = 'drop-upload'
18
19     def __init__(self, client, upload_dircap, local_dir_utf8, inotify=None):
20         service.MultiService.__init__(self)
21
22         try:
23             local_dir_u = abspath_expanduser_unicode(local_dir_utf8.decode('utf-8'))
24             if sys.platform == "win32":
25                 local_dir = local_dir_u
26             else:
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))
32
33         self._client = client
34         self._stats_provider = client.stats_provider
35         self._convergence = client.convergence
36         self._local_path = FilePath(local_dir)
37
38         if inotify is None:
39             from twisted.internet import inotify
40         self._inotify = inotify
41
42         if not self._local_path.exists():
43             raise AssertionError("The '[drop_upload] local.directory' parameter was %s but there is no directory at that location." % quote_output(local_dir_u))
44         if not self._local_path.isdir():
45             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))
46
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.")
53
54         self._uploaded_callback = lambda ign: None
55
56         self._notifier = inotify.INotify()
57
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])
64
65     def startService(self):
66         service.MultiService.startService(self)
67         d = self._notifier.startReading()
68         self._stats_provider.count('drop_upload.dirs_monitored', 1)
69         return d
70
71     def _notify(self, opaque, path, events_mask):
72         self._log("inotify event %r, %r, %r\n" % (opaque, path, ', '.join(self._inotify.humanReadableMask(events_mask))))
73
74         self._stats_provider.count('drop_upload.files_queued', 1)
75         eventually(self._process, opaque, path, events_mask)
76
77     def _process(self, opaque, path, events_mask):
78         d = defer.succeed(None)
79
80         # FIXME: if this already exists as a mutable file, we replace the directory entry,
81         # but we should probably modify the file (as the SFTP frontend does).
82         def _add_file(ign):
83             name = path.basename()
84             # on Windows the name is already Unicode
85             if not isinstance(name, unicode):
86                 name = name.decode(get_filesystem_encoding())
87
88             u = FileName(path.path, self._convergence)
89             return self._parent.add_file(name, u)
90         d.addCallback(_add_file)
91
92         def _succeeded(ign):
93             self._stats_provider.count('drop_upload.files_queued', -1)
94             self._stats_provider.count('drop_upload.files_uploaded', 1)
95         def _failed(f):
96             self._stats_provider.count('drop_upload.files_queued', -1)
97             if path.exists():
98                 self._log("drop-upload: %r failed to upload due to %r" % (path.path, f))
99                 self._stats_provider.count('drop_upload.files_failed', 1)
100                 return f
101             else:
102                 self._log("drop-upload: notified file %r disappeared "
103                           "(this is normal for temporary files): %r" % (path.path, f))
104                 self._stats_provider.count('drop_upload.files_disappeared', 1)
105                 return None
106         d.addCallbacks(_succeeded, _failed)
107         d.addBoth(self._uploaded_callback)
108         return d
109
110     def set_uploaded_callback(self, callback):
111         """This sets a function that will be called after a file has been uploaded."""
112         self._uploaded_callback = callback
113
114     def finish(self, for_tests=False):
115         self._notifier.stopReading()
116         self._stats_provider.count('drop_upload.dirs_monitored', -1)
117         if for_tests and hasattr(self._notifier, 'wait_until_stopped'):
118             return self._notifier.wait_until_stopped()
119         else:
120             return defer.succeed(None)
121
122     def _log(self, msg):
123         self._client.log(msg)
124         #open("events", "ab+").write(msg)