remote.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. import errno
  2. import fcntl
  3. import logging
  4. import os
  5. import select
  6. import shlex
  7. from subprocess import Popen, PIPE
  8. import sys
  9. import tempfile
  10. from . import __version__
  11. from .helpers import Error, IntegrityError, sysinfo
  12. from .repository import Repository
  13. import msgpack
  14. RPC_PROTOCOL_VERSION = 2
  15. BUFSIZE = 10 * 1024 * 1024
  16. class ConnectionClosed(Error):
  17. """Connection closed by remote host"""
  18. class ConnectionClosedWithHint(ConnectionClosed):
  19. """Connection closed by remote host. {}"""
  20. class PathNotAllowed(Error):
  21. """Repository path not allowed"""
  22. class InvalidRPCMethod(Error):
  23. """RPC method {} is not valid"""
  24. class RepositoryServer: # pragma: no cover
  25. rpc_methods = (
  26. '__len__',
  27. 'check',
  28. 'commit',
  29. 'delete',
  30. 'destroy',
  31. 'get',
  32. 'list',
  33. 'negotiate',
  34. 'open',
  35. 'put',
  36. 'rollback',
  37. 'save_key',
  38. 'load_key',
  39. 'break_lock',
  40. )
  41. def __init__(self, restrict_to_paths, append_only):
  42. self.repository = None
  43. self.restrict_to_paths = restrict_to_paths
  44. self.append_only = append_only
  45. def serve(self):
  46. stdin_fd = sys.stdin.fileno()
  47. stdout_fd = sys.stdout.fileno()
  48. stderr_fd = sys.stdout.fileno()
  49. # Make stdin non-blocking
  50. fl = fcntl.fcntl(stdin_fd, fcntl.F_GETFL)
  51. fcntl.fcntl(stdin_fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
  52. # Make stdout blocking
  53. fl = fcntl.fcntl(stdout_fd, fcntl.F_GETFL)
  54. fcntl.fcntl(stdout_fd, fcntl.F_SETFL, fl & ~os.O_NONBLOCK)
  55. # Make stderr blocking
  56. fl = fcntl.fcntl(stderr_fd, fcntl.F_GETFL)
  57. fcntl.fcntl(stderr_fd, fcntl.F_SETFL, fl & ~os.O_NONBLOCK)
  58. unpacker = msgpack.Unpacker(use_list=False)
  59. while True:
  60. r, w, es = select.select([stdin_fd], [], [], 10)
  61. if r:
  62. data = os.read(stdin_fd, BUFSIZE)
  63. if not data:
  64. self.repository.close()
  65. return
  66. unpacker.feed(data)
  67. for unpacked in unpacker:
  68. if not (isinstance(unpacked, tuple) and len(unpacked) == 4):
  69. self.repository.close()
  70. raise Exception("Unexpected RPC data format.")
  71. type, msgid, method, args = unpacked
  72. method = method.decode('ascii')
  73. try:
  74. if method not in self.rpc_methods:
  75. raise InvalidRPCMethod(method)
  76. try:
  77. f = getattr(self, method)
  78. except AttributeError:
  79. f = getattr(self.repository, method)
  80. res = f(*args)
  81. except BaseException as e:
  82. # These exceptions are reconstructed on the client end in RemoteRepository.call_many(),
  83. # and will be handled just like locally raised exceptions. Suppress the remote traceback
  84. # for these, except ErrorWithTraceback, which should always display a traceback.
  85. if not isinstance(e, (Repository.DoesNotExist, Repository.AlreadyExists, PathNotAllowed)):
  86. logging.exception('Borg %s: exception in RPC call:', __version__)
  87. logging.error(sysinfo())
  88. exc = "Remote Exception (see remote log for the traceback)"
  89. os.write(stdout_fd, msgpack.packb((1, msgid, e.__class__.__name__, exc)))
  90. else:
  91. os.write(stdout_fd, msgpack.packb((1, msgid, None, res)))
  92. if es:
  93. self.repository.close()
  94. return
  95. def negotiate(self, versions):
  96. return RPC_PROTOCOL_VERSION
  97. def open(self, path, create=False, lock_wait=None, lock=True):
  98. path = os.fsdecode(path)
  99. if path.startswith('/~'):
  100. path = path[1:]
  101. path = os.path.realpath(os.path.expanduser(path))
  102. if self.restrict_to_paths:
  103. for restrict_to_path in self.restrict_to_paths:
  104. if path.startswith(os.path.realpath(restrict_to_path)):
  105. break
  106. else:
  107. raise PathNotAllowed(path)
  108. self.repository = Repository(path, create, lock_wait=lock_wait, lock=lock, append_only=self.append_only)
  109. self.repository.__enter__() # clean exit handled by serve() method
  110. return self.repository.id
  111. class RemoteRepository:
  112. extra_test_args = []
  113. class RPCError(Exception):
  114. def __init__(self, name):
  115. self.name = name
  116. def __init__(self, location, create=False, lock_wait=None, lock=True, args=None):
  117. self.location = self._location = location
  118. self.preload_ids = []
  119. self.msgid = 0
  120. self.to_send = b''
  121. self.cache = {}
  122. self.ignore_responses = set()
  123. self.responses = {}
  124. self.unpacker = msgpack.Unpacker(use_list=False)
  125. self.p = None
  126. testing = location.host == '__testsuite__'
  127. borg_cmd = self.borg_cmd(args, testing)
  128. env = dict(os.environ)
  129. if not testing:
  130. borg_cmd = self.ssh_cmd(location) + borg_cmd
  131. # pyinstaller binary adds LD_LIBRARY_PATH=/tmp/_ME... but we do not want
  132. # that the system's ssh binary picks up (non-matching) libraries from there
  133. env.pop('LD_LIBRARY_PATH', None)
  134. env.pop('BORG_PASSPHRASE', None) # security: do not give secrets to subprocess
  135. self.p = Popen(borg_cmd, bufsize=0, stdin=PIPE, stdout=PIPE, stderr=PIPE, env=env)
  136. self.stdin_fd = self.p.stdin.fileno()
  137. self.stdout_fd = self.p.stdout.fileno()
  138. self.stderr_fd = self.p.stderr.fileno()
  139. fcntl.fcntl(self.stdin_fd, fcntl.F_SETFL, fcntl.fcntl(self.stdin_fd, fcntl.F_GETFL) | os.O_NONBLOCK)
  140. fcntl.fcntl(self.stdout_fd, fcntl.F_SETFL, fcntl.fcntl(self.stdout_fd, fcntl.F_GETFL) | os.O_NONBLOCK)
  141. fcntl.fcntl(self.stderr_fd, fcntl.F_SETFL, fcntl.fcntl(self.stderr_fd, fcntl.F_GETFL) | os.O_NONBLOCK)
  142. self.r_fds = [self.stdout_fd, self.stderr_fd]
  143. self.x_fds = [self.stdin_fd, self.stdout_fd, self.stderr_fd]
  144. try:
  145. version = self.call('negotiate', RPC_PROTOCOL_VERSION)
  146. except ConnectionClosed:
  147. raise ConnectionClosedWithHint('Is borg working on the server?') from None
  148. if version != RPC_PROTOCOL_VERSION:
  149. raise Exception('Server insisted on using unsupported protocol version %d' % version)
  150. try:
  151. self.id = self.call('open', self.location.path, create, lock_wait, lock)
  152. except Exception:
  153. self.close()
  154. raise
  155. def __del__(self):
  156. if self.p:
  157. self.close()
  158. assert False, "cleanup happened in Repository.__del__"
  159. def __repr__(self):
  160. return '<%s %s>' % (self.__class__.__name__, self.location.canonical_path())
  161. def __enter__(self):
  162. return self
  163. def __exit__(self, exc_type, exc_val, exc_tb):
  164. try:
  165. if exc_type is not None:
  166. self.rollback()
  167. finally:
  168. # in any case, we want to cleanly close the repo, even if the
  169. # rollback can not succeed (e.g. because the connection was
  170. # already closed) and raised another exception:
  171. self.close()
  172. def borg_cmd(self, args, testing):
  173. """return a borg serve command line"""
  174. # give some args/options to "borg serve" process as they were given to us
  175. opts = []
  176. if args is not None:
  177. opts.append('--umask=%03o' % args.umask)
  178. root_logger = logging.getLogger()
  179. if root_logger.isEnabledFor(logging.DEBUG):
  180. opts.append('--debug')
  181. elif root_logger.isEnabledFor(logging.INFO):
  182. opts.append('--info')
  183. elif root_logger.isEnabledFor(logging.WARNING):
  184. pass # warning is default
  185. elif root_logger.isEnabledFor(logging.ERROR):
  186. opts.append('--error')
  187. elif root_logger.isEnabledFor(logging.CRITICAL):
  188. opts.append('--critical')
  189. else:
  190. raise ValueError('log level missing, fix this code')
  191. if testing:
  192. return [sys.executable, '-m', 'borg.archiver', 'serve'] + opts + self.extra_test_args
  193. else: # pragma: no cover
  194. remote_path = args.remote_path or os.environ.get('BORG_REMOTE_PATH', 'borg')
  195. return [remote_path, 'serve'] + opts
  196. def ssh_cmd(self, location):
  197. """return a ssh command line that can be prefixed to a borg command line"""
  198. args = shlex.split(os.environ.get('BORG_RSH', 'ssh'))
  199. if location.port:
  200. args += ['-p', str(location.port)]
  201. if location.user:
  202. args.append('%s@%s' % (location.user, location.host))
  203. else:
  204. args.append('%s' % location.host)
  205. return args
  206. def call(self, cmd, *args, **kw):
  207. for resp in self.call_many(cmd, [args], **kw):
  208. return resp
  209. def call_many(self, cmd, calls, wait=True, is_preloaded=False):
  210. if not calls:
  211. return
  212. def fetch_from_cache(args):
  213. msgid = self.cache[args].pop(0)
  214. if not self.cache[args]:
  215. del self.cache[args]
  216. return msgid
  217. def handle_error(error, res):
  218. if error == b'DoesNotExist':
  219. raise Repository.DoesNotExist(self.location.orig)
  220. elif error == b'AlreadyExists':
  221. raise Repository.AlreadyExists(self.location.orig)
  222. elif error == b'CheckNeeded':
  223. raise Repository.CheckNeeded(self.location.orig)
  224. elif error == b'IntegrityError':
  225. raise IntegrityError(res)
  226. elif error == b'PathNotAllowed':
  227. raise PathNotAllowed(*res)
  228. elif error == b'ObjectNotFound':
  229. raise Repository.ObjectNotFound(res[0], self.location.orig)
  230. elif error == b'InvalidRPCMethod':
  231. raise InvalidRPCMethod(*res)
  232. else:
  233. raise self.RPCError(res.decode('utf-8'))
  234. calls = list(calls)
  235. waiting_for = []
  236. w_fds = [self.stdin_fd]
  237. while wait or calls:
  238. while waiting_for:
  239. try:
  240. error, res = self.responses.pop(waiting_for[0])
  241. waiting_for.pop(0)
  242. if error:
  243. handle_error(error, res)
  244. else:
  245. yield res
  246. if not waiting_for and not calls:
  247. return
  248. except KeyError:
  249. break
  250. r, w, x = select.select(self.r_fds, w_fds, self.x_fds, 1)
  251. if x:
  252. raise Exception('FD exception occurred')
  253. for fd in r:
  254. if fd is self.stdout_fd:
  255. data = os.read(fd, BUFSIZE)
  256. if not data:
  257. raise ConnectionClosed()
  258. self.unpacker.feed(data)
  259. for unpacked in self.unpacker:
  260. if not (isinstance(unpacked, tuple) and len(unpacked) == 4):
  261. raise Exception("Unexpected RPC data format.")
  262. type, msgid, error, res = unpacked
  263. if msgid in self.ignore_responses:
  264. self.ignore_responses.remove(msgid)
  265. if error:
  266. handle_error(error, res)
  267. else:
  268. self.responses[msgid] = error, res
  269. elif fd is self.stderr_fd:
  270. data = os.read(fd, 32768)
  271. if not data:
  272. raise ConnectionClosed()
  273. data = data.decode('utf-8')
  274. for line in data.splitlines(keepends=True):
  275. if line.startswith('$LOG '):
  276. _, level, msg = line.split(' ', 2)
  277. level = getattr(logging, level, logging.CRITICAL) # str -> int
  278. logging.log(level, msg.rstrip())
  279. else:
  280. sys.stderr.write("Remote: " + line)
  281. if w:
  282. while not self.to_send and (calls or self.preload_ids) and len(waiting_for) < 100:
  283. if calls:
  284. if is_preloaded:
  285. if calls[0] in self.cache:
  286. waiting_for.append(fetch_from_cache(calls.pop(0)))
  287. else:
  288. args = calls.pop(0)
  289. if cmd == 'get' and args in self.cache:
  290. waiting_for.append(fetch_from_cache(args))
  291. else:
  292. self.msgid += 1
  293. waiting_for.append(self.msgid)
  294. self.to_send = msgpack.packb((1, self.msgid, cmd, args))
  295. if not self.to_send and self.preload_ids:
  296. args = (self.preload_ids.pop(0),)
  297. self.msgid += 1
  298. self.cache.setdefault(args, []).append(self.msgid)
  299. self.to_send = msgpack.packb((1, self.msgid, cmd, args))
  300. if self.to_send:
  301. try:
  302. self.to_send = self.to_send[os.write(self.stdin_fd, self.to_send):]
  303. except OSError as e:
  304. # io.write might raise EAGAIN even though select indicates
  305. # that the fd should be writable
  306. if e.errno != errno.EAGAIN:
  307. raise
  308. if not self.to_send and not (calls or self.preload_ids):
  309. w_fds = []
  310. self.ignore_responses |= set(waiting_for)
  311. def check(self, repair=False, save_space=False):
  312. return self.call('check', repair, save_space)
  313. def commit(self, save_space=False):
  314. return self.call('commit', save_space)
  315. def rollback(self, *args):
  316. return self.call('rollback')
  317. def destroy(self):
  318. return self.call('destroy')
  319. def __len__(self):
  320. return self.call('__len__')
  321. def list(self, limit=None, marker=None):
  322. return self.call('list', limit, marker)
  323. def get(self, id_):
  324. for resp in self.get_many([id_]):
  325. return resp
  326. def get_many(self, ids, is_preloaded=False):
  327. for resp in self.call_many('get', [(id_,) for id_ in ids], is_preloaded=is_preloaded):
  328. yield resp
  329. def put(self, id_, data, wait=True):
  330. return self.call('put', id_, data, wait=wait)
  331. def delete(self, id_, wait=True):
  332. return self.call('delete', id_, wait=wait)
  333. def save_key(self, keydata):
  334. return self.call('save_key', keydata)
  335. def load_key(self):
  336. return self.call('load_key')
  337. def break_lock(self):
  338. return self.call('break_lock')
  339. def close(self):
  340. if self.p:
  341. self.p.stdin.close()
  342. self.p.stdout.close()
  343. self.p.wait()
  344. self.p = None
  345. def preload(self, ids):
  346. self.preload_ids += ids
  347. class RepositoryNoCache:
  348. """A not caching Repository wrapper, passes through to repository.
  349. Just to have same API (including the context manager) as RepositoryCache.
  350. """
  351. def __init__(self, repository):
  352. self.repository = repository
  353. def close(self):
  354. pass
  355. def __enter__(self):
  356. return self
  357. def __exit__(self, exc_type, exc_val, exc_tb):
  358. self.close()
  359. def get(self, key):
  360. return next(self.get_many([key]))
  361. def get_many(self, keys):
  362. for data in self.repository.get_many(keys):
  363. yield data
  364. class RepositoryCache(RepositoryNoCache):
  365. """A caching Repository wrapper
  366. Caches Repository GET operations using a local temporary Repository.
  367. """
  368. # maximum object size that will be cached, 64 kiB.
  369. THRESHOLD = 2**16
  370. def __init__(self, repository):
  371. super().__init__(repository)
  372. tmppath = tempfile.mkdtemp(prefix='borg-tmp')
  373. self.caching_repo = Repository(tmppath, create=True, exclusive=True)
  374. self.caching_repo.__enter__() # handled by context manager in base class
  375. def close(self):
  376. if self.caching_repo is not None:
  377. self.caching_repo.destroy()
  378. self.caching_repo = None
  379. def get_many(self, keys):
  380. unknown_keys = [key for key in keys if key not in self.caching_repo]
  381. repository_iterator = zip(unknown_keys, self.repository.get_many(unknown_keys))
  382. for key in keys:
  383. try:
  384. yield self.caching_repo.get(key)
  385. except Repository.ObjectNotFound:
  386. for key_, data in repository_iterator:
  387. if key_ == key:
  388. if len(data) <= self.THRESHOLD:
  389. self.caching_repo.put(key, data)
  390. yield data
  391. break
  392. # Consume any pending requests
  393. for _ in repository_iterator:
  394. pass
  395. def cache_if_remote(repository):
  396. if isinstance(repository, RemoteRepository):
  397. return RepositoryCache(repository)
  398. else:
  399. return RepositoryNoCache(repository)