2
0

upgrader.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. import datetime
  2. import os
  3. import shutil
  4. import time
  5. from .logger import create_logger
  6. logger = create_logger()
  7. from .helpers import get_keys_dir, get_cache_dir, ProgressIndicatorPercent, bin_to_hex
  8. from .locking import Lock
  9. from .repository import Repository, MAGIC
  10. from .key import KeyfileKey, KeyfileNotFoundError
  11. ATTIC_MAGIC = b'ATTICSEG'
  12. class AtticRepositoryUpgrader(Repository):
  13. def __init__(self, *args, **kw):
  14. kw['lock'] = False # do not create borg lock files (now) in attic repo
  15. super().__init__(*args, **kw)
  16. def upgrade(self, dryrun=True, inplace=False, progress=False):
  17. """convert an attic repository to a borg repository
  18. those are the files that need to be upgraded here, from most
  19. important to least important: segments, key files, and various
  20. caches, the latter being optional, as they will be rebuilt if
  21. missing.
  22. we nevertheless do the order in reverse, as we prefer to do
  23. the fast stuff first, to improve interactivity.
  24. """
  25. with self:
  26. backup = None
  27. if not inplace:
  28. backup = '{}.upgrade-{:%Y-%m-%d-%H:%M:%S}'.format(self.path, datetime.datetime.now())
  29. logger.info('making a hardlink copy in %s', backup)
  30. if not dryrun:
  31. shutil.copytree(self.path, backup, copy_function=os.link)
  32. logger.info("opening attic repository with borg and converting")
  33. # now lock the repo, after we have made the copy
  34. self.lock = Lock(os.path.join(self.path, 'lock'), exclusive=True, timeout=1.0).acquire()
  35. segments = [filename for i, filename in self.io.segment_iterator()]
  36. try:
  37. keyfile = self.find_attic_keyfile()
  38. except KeyfileNotFoundError:
  39. logger.warning("no key file found for repository")
  40. else:
  41. self.convert_keyfiles(keyfile, dryrun)
  42. # partial open: just hold on to the lock
  43. self.lock = Lock(os.path.join(self.path, 'lock'), exclusive=True).acquire()
  44. try:
  45. self.convert_cache(dryrun)
  46. self.convert_repo_index(dryrun=dryrun, inplace=inplace)
  47. self.convert_segments(segments, dryrun=dryrun, inplace=inplace, progress=progress)
  48. self.borg_readme()
  49. finally:
  50. self.lock.release()
  51. self.lock = None
  52. return backup
  53. def borg_readme(self):
  54. readme = os.path.join(self.path, 'README')
  55. os.remove(readme)
  56. with open(readme, 'w') as fd:
  57. fd.write('This is a Borg repository\n')
  58. @staticmethod
  59. def convert_segments(segments, dryrun=True, inplace=False, progress=False):
  60. """convert repository segments from attic to borg
  61. replacement pattern is `s/ATTICSEG/BORG_SEG/` in files in
  62. `$ATTIC_REPO/data/**`.
  63. luckily the magic string length didn't change so we can just
  64. replace the 8 first bytes of all regular files in there."""
  65. logger.info("converting %d segments..." % len(segments))
  66. segment_count = len(segments)
  67. pi = ProgressIndicatorPercent(total=segment_count, msg="Converting segments %3.0f%%", same_line=True)
  68. for i, filename in enumerate(segments):
  69. if progress:
  70. pi.show(i)
  71. if dryrun:
  72. time.sleep(0.001)
  73. else:
  74. AtticRepositoryUpgrader.header_replace(filename, ATTIC_MAGIC, MAGIC, inplace=inplace)
  75. if progress:
  76. pi.finish()
  77. @staticmethod
  78. def header_replace(filename, old_magic, new_magic, inplace=True):
  79. with open(filename, 'r+b') as segment:
  80. segment.seek(0)
  81. # only write if necessary
  82. if segment.read(len(old_magic)) == old_magic:
  83. if inplace:
  84. segment.seek(0)
  85. segment.write(new_magic)
  86. else:
  87. # rename the hardlink and rewrite the file. this works
  88. # because the file is still open. so even though the file
  89. # is renamed, we can still read it until it is closed.
  90. os.rename(filename, filename + '.tmp')
  91. with open(filename, 'wb') as new_segment:
  92. new_segment.write(new_magic)
  93. new_segment.write(segment.read())
  94. # the little dance with the .tmp file is necessary
  95. # because Windows won't allow overwriting an open file.
  96. os.unlink(filename + '.tmp')
  97. def find_attic_keyfile(self):
  98. """find the attic keyfiles
  99. the keyfiles are loaded by `KeyfileKey.find_key_file()`. that
  100. finds the keys with the right identifier for the repo.
  101. this is expected to look into $HOME/.attic/keys or
  102. $ATTIC_KEYS_DIR for key files matching the given Borg
  103. repository.
  104. it is expected to raise an exception (KeyfileNotFoundError) if
  105. no key is found. whether that exception is from Borg or Attic
  106. is unclear.
  107. this is split in a separate function in case we want to use
  108. the attic code here directly, instead of our local
  109. implementation."""
  110. return AtticKeyfileKey.find_key_file(self)
  111. @staticmethod
  112. def convert_keyfiles(keyfile, dryrun):
  113. """convert key files from attic to borg
  114. replacement pattern is `s/ATTIC KEY/BORG_KEY/` in
  115. `get_keys_dir()`, that is `$ATTIC_KEYS_DIR` or
  116. `$HOME/.attic/keys`, and moved to `$BORG_KEYS_DIR` or
  117. `$HOME/.config/borg/keys`.
  118. no need to decrypt to convert. we need to rewrite the whole
  119. key file because magic string length changed, but that's not a
  120. problem because the keyfiles are small (compared to, say,
  121. all the segments)."""
  122. logger.info("converting keyfile %s" % keyfile)
  123. with open(keyfile, 'r') as f:
  124. data = f.read()
  125. data = data.replace(AtticKeyfileKey.FILE_ID, KeyfileKey.FILE_ID, 1)
  126. keyfile = os.path.join(get_keys_dir(), os.path.basename(keyfile))
  127. logger.info("writing borg keyfile to %s" % keyfile)
  128. if not dryrun:
  129. with open(keyfile, 'w') as f:
  130. f.write(data)
  131. def convert_repo_index(self, dryrun, inplace):
  132. """convert some repo files
  133. those are all hash indexes, so we need to
  134. `s/ATTICIDX/BORG_IDX/` in a few locations:
  135. * the repository index (in `$ATTIC_REPO/index.%d`, where `%d`
  136. is the `Repository.get_index_transaction_id()`), which we
  137. should probably update, with a lock, see
  138. `Repository.open()`, which i'm not sure we should use
  139. because it may write data on `Repository.close()`...
  140. """
  141. transaction_id = self.get_index_transaction_id()
  142. if transaction_id is None:
  143. logger.warning('no index file found for repository %s' % self.path)
  144. else:
  145. index = os.path.join(self.path, 'index.%d' % transaction_id)
  146. logger.info("converting repo index %s" % index)
  147. if not dryrun:
  148. AtticRepositoryUpgrader.header_replace(index, b'ATTICIDX', b'BORG_IDX', inplace=inplace)
  149. def convert_cache(self, dryrun):
  150. """convert caches from attic to borg
  151. those are all hash indexes, so we need to
  152. `s/ATTICIDX/BORG_IDX/` in a few locations:
  153. * the `files` and `chunks` cache (in `$ATTIC_CACHE_DIR` or
  154. `$HOME/.cache/attic/<repoid>/`), which we could just drop,
  155. but if we'd want to convert, we could open it with the
  156. `Cache.open()`, edit in place and then `Cache.close()` to
  157. make sure we have locking right
  158. """
  159. # copy of attic's get_cache_dir()
  160. attic_cache_dir = os.environ.get('ATTIC_CACHE_DIR',
  161. os.path.join(os.path.expanduser('~'),
  162. '.cache', 'attic'))
  163. attic_cache_dir = os.path.join(attic_cache_dir, bin_to_hex(self.id))
  164. borg_cache_dir = os.path.join(get_cache_dir(), bin_to_hex(self.id))
  165. def copy_cache_file(path):
  166. """copy the given attic cache path into the borg directory
  167. does nothing if dryrun is True. also expects
  168. attic_cache_dir and borg_cache_dir to be set in the parent
  169. scope, to the directories path including the repository
  170. identifier.
  171. :params path: the basename of the cache file to copy
  172. (example: "files" or "chunks") as a string
  173. :returns: the borg file that was created or None if no
  174. Attic cache file was found.
  175. """
  176. attic_file = os.path.join(attic_cache_dir, path)
  177. if os.path.exists(attic_file):
  178. borg_file = os.path.join(borg_cache_dir, path)
  179. if os.path.exists(borg_file):
  180. logger.warning("borg cache file already exists in %s, not copying from Attic", borg_file)
  181. else:
  182. logger.info("copying attic cache file from %s to %s" % (attic_file, borg_file))
  183. if not dryrun:
  184. shutil.copyfile(attic_file, borg_file)
  185. return borg_file
  186. else:
  187. logger.warning("no %s cache file found in %s" % (path, attic_file))
  188. return None
  189. # XXX: untested, because generating cache files is a PITA, see
  190. # Archiver.do_create() for proof
  191. if os.path.exists(attic_cache_dir):
  192. if not os.path.exists(borg_cache_dir):
  193. os.makedirs(borg_cache_dir)
  194. # file that we don't have a header to convert, just copy
  195. for cache in ['config', 'files']:
  196. copy_cache_file(cache)
  197. # we need to convert the headers of those files, copy first
  198. for cache in ['chunks']:
  199. cache = copy_cache_file(cache)
  200. logger.info("converting cache %s" % cache)
  201. if not dryrun:
  202. AtticRepositoryUpgrader.header_replace(cache, b'ATTICIDX', b'BORG_IDX')
  203. class AtticKeyfileKey(KeyfileKey):
  204. """backwards compatible Attic key file parser"""
  205. FILE_ID = 'ATTIC KEY'
  206. # verbatim copy from attic
  207. @staticmethod
  208. def get_keys_dir():
  209. """Determine where to repository keys and cache"""
  210. return os.environ.get('ATTIC_KEYS_DIR',
  211. os.path.join(os.path.expanduser('~'), '.attic', 'keys'))
  212. @classmethod
  213. def find_key_file(cls, repository):
  214. """copy of attic's `find_key_file`_
  215. this has two small modifications:
  216. 1. it uses the above `get_keys_dir`_ instead of the global one,
  217. assumed to be borg's
  218. 2. it uses `repository.path`_ instead of
  219. `repository._location.canonical_path`_ because we can't
  220. assume the repository has been opened by the archiver yet
  221. """
  222. get_keys_dir = cls.get_keys_dir
  223. id = bin_to_hex(repository.id)
  224. keys_dir = get_keys_dir()
  225. if not os.path.exists(keys_dir):
  226. raise KeyfileNotFoundError(repository.path, keys_dir)
  227. for name in os.listdir(keys_dir):
  228. filename = os.path.join(keys_dir, name)
  229. with open(filename, 'r') as fd:
  230. line = fd.readline().strip()
  231. if line and line.startswith(cls.FILE_ID) and line[10:] == id:
  232. return filename
  233. raise KeyfileNotFoundError(repository.path, keys_dir)
  234. class BorgRepositoryUpgrader(Repository):
  235. def upgrade(self, dryrun=True, inplace=False, progress=False):
  236. """convert an old borg repository to a current borg repository
  237. """
  238. logger.info("converting borg 0.xx to borg current")
  239. with self:
  240. try:
  241. keyfile = self.find_borg0xx_keyfile()
  242. except KeyfileNotFoundError:
  243. logger.warning("no key file found for repository")
  244. else:
  245. self.move_keyfiles(keyfile, dryrun)
  246. def find_borg0xx_keyfile(self):
  247. return Borg0xxKeyfileKey.find_key_file(self)
  248. def move_keyfiles(self, keyfile, dryrun):
  249. filename = os.path.basename(keyfile)
  250. new_keyfile = os.path.join(get_keys_dir(), filename)
  251. try:
  252. os.rename(keyfile, new_keyfile)
  253. except FileExistsError:
  254. # likely the attic -> borg upgrader already put it in the final location
  255. pass
  256. class Borg0xxKeyfileKey(KeyfileKey):
  257. """backwards compatible borg 0.xx key file parser"""
  258. @staticmethod
  259. def get_keys_dir():
  260. return os.environ.get('BORG_KEYS_DIR',
  261. os.path.join(os.path.expanduser('~'), '.borg', 'keys'))
  262. @classmethod
  263. def find_key_file(cls, repository):
  264. get_keys_dir = cls.get_keys_dir
  265. id = bin_to_hex(repository.id)
  266. keys_dir = get_keys_dir()
  267. if not os.path.exists(keys_dir):
  268. raise KeyfileNotFoundError(repository.path, keys_dir)
  269. for name in os.listdir(keys_dir):
  270. filename = os.path.join(keys_dir, name)
  271. with open(filename, 'r') as fd:
  272. line = fd.readline().strip()
  273. if line and line.startswith(cls.FILE_ID) and line[len(cls.FILE_ID) + 1:] == id:
  274. return filename
  275. raise KeyfileNotFoundError(repository.path, keys_dir)