remote.py 12 KB

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