]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/frontends/drop_upload.py
06f2273a8d3340767e0c6d64e8ec2e45c4438ce4
[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.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
16
17
18 class DropUploader(service.MultiService):
19     name = 'drop-upload'
20
21     def __init__(self, client, upload_dircap, local_dir, dbfile, inotify=None):
22         precondition_abspath(local_dir)
23
24         service.MultiService.__init__(self)
25         self._local_dir = abspath_expanduser_unicode(local_dir)
26         self._client = client
27         self._stats_provider = client.stats_provider
28         self._convergence = client.convergence
29         self._local_path = to_filepath(self._local_dir)
30         self._dbfile = dbfile
31
32         self.is_upload_ready = False
33
34         if inotify is None:
35             from twisted.internet import inotify
36         self._inotify = inotify
37
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))
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 _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()
70         if filecap is False:
71             return True
72
73     def startService(self):
74         self._db = backupdb.get_backupdb(self._dbfile)
75         if self._db is None:
76             return Failure(Exception('ERROR: Unable to load magic folder db.'))
77
78         service.MultiService.startService(self)
79         d = self._notifier.startReading()
80         self._stats_provider.count('drop_upload.dirs_monitored', 1)
81         return d
82
83     def upload_ready(self):
84         """upload_ready is used to signal us to start
85         processing the upload items...
86         """
87         self.is_upload_ready = True
88
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))))
91
92         self._stats_provider.count('drop_upload.files_queued', 1)
93         eventually(self._process, opaque, path, events_mask)
94
95     def _process(self, opaque, path, events_mask):
96         d = defer.succeed(None)
97
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).
100         def _add_file(ign):
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())
105
106             u = FileName(path.path, self._convergence)
107             return self._parent.add_file(name, u)
108         d.addCallback(_add_file)
109
110         def _succeeded(ign):
111             self._stats_provider.count('drop_upload.files_queued', -1)
112             self._stats_provider.count('drop_upload.files_uploaded', 1)
113         def _failed(f):
114             self._stats_provider.count('drop_upload.files_queued', -1)
115             if path.exists():
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)
118                 return f
119             else:
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)
123                 return None
124         d.addCallbacks(_succeeded, _failed)
125         d.addBoth(self._uploaded_callback)
126         return d
127
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
131
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()
137         else:
138             return defer.succeed(None)
139
140     def _log(self, msg):
141         self._client.log(msg)
142         #open("events", "ab+").write(msg)