upgrader.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. import datetime
  2. import logging
  3. logger = logging.getLogger(__name__)
  4. import os
  5. import shutil
  6. import time
  7. from .helpers import get_home_dir, get_keys_dir, get_cache_dir, ProgressIndicatorPercent
  8. from .locking import UpgradableLock
  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 = UpgradableLock(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 = UpgradableLock(os.path.join(self.path, 'lock'),
  44. exclusive=True).acquire()
  45. try:
  46. self.convert_cache(dryrun)
  47. self.convert_repo_index(dryrun=dryrun, inplace=inplace)
  48. self.convert_segments(segments, dryrun=dryrun, inplace=inplace, progress=progress)
  49. self.borg_readme()
  50. finally:
  51. self.lock.release()
  52. self.lock = None
  53. return backup
  54. def borg_readme(self):
  55. readme = os.path.join(self.path, 'README')
  56. os.remove(readme)
  57. with open(readme, 'w') as fd:
  58. fd.write('This is a Borg repository\n')
  59. @staticmethod
  60. def convert_segments(segments, dryrun=True, inplace=False, progress=False):
  61. """convert repository segments from attic to borg
  62. replacement pattern is `s/ATTICSEG/BORG_SEG/` in files in
  63. `$ATTIC_REPO/data/**`.
  64. luckily the magic string length didn't change so we can just
  65. replace the 8 first bytes of all regular files in there."""
  66. logger.info("converting %d segments..." % len(segments))
  67. segment_count = len(segments)
  68. pi = ProgressIndicatorPercent(total=segment_count, msg="Converting segments %3.0f%%", same_line=True)
  69. for i, filename in enumerate(segments):
  70. if progress:
  71. pi.show(i)
  72. if dryrun:
  73. time.sleep(0.001)
  74. else:
  75. AtticRepositoryUpgrader.header_replace(filename, ATTIC_MAGIC, MAGIC, inplace=inplace)
  76. if progress:
  77. pi.finish()
  78. @staticmethod
  79. def header_replace(filename, old_magic, new_magic, inplace=True):
  80. with open(filename, 'r+b') as segment:
  81. segment.seek(0)
  82. # only write if necessary
  83. if segment.read(len(old_magic)) == old_magic:
  84. if inplace:
  85. segment.seek(0)
  86. segment.write(new_magic)
  87. else:
  88. # rename the hardlink and rewrite the file. this works
  89. # because the file is still open. so even though the file
  90. # is renamed, we can still read it until it is closed.
  91. os.rename(filename, filename + '.tmp')
  92. with open(filename, 'wb') as new_segment:
  93. new_segment.write(new_magic)
  94. new_segment.write(segment.read())
  95. # the little dance with the .tmp file is necessary
  96. # because Windows won't allow overwriting an open file.
  97. os.unlink(filename + '.tmp')
  98. def find_attic_keyfile(self):
  99. """find the attic keyfiles
  100. the keyfiles are loaded by `KeyfileKey.find_key_file()`. that
  101. finds the keys with the right identifier for the repo.
  102. this is expected to look into $HOME/.attic/keys or
  103. $ATTIC_KEYS_DIR for key files matching the given Borg
  104. repository.
  105. it is expected to raise an exception (KeyfileNotFoundError) if
  106. no key is found. whether that exception is from Borg or Attic
  107. is unclear.
  108. this is split in a separate function in case we want to use
  109. the attic code here directly, instead of our local
  110. implementation."""
  111. return AtticKeyfileKey.find_key_file(self)
  112. @staticmethod
  113. def convert_keyfiles(keyfile, dryrun):
  114. """convert key files from attic to borg
  115. replacement pattern is `s/ATTIC KEY/BORG_KEY/` in
  116. `get_keys_dir()`, that is `$ATTIC_KEYS_DIR` or
  117. `$HOME/.attic/keys`, and moved to `$BORG_KEYS_DIR` or
  118. `$HOME/.config/borg/keys`.
  119. no need to decrypt to convert. we need to rewrite the whole
  120. key file because magic string length changed, but that's not a
  121. problem because the keyfiles are small (compared to, say,
  122. all the segments)."""
  123. logger.info("converting keyfile %s" % keyfile)
  124. with open(keyfile, 'r') as f:
  125. data = f.read()
  126. data = data.replace(AtticKeyfileKey.FILE_ID, KeyfileKey.FILE_ID, 1)
  127. keyfile = os.path.join(get_keys_dir(), os.path.basename(keyfile))
  128. logger.info("writing borg keyfile to %s" % keyfile)
  129. if not dryrun:
  130. with open(keyfile, 'w') as f:
  131. f.write(data)
  132. def convert_repo_index(self, dryrun, inplace):
  133. """convert some repo files
  134. those are all hash indexes, so we need to
  135. `s/ATTICIDX/BORG_IDX/` in a few locations:
  136. * the repository index (in `$ATTIC_REPO/index.%d`, where `%d`
  137. is the `Repository.get_index_transaction_id()`), which we
  138. should probably update, with a lock, see
  139. `Repository.open()`, which i'm not sure we should use
  140. because it may write data on `Repository.close()`...
  141. """
  142. transaction_id = self.get_index_transaction_id()
  143. if transaction_id is None:
  144. logger.warning('no index file found for repository %s' % self.path)
  145. else:
  146. index = os.path.join(self.path, 'index.%d' % transaction_id)
  147. logger.info("converting repo index %s" % index)
  148. if not dryrun:
  149. AtticRepositoryUpgrader.header_replace(index, b'ATTICIDX', b'BORG_IDX', inplace=inplace)
  150. def convert_cache(self, dryrun):
  151. """convert caches from attic to borg
  152. those are all hash indexes, so we need to
  153. `s/ATTICIDX/BORG_IDX/` in a few locations:
  154. * the `files` and `chunks` cache (in `$ATTIC_CACHE_DIR` or
  155. `$HOME/.cache/attic/<repoid>/`), which we could just drop,
  156. but if we'd want to convert, we could open it with the
  157. `Cache.open()`, edit in place and then `Cache.close()` to
  158. make sure we have locking right
  159. """
  160. # copy of attic's get_cache_dir()
  161. attic_cache_dir = os.environ.get('ATTIC_CACHE_DIR',
  162. os.path.join(get_home_dir(),
  163. '.cache', 'attic'))
  164. attic_cache_dir = os.path.join(attic_cache_dir, self.id_str)
  165. borg_cache_dir = os.path.join(get_cache_dir(), self.id_str)
  166. def copy_cache_file(path):
  167. """copy the given attic cache path into the borg directory
  168. does nothing if dryrun is True. also expects
  169. attic_cache_dir and borg_cache_dir to be set in the parent
  170. scope, to the directories path including the repository
  171. identifier.
  172. :params path: the basename of the cache file to copy
  173. (example: "files" or "chunks") as a string
  174. :returns: the borg file that was created or None if no
  175. Attic cache file was found.
  176. """
  177. attic_file = os.path.join(attic_cache_dir, path)
  178. if os.path.exists(attic_file):
  179. borg_file = os.path.join(borg_cache_dir, path)
  180. if os.path.exists(borg_file):
  181. logger.warning("borg cache file already exists in %s, not copying from Attic", borg_file)
  182. else:
  183. logger.info("copying attic cache file from %s to %s" % (attic_file, borg_file))
  184. if not dryrun:
  185. shutil.copyfile(attic_file, borg_file)
  186. return borg_file
  187. else:
  188. logger.warning("no %s cache file found in %s" % (path, attic_file))
  189. return None
  190. # XXX: untested, because generating cache files is a PITA, see
  191. # Archiver.do_create() for proof
  192. if os.path.exists(attic_cache_dir):
  193. if not os.path.exists(borg_cache_dir):
  194. os.makedirs(borg_cache_dir)
  195. # file that we don't have a header to convert, just copy
  196. for cache in ['config', 'files']:
  197. copy_cache_file(cache)
  198. # we need to convert the headers of those files, copy first
  199. for cache in ['chunks']:
  200. cache = copy_cache_file(cache)
  201. logger.info("converting cache %s" % cache)
  202. if not dryrun:
  203. AtticRepositoryUpgrader.header_replace(cache, b'ATTICIDX', b'BORG_IDX')
  204. class AtticKeyfileKey(KeyfileKey):
  205. """backwards compatible Attic key file parser"""
  206. FILE_ID = 'ATTIC KEY'
  207. # verbatim copy from attic
  208. @staticmethod
  209. def get_keys_dir():
  210. """Determine where to repository keys and cache"""
  211. return os.environ.get('ATTIC_KEYS_DIR',
  212. os.path.join(get_home_dir(), '.attic', 'keys'))
  213. @classmethod
  214. def find_key_file(cls, repository):
  215. """copy of attic's `find_key_file`_
  216. this has two small modifications:
  217. 1. it uses the above `get_keys_dir`_ instead of the global one,
  218. assumed to be borg's
  219. 2. it uses `repository.path`_ instead of
  220. `repository._location.canonical_path`_ because we can't
  221. assume the repository has been opened by the archiver yet
  222. """
  223. get_keys_dir = cls.get_keys_dir
  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:] == repository.id_str:
  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(get_home_dir(), '.borg', 'keys'))
  262. @classmethod
  263. def find_key_file(cls, repository):
  264. get_keys_dir = cls.get_keys_dir
  265. keys_dir = get_keys_dir()
  266. if not os.path.exists(keys_dir):
  267. raise KeyfileNotFoundError(repository.path, keys_dir)
  268. for name in os.listdir(keys_dir):
  269. filename = os.path.join(keys_dir, name)
  270. with open(filename, 'r') as fd:
  271. line = fd.readline().strip()
  272. if line and line.startswith(cls.FILE_ID) and line[len(cls.FILE_ID) + 1:] == repository.id_str:
  273. return filename
  274. raise KeyfileNotFoundError(repository.path, keys_dir)