remote.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. import errno
  2. import fcntl
  3. import msgpack
  4. import os
  5. import select
  6. from subprocess import Popen, PIPE
  7. import sys
  8. import tempfile
  9. import traceback
  10. from . import __version__
  11. from .helpers import Error, IntegrityError
  12. from .repository import Repository
  13. BUFSIZE = 10 * 1024 * 1024
  14. class ConnectionClosed(Error):
  15. """Connection closed by remote host"""
  16. class PathNotAllowed(Error):
  17. """Repository path not allowed"""
  18. class InvalidRPCMethod(Error):
  19. """RPC method is not valid"""
  20. class RepositoryServer:
  21. rpc_methods = (
  22. '__len__',
  23. 'check',
  24. 'commit',
  25. 'delete',
  26. 'destroy',
  27. 'get',
  28. 'list',
  29. 'negotiate',
  30. 'open',
  31. 'put',
  32. 'repair',
  33. 'rollback',
  34. 'save_key',
  35. 'load_key',
  36. )
  37. def __init__(self, restrict_to_paths):
  38. self.repository = None
  39. self.restrict_to_paths = restrict_to_paths
  40. def serve(self):
  41. stdin_fd = sys.stdin.fileno()
  42. stdout_fd = sys.stdout.fileno()
  43. # Make stdin non-blocking
  44. fl = fcntl.fcntl(stdin_fd, fcntl.F_GETFL)
  45. fcntl.fcntl(stdin_fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
  46. # Make stdout blocking
  47. fl = fcntl.fcntl(stdout_fd, fcntl.F_GETFL)
  48. fcntl.fcntl(stdout_fd, fcntl.F_SETFL, fl & ~os.O_NONBLOCK)
  49. unpacker = msgpack.Unpacker(use_list=False)
  50. while True:
  51. r, w, es = select.select([stdin_fd], [], [], 10)
  52. if r:
  53. data = os.read(stdin_fd, BUFSIZE)
  54. if not data:
  55. return
  56. unpacker.feed(data)
  57. for unpacked in unpacker:
  58. if not (isinstance(unpacked, tuple) and len(unpacked) == 4):
  59. raise Exception("Unexpected RPC data format.")
  60. type, msgid, method, args = unpacked
  61. method = method.decode('ascii')
  62. try:
  63. if method not in self.rpc_methods:
  64. raise InvalidRPCMethod(method)
  65. try:
  66. f = getattr(self, method)
  67. except AttributeError:
  68. f = getattr(self.repository, method)
  69. res = f(*args)
  70. except BaseException as e:
  71. exc = "Remote Traceback by Borg %s%s%s" % (__version__, os.linesep, traceback.format_exc())
  72. os.write(stdout_fd, msgpack.packb((1, msgid, e.__class__.__name__, exc)))
  73. else:
  74. os.write(stdout_fd, msgpack.packb((1, msgid, None, res)))
  75. if es:
  76. return
  77. def negotiate(self, versions):
  78. return 1
  79. def open(self, path, create=False):
  80. path = os.fsdecode(path)
  81. if path.startswith('/~'):
  82. path = path[1:]
  83. path = os.path.realpath(os.path.expanduser(path))
  84. if self.restrict_to_paths:
  85. for restrict_to_path in self.restrict_to_paths:
  86. if path.startswith(os.path.realpath(restrict_to_path)):
  87. break
  88. else:
  89. raise PathNotAllowed(path)
  90. self.repository = Repository(path, create)
  91. return self.repository.id
  92. class RemoteRepository:
  93. extra_test_args = []
  94. class RPCError(Exception):
  95. def __init__(self, name):
  96. self.name = name
  97. def __init__(self, location, create=False):
  98. self.location = location
  99. self.preload_ids = []
  100. self.msgid = 0
  101. self.to_send = b''
  102. self.cache = {}
  103. self.ignore_responses = set()
  104. self.responses = {}
  105. self.unpacker = msgpack.Unpacker(use_list=False)
  106. self.p = None
  107. if location.host == '__testsuite__':
  108. args = [sys.executable, '-m', 'borg.archiver', 'serve'] + self.extra_test_args
  109. else:
  110. args = ['ssh']
  111. if location.port:
  112. args += ['-p', str(location.port)]
  113. if location.user:
  114. args.append('%s@%s' % (location.user, location.host))
  115. else:
  116. args.append('%s' % location.host)
  117. args += ['borg', 'serve']
  118. self.p = Popen(args, bufsize=0, stdin=PIPE, stdout=PIPE)
  119. self.stdin_fd = self.p.stdin.fileno()
  120. self.stdout_fd = self.p.stdout.fileno()
  121. fcntl.fcntl(self.stdin_fd, fcntl.F_SETFL, fcntl.fcntl(self.stdin_fd, fcntl.F_GETFL) | os.O_NONBLOCK)
  122. fcntl.fcntl(self.stdout_fd, fcntl.F_SETFL, fcntl.fcntl(self.stdout_fd, fcntl.F_GETFL) | os.O_NONBLOCK)
  123. self.r_fds = [self.stdout_fd]
  124. self.x_fds = [self.stdin_fd, self.stdout_fd]
  125. try:
  126. version = self.call('negotiate', 1)
  127. except ConnectionClosed:
  128. raise Exception('Server immediately closed connection - is Borg installed and working on the server?')
  129. if version != 1:
  130. raise Exception('Server insisted on using unsupported protocol version %d' % version)
  131. self.id = self.call('open', location.path, create)
  132. def __del__(self):
  133. self.close()
  134. def __repr__(self):
  135. return '<%s %s>' % (self.__class__.__name__, self.location.canonical_path())
  136. def call(self, cmd, *args, **kw):
  137. for resp in self.call_many(cmd, [args], **kw):
  138. return resp
  139. def call_many(self, cmd, calls, wait=True, is_preloaded=False):
  140. if not calls:
  141. return
  142. def fetch_from_cache(args):
  143. msgid = self.cache[args].pop(0)
  144. if not self.cache[args]:
  145. del self.cache[args]
  146. return msgid
  147. calls = list(calls)
  148. waiting_for = []
  149. w_fds = [self.stdin_fd]
  150. while wait or calls:
  151. while waiting_for:
  152. try:
  153. error, res = self.responses.pop(waiting_for[0])
  154. waiting_for.pop(0)
  155. if error:
  156. if error == b'DoesNotExist':
  157. raise Repository.DoesNotExist(self.location.orig)
  158. elif error == b'AlreadyExists':
  159. raise Repository.AlreadyExists(self.location.orig)
  160. elif error == b'CheckNeeded':
  161. raise Repository.CheckNeeded(self.location.orig)
  162. elif error == b'IntegrityError':
  163. raise IntegrityError(res)
  164. elif error == b'PathNotAllowed':
  165. raise PathNotAllowed(*res)
  166. elif error == b'ObjectNotFound':
  167. raise Repository.ObjectNotFound(res[0], self.location.orig)
  168. elif error == b'InvalidRPCMethod':
  169. raise InvalidRPCMethod(*res)
  170. else:
  171. raise self.RPCError(res.decode('utf-8'))
  172. else:
  173. yield res
  174. if not waiting_for and not calls:
  175. return
  176. except KeyError:
  177. break
  178. r, w, x = select.select(self.r_fds, w_fds, self.x_fds, 1)
  179. if x:
  180. raise Exception('FD exception occurred')
  181. if r:
  182. data = os.read(self.stdout_fd, BUFSIZE)
  183. if not data:
  184. raise ConnectionClosed()
  185. self.unpacker.feed(data)
  186. for unpacked in self.unpacker:
  187. if not (isinstance(unpacked, tuple) and len(unpacked) == 4):
  188. raise Exception("Unexpected RPC data format.")
  189. type, msgid, error, res = unpacked
  190. if msgid in self.ignore_responses:
  191. self.ignore_responses.remove(msgid)
  192. else:
  193. self.responses[msgid] = error, res
  194. if w:
  195. while not self.to_send and (calls or self.preload_ids) and len(waiting_for) < 100:
  196. if calls:
  197. if is_preloaded:
  198. if calls[0] in self.cache:
  199. waiting_for.append(fetch_from_cache(calls.pop(0)))
  200. else:
  201. args = calls.pop(0)
  202. if cmd == 'get' and args in self.cache:
  203. waiting_for.append(fetch_from_cache(args))
  204. else:
  205. self.msgid += 1
  206. waiting_for.append(self.msgid)
  207. self.to_send = msgpack.packb((1, self.msgid, cmd, args))
  208. if not self.to_send and self.preload_ids:
  209. args = (self.preload_ids.pop(0),)
  210. self.msgid += 1
  211. self.cache.setdefault(args, []).append(self.msgid)
  212. self.to_send = msgpack.packb((1, self.msgid, cmd, args))
  213. if self.to_send:
  214. try:
  215. self.to_send = self.to_send[os.write(self.stdin_fd, self.to_send):]
  216. except OSError as e:
  217. # io.write might raise EAGAIN even though select indicates
  218. # that the fd should be writable
  219. if e.errno != errno.EAGAIN:
  220. raise
  221. if not self.to_send and not (calls or self.preload_ids):
  222. w_fds = []
  223. self.ignore_responses |= set(waiting_for)
  224. def check(self, repair=False):
  225. return self.call('check', repair)
  226. def commit(self, *args):
  227. return self.call('commit')
  228. def rollback(self, *args):
  229. return self.call('rollback')
  230. def destroy(self):
  231. return self.call('destroy')
  232. def __len__(self):
  233. return self.call('__len__')
  234. def list(self, limit=None, marker=None):
  235. return self.call('list', limit, marker)
  236. def get(self, id_):
  237. for resp in self.get_many([id_]):
  238. return resp
  239. def get_many(self, ids, is_preloaded=False):
  240. for resp in self.call_many('get', [(id_,) for id_ in ids], is_preloaded=is_preloaded):
  241. yield resp
  242. def put(self, id_, data, wait=True):
  243. return self.call('put', id_, data, wait=wait)
  244. def delete(self, id_, wait=True):
  245. return self.call('delete', id_, wait=wait)
  246. def save_key(self, keydata):
  247. return self.call('save_key', keydata)
  248. def load_key(self):
  249. return self.call('load_key')
  250. def close(self):
  251. if self.p:
  252. self.p.stdin.close()
  253. self.p.stdout.close()
  254. self.p.wait()
  255. self.p = None
  256. def preload(self, ids):
  257. self.preload_ids += ids
  258. class RepositoryCache:
  259. """A caching Repository wrapper
  260. Caches Repository GET operations using a local temporary Repository.
  261. """
  262. def __init__(self, repository):
  263. self.repository = repository
  264. tmppath = tempfile.mkdtemp(prefix='borg-tmp')
  265. self.caching_repo = Repository(tmppath, create=True, exclusive=True)
  266. def __del__(self):
  267. self.caching_repo.destroy()
  268. def get(self, key):
  269. return next(self.get_many([key]))
  270. def get_many(self, keys):
  271. unknown_keys = [key for key in keys if key not in self.caching_repo]
  272. repository_iterator = zip(unknown_keys, self.repository.get_many(unknown_keys))
  273. for key in keys:
  274. try:
  275. yield self.caching_repo.get(key)
  276. except Repository.ObjectNotFound:
  277. for key_, data in repository_iterator:
  278. if key_ == key:
  279. self.caching_repo.put(key, data)
  280. yield data
  281. break
  282. # Consume any pending requests
  283. for _ in repository_iterator:
  284. pass
  285. def cache_if_remote(repository):
  286. if isinstance(repository, RemoteRepository):
  287. return RepositoryCache(repository)
  288. return repository