remote.py 15 KB

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