remote.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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. remote_path = None
  95. umask = None
  96. class RPCError(Exception):
  97. def __init__(self, name):
  98. self.name = name
  99. def __init__(self, location, create=False):
  100. self.location = location
  101. self.preload_ids = []
  102. self.msgid = 0
  103. self.to_send = b''
  104. self.cache = {}
  105. self.ignore_responses = set()
  106. self.responses = {}
  107. self.unpacker = msgpack.Unpacker(use_list=False)
  108. self.p = None
  109. # use local umask also for the remote process
  110. umask = ['--umask', '%03o' % self.umask]
  111. if location.host == '__testsuite__':
  112. args = [sys.executable, '-m', 'borg.archiver', 'serve'] + umask + self.extra_test_args
  113. else:
  114. args = ['ssh']
  115. if location.port:
  116. args += ['-p', str(location.port)]
  117. if location.user:
  118. args.append('%s@%s' % (location.user, location.host))
  119. else:
  120. args.append('%s' % location.host)
  121. args += [self.remote_path, 'serve'] + umask
  122. self.p = Popen(args, bufsize=0, stdin=PIPE, stdout=PIPE)
  123. self.stdin_fd = self.p.stdin.fileno()
  124. self.stdout_fd = self.p.stdout.fileno()
  125. fcntl.fcntl(self.stdin_fd, fcntl.F_SETFL, fcntl.fcntl(self.stdin_fd, fcntl.F_GETFL) | os.O_NONBLOCK)
  126. fcntl.fcntl(self.stdout_fd, fcntl.F_SETFL, fcntl.fcntl(self.stdout_fd, fcntl.F_GETFL) | os.O_NONBLOCK)
  127. self.r_fds = [self.stdout_fd]
  128. self.x_fds = [self.stdin_fd, self.stdout_fd]
  129. try:
  130. version = self.call('negotiate', 1)
  131. except ConnectionClosed:
  132. raise Exception('Server immediately closed connection - is Borg installed and working on the server?')
  133. if version != 1:
  134. raise Exception('Server insisted on using unsupported protocol version %d' % version)
  135. self.id = self.call('open', location.path, create)
  136. def __del__(self):
  137. self.close()
  138. def __repr__(self):
  139. return '<%s %s>' % (self.__class__.__name__, self.location.canonical_path())
  140. def call(self, cmd, *args, **kw):
  141. for resp in self.call_many(cmd, [args], **kw):
  142. return resp
  143. def call_many(self, cmd, calls, wait=True, is_preloaded=False):
  144. if not calls:
  145. return
  146. def fetch_from_cache(args):
  147. msgid = self.cache[args].pop(0)
  148. if not self.cache[args]:
  149. del self.cache[args]
  150. return msgid
  151. calls = list(calls)
  152. waiting_for = []
  153. w_fds = [self.stdin_fd]
  154. while wait or calls:
  155. while waiting_for:
  156. try:
  157. error, res = self.responses.pop(waiting_for[0])
  158. waiting_for.pop(0)
  159. if error:
  160. if error == b'DoesNotExist':
  161. raise Repository.DoesNotExist(self.location.orig)
  162. elif error == b'AlreadyExists':
  163. raise Repository.AlreadyExists(self.location.orig)
  164. elif error == b'CheckNeeded':
  165. raise Repository.CheckNeeded(self.location.orig)
  166. elif error == b'IntegrityError':
  167. raise IntegrityError(res)
  168. elif error == b'PathNotAllowed':
  169. raise PathNotAllowed(*res)
  170. elif error == b'ObjectNotFound':
  171. raise Repository.ObjectNotFound(res[0], self.location.orig)
  172. elif error == b'InvalidRPCMethod':
  173. raise InvalidRPCMethod(*res)
  174. else:
  175. raise self.RPCError(res.decode('utf-8'))
  176. else:
  177. yield res
  178. if not waiting_for and not calls:
  179. return
  180. except KeyError:
  181. break
  182. r, w, x = select.select(self.r_fds, w_fds, self.x_fds, 1)
  183. if x:
  184. raise Exception('FD exception occurred')
  185. if r:
  186. data = os.read(self.stdout_fd, BUFSIZE)
  187. if not data:
  188. raise ConnectionClosed()
  189. self.unpacker.feed(data)
  190. for unpacked in self.unpacker:
  191. if not (isinstance(unpacked, tuple) and len(unpacked) == 4):
  192. raise Exception("Unexpected RPC data format.")
  193. type, msgid, error, res = unpacked
  194. if msgid in self.ignore_responses:
  195. self.ignore_responses.remove(msgid)
  196. else:
  197. self.responses[msgid] = error, res
  198. if w:
  199. while not self.to_send and (calls or self.preload_ids) and len(waiting_for) < 100:
  200. if calls:
  201. if is_preloaded:
  202. if calls[0] in self.cache:
  203. waiting_for.append(fetch_from_cache(calls.pop(0)))
  204. else:
  205. args = calls.pop(0)
  206. if cmd == 'get' and args in self.cache:
  207. waiting_for.append(fetch_from_cache(args))
  208. else:
  209. self.msgid += 1
  210. waiting_for.append(self.msgid)
  211. self.to_send = msgpack.packb((1, self.msgid, cmd, args))
  212. if not self.to_send and self.preload_ids:
  213. args = (self.preload_ids.pop(0),)
  214. self.msgid += 1
  215. self.cache.setdefault(args, []).append(self.msgid)
  216. self.to_send = msgpack.packb((1, self.msgid, cmd, args))
  217. if self.to_send:
  218. try:
  219. self.to_send = self.to_send[os.write(self.stdin_fd, self.to_send):]
  220. except OSError as e:
  221. # io.write might raise EAGAIN even though select indicates
  222. # that the fd should be writable
  223. if e.errno != errno.EAGAIN:
  224. raise
  225. if not self.to_send and not (calls or self.preload_ids):
  226. w_fds = []
  227. self.ignore_responses |= set(waiting_for)
  228. def check(self, repair=False):
  229. return self.call('check', repair)
  230. def commit(self, *args):
  231. return self.call('commit')
  232. def rollback(self, *args):
  233. return self.call('rollback')
  234. def destroy(self):
  235. return self.call('destroy')
  236. def __len__(self):
  237. return self.call('__len__')
  238. def list(self, limit=None, marker=None):
  239. return self.call('list', limit, marker)
  240. def get(self, id_):
  241. for resp in self.get_many([id_]):
  242. return resp
  243. def get_many(self, ids, is_preloaded=False):
  244. for resp in self.call_many('get', [(id_,) for id_ in ids], is_preloaded=is_preloaded):
  245. yield resp
  246. def put(self, id_, data, wait=True):
  247. return self.call('put', id_, data, wait=wait)
  248. def delete(self, id_, wait=True):
  249. return self.call('delete', id_, wait=wait)
  250. def save_key(self, keydata):
  251. return self.call('save_key', keydata)
  252. def load_key(self):
  253. return self.call('load_key')
  254. def close(self):
  255. if self.p:
  256. self.p.stdin.close()
  257. self.p.stdout.close()
  258. self.p.wait()
  259. self.p = None
  260. def preload(self, ids):
  261. self.preload_ids += ids
  262. class RepositoryCache:
  263. """A caching Repository wrapper
  264. Caches Repository GET operations using a local temporary Repository.
  265. """
  266. def __init__(self, repository):
  267. self.repository = repository
  268. tmppath = tempfile.mkdtemp(prefix='borg-tmp')
  269. self.caching_repo = Repository(tmppath, create=True, exclusive=True)
  270. def __del__(self):
  271. self.caching_repo.destroy()
  272. def get(self, key):
  273. return next(self.get_many([key]))
  274. def get_many(self, keys):
  275. unknown_keys = [key for key in keys if key not in self.caching_repo]
  276. repository_iterator = zip(unknown_keys, self.repository.get_many(unknown_keys))
  277. for key in keys:
  278. try:
  279. yield self.caching_repo.get(key)
  280. except Repository.ObjectNotFound:
  281. for key_, data in repository_iterator:
  282. if key_ == key:
  283. self.caching_repo.put(key, data)
  284. yield data
  285. break
  286. # Consume any pending requests
  287. for _ in repository_iterator:
  288. pass
  289. def cache_if_remote(repository):
  290. if isinstance(repository, RemoteRepository):
  291. return RepositoryCache(repository)
  292. return repository