helpers.py 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243
  1. import argparse
  2. from binascii import hexlify
  3. from collections import namedtuple
  4. import contextlib
  5. from functools import wraps
  6. import grp
  7. import os
  8. import stat
  9. import textwrap
  10. import pwd
  11. import re
  12. from shutil import get_terminal_size
  13. import sys
  14. import platform
  15. import signal
  16. import threading
  17. import time
  18. import unicodedata
  19. import io
  20. import errno
  21. import logging
  22. from .logger import create_logger
  23. logger = create_logger()
  24. from datetime import datetime, timezone, timedelta
  25. from fnmatch import translate
  26. from operator import attrgetter
  27. from . import __version__ as borg_version
  28. from . import hashindex
  29. from . import chunker
  30. from . import crypto
  31. from . import shellpattern
  32. import msgpack
  33. import msgpack.fallback
  34. import socket
  35. # return codes returned by borg command
  36. # when borg is killed by signal N, rc = 128 + N
  37. EXIT_SUCCESS = 0 # everything done, no problems
  38. EXIT_WARNING = 1 # reached normal end of operation, but there were issues
  39. EXIT_ERROR = 2 # terminated abruptly, did not reach end of operation
  40. class Error(Exception):
  41. """Error base class"""
  42. # if we raise such an Error and it is only catched by the uppermost
  43. # exception handler (that exits short after with the given exit_code),
  44. # it is always a (fatal and abrupt) EXIT_ERROR, never just a warning.
  45. exit_code = EXIT_ERROR
  46. # show a traceback?
  47. traceback = False
  48. def get_message(self):
  49. return type(self).__doc__.format(*self.args)
  50. class ErrorWithTraceback(Error):
  51. """like Error, but show a traceback also"""
  52. traceback = True
  53. class IntegrityError(ErrorWithTraceback):
  54. """Data integrity error: {}"""
  55. class ExtensionModuleError(Error):
  56. """The Borg binary extension modules do not seem to be properly installed"""
  57. class NoManifestError(Error):
  58. """Repository has no manifest."""
  59. class PlaceholderError(Error):
  60. """Formatting Error: "{}".format({}): {}({})"""
  61. def check_extension_modules():
  62. from . import platform
  63. if hashindex.API_VERSION != 3:
  64. raise ExtensionModuleError
  65. if chunker.API_VERSION != 2:
  66. raise ExtensionModuleError
  67. if crypto.API_VERSION != 2:
  68. raise ExtensionModuleError
  69. if platform.API_VERSION != 2:
  70. raise ExtensionModuleError
  71. class Manifest:
  72. MANIFEST_ID = b'\0' * 32
  73. def __init__(self, key, repository, item_keys=None):
  74. from .archive import ITEM_KEYS
  75. self.archives = {}
  76. self.config = {}
  77. self.key = key
  78. self.repository = repository
  79. self.item_keys = frozenset(item_keys) if item_keys is not None else ITEM_KEYS
  80. @classmethod
  81. def load(cls, repository, key=None):
  82. from .key import key_factory
  83. from .repository import Repository
  84. from .archive import ITEM_KEYS
  85. try:
  86. cdata = repository.get(cls.MANIFEST_ID)
  87. except Repository.ObjectNotFound:
  88. raise NoManifestError
  89. if not key:
  90. key = key_factory(repository, cdata)
  91. manifest = cls(key, repository)
  92. data = key.decrypt(None, cdata)
  93. manifest.id = key.id_hash(data)
  94. m = msgpack.unpackb(data)
  95. if not m.get(b'version') == 1:
  96. raise ValueError('Invalid manifest version')
  97. manifest.archives = dict((k.decode('utf-8'), v) for k, v in m[b'archives'].items())
  98. manifest.timestamp = m.get(b'timestamp')
  99. if manifest.timestamp:
  100. manifest.timestamp = manifest.timestamp.decode('ascii')
  101. manifest.config = m[b'config']
  102. # valid item keys are whatever is known in the repo or every key we know
  103. manifest.item_keys = frozenset(m.get(b'item_keys', [])) | ITEM_KEYS
  104. return manifest, key
  105. def write(self):
  106. self.timestamp = datetime.utcnow().isoformat()
  107. data = msgpack.packb(StableDict({
  108. 'version': 1,
  109. 'archives': self.archives,
  110. 'timestamp': self.timestamp,
  111. 'config': self.config,
  112. 'item_keys': tuple(self.item_keys),
  113. }))
  114. self.id = self.key.id_hash(data)
  115. self.repository.put(self.MANIFEST_ID, self.key.encrypt(data))
  116. def list_archive_infos(self, sort_by=None, reverse=False):
  117. # inexpensive Archive.list_archives replacement if we just need .name, .id, .ts
  118. ArchiveInfo = namedtuple('ArchiveInfo', 'name id ts')
  119. archives = []
  120. for name, values in self.archives.items():
  121. ts = parse_timestamp(values[b'time'].decode('utf-8'))
  122. id = values[b'id']
  123. archives.append(ArchiveInfo(name=name, id=id, ts=ts))
  124. if sort_by is not None:
  125. archives = sorted(archives, key=attrgetter(sort_by), reverse=reverse)
  126. return archives
  127. def prune_within(archives, within):
  128. multiplier = {'H': 1, 'd': 24, 'w': 24 * 7, 'm': 24 * 31, 'y': 24 * 365}
  129. try:
  130. hours = int(within[:-1]) * multiplier[within[-1]]
  131. except (KeyError, ValueError):
  132. # I don't like how this displays the original exception too:
  133. raise argparse.ArgumentTypeError('Unable to parse --within option: "%s"' % within)
  134. if hours <= 0:
  135. raise argparse.ArgumentTypeError('Number specified using --within option must be positive')
  136. target = datetime.now(timezone.utc) - timedelta(seconds=hours * 3600)
  137. return [a for a in archives if a.ts > target]
  138. def prune_split(archives, pattern, n, skip=[]):
  139. last = None
  140. keep = []
  141. if n == 0:
  142. return keep
  143. for a in sorted(archives, key=attrgetter('ts'), reverse=True):
  144. period = to_localtime(a.ts).strftime(pattern)
  145. if period != last:
  146. last = period
  147. if a not in skip:
  148. keep.append(a)
  149. if len(keep) == n:
  150. break
  151. return keep
  152. class Statistics:
  153. def __init__(self):
  154. self.osize = self.csize = self.usize = self.nfiles = 0
  155. self.last_progress = 0 # timestamp when last progress was shown
  156. def update(self, size, csize, unique):
  157. self.osize += size
  158. self.csize += csize
  159. if unique:
  160. self.usize += csize
  161. summary = """\
  162. Original size Compressed size Deduplicated size
  163. {label:15} {stats.osize_fmt:>20s} {stats.csize_fmt:>20s} {stats.usize_fmt:>20s}"""
  164. def __str__(self):
  165. return self.summary.format(stats=self, label='This archive:')
  166. def __repr__(self):
  167. return "<{cls} object at {hash:#x} ({self.osize}, {self.csize}, {self.usize})>".format(cls=type(self).__name__, hash=id(self), self=self)
  168. @property
  169. def osize_fmt(self):
  170. return format_file_size(self.osize)
  171. @property
  172. def usize_fmt(self):
  173. return format_file_size(self.usize)
  174. @property
  175. def csize_fmt(self):
  176. return format_file_size(self.csize)
  177. def show_progress(self, item=None, final=False, stream=None, dt=None):
  178. now = time.time()
  179. if dt is None or now - self.last_progress > dt:
  180. self.last_progress = now
  181. columns, lines = get_terminal_size()
  182. if not final:
  183. msg = '{0.osize_fmt} O {0.csize_fmt} C {0.usize_fmt} D {0.nfiles} N '.format(self)
  184. path = remove_surrogates(item[b'path']) if item else ''
  185. space = columns - len(msg)
  186. if space < 12:
  187. msg = ''
  188. space = columns - len(msg)
  189. if space >= 8:
  190. if space < len('...') + len(path):
  191. path = '%s...%s' % (path[:(space // 2) - len('...')], path[-space // 2:])
  192. msg += "{0:<{space}}".format(path, space=space)
  193. else:
  194. msg = ' ' * columns
  195. print(msg, file=stream or sys.stderr, end="\r", flush=True)
  196. def get_keys_dir():
  197. """Determine where to repository keys and cache"""
  198. xdg_config = os.environ.get('XDG_CONFIG_HOME', os.path.join(os.path.expanduser('~'), '.config'))
  199. keys_dir = os.environ.get('BORG_KEYS_DIR', os.path.join(xdg_config, 'borg', 'keys'))
  200. if not os.path.exists(keys_dir):
  201. os.makedirs(keys_dir)
  202. os.chmod(keys_dir, stat.S_IRWXU)
  203. return keys_dir
  204. def get_cache_dir():
  205. """Determine where to repository keys and cache"""
  206. xdg_cache = os.environ.get('XDG_CACHE_HOME', os.path.join(os.path.expanduser('~'), '.cache'))
  207. cache_dir = os.environ.get('BORG_CACHE_DIR', os.path.join(xdg_cache, 'borg'))
  208. if not os.path.exists(cache_dir):
  209. os.makedirs(cache_dir)
  210. os.chmod(cache_dir, stat.S_IRWXU)
  211. with open(os.path.join(cache_dir, 'CACHEDIR.TAG'), 'w') as fd:
  212. fd.write(textwrap.dedent("""
  213. Signature: 8a477f597d28d172789f06886806bc55
  214. # This file is a cache directory tag created by Borg.
  215. # For information about cache directory tags, see:
  216. # http://www.brynosaurus.com/cachedir/
  217. """).lstrip())
  218. return cache_dir
  219. def to_localtime(ts):
  220. """Convert datetime object from UTC to local time zone"""
  221. return datetime(*time.localtime((ts - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds())[:6])
  222. def parse_timestamp(timestamp):
  223. """Parse a ISO 8601 timestamp string"""
  224. if '.' in timestamp: # microseconds might not be present
  225. return datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S.%f').replace(tzinfo=timezone.utc)
  226. else:
  227. return datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc)
  228. def load_excludes(fh):
  229. """Load and parse exclude patterns from file object. Lines empty or starting with '#' after stripping whitespace on
  230. both line ends are ignored.
  231. """
  232. patterns = (line for line in (i.strip() for i in fh) if not line.startswith('#'))
  233. return [parse_pattern(pattern) for pattern in patterns if pattern]
  234. def update_excludes(args):
  235. """Merge exclude patterns from files with those on command line."""
  236. if hasattr(args, 'exclude_files') and args.exclude_files:
  237. if not hasattr(args, 'excludes') or args.excludes is None:
  238. args.excludes = []
  239. for file in args.exclude_files:
  240. args.excludes += load_excludes(file)
  241. file.close()
  242. class PatternMatcher:
  243. def __init__(self, fallback=None):
  244. self._items = []
  245. # Value to return from match function when none of the patterns match.
  246. self.fallback = fallback
  247. def add(self, patterns, value):
  248. """Add list of patterns to internal list. The given value is returned from the match function when one of the
  249. given patterns matches.
  250. """
  251. self._items.extend((i, value) for i in patterns)
  252. def match(self, path):
  253. for (pattern, value) in self._items:
  254. if pattern.match(path):
  255. return value
  256. return self.fallback
  257. def normalized(func):
  258. """ Decorator for the Pattern match methods, returning a wrapper that
  259. normalizes OSX paths to match the normalized pattern on OSX, and
  260. returning the original method on other platforms"""
  261. @wraps(func)
  262. def normalize_wrapper(self, path):
  263. return func(self, unicodedata.normalize("NFD", path))
  264. if sys.platform in ('darwin',):
  265. # HFS+ converts paths to a canonical form, so users shouldn't be
  266. # required to enter an exact match
  267. return normalize_wrapper
  268. else:
  269. # Windows and Unix filesystems allow different forms, so users
  270. # always have to enter an exact match
  271. return func
  272. class PatternBase:
  273. """Shared logic for inclusion/exclusion patterns.
  274. """
  275. PREFIX = NotImplemented
  276. def __init__(self, pattern):
  277. self.pattern_orig = pattern
  278. self.match_count = 0
  279. if sys.platform in ('darwin',):
  280. pattern = unicodedata.normalize("NFD", pattern)
  281. self._prepare(pattern)
  282. @normalized
  283. def match(self, path):
  284. matches = self._match(path)
  285. if matches:
  286. self.match_count += 1
  287. return matches
  288. def __repr__(self):
  289. return '%s(%s)' % (type(self), self.pattern)
  290. def __str__(self):
  291. return self.pattern_orig
  292. def _prepare(self, pattern):
  293. raise NotImplementedError
  294. def _match(self, path):
  295. raise NotImplementedError
  296. # For PathPrefixPattern, FnmatchPattern and ShellPattern, we require that the pattern either match the whole path
  297. # or an initial segment of the path up to but not including a path separator. To unify the two cases, we add a path
  298. # separator to the end of the path before matching.
  299. class PathPrefixPattern(PatternBase):
  300. """Literal files or directories listed on the command line
  301. for some operations (e.g. extract, but not create).
  302. If a directory is specified, all paths that start with that
  303. path match as well. A trailing slash makes no difference.
  304. """
  305. PREFIX = "pp"
  306. def _prepare(self, pattern):
  307. self.pattern = os.path.normpath(pattern).rstrip(os.path.sep) + os.path.sep
  308. def _match(self, path):
  309. return (path + os.path.sep).startswith(self.pattern)
  310. class FnmatchPattern(PatternBase):
  311. """Shell glob patterns to exclude. A trailing slash means to
  312. exclude the contents of a directory, but not the directory itself.
  313. """
  314. PREFIX = "fm"
  315. def _prepare(self, pattern):
  316. if pattern.endswith(os.path.sep):
  317. pattern = os.path.normpath(pattern).rstrip(os.path.sep) + os.path.sep + '*' + os.path.sep
  318. else:
  319. pattern = os.path.normpath(pattern) + os.path.sep + '*'
  320. self.pattern = pattern
  321. # fnmatch and re.match both cache compiled regular expressions.
  322. # Nevertheless, this is about 10 times faster.
  323. self.regex = re.compile(translate(self.pattern))
  324. def _match(self, path):
  325. return (self.regex.match(path + os.path.sep) is not None)
  326. class ShellPattern(PatternBase):
  327. """Shell glob patterns to exclude. A trailing slash means to
  328. exclude the contents of a directory, but not the directory itself.
  329. """
  330. PREFIX = "sh"
  331. def _prepare(self, pattern):
  332. sep = os.path.sep
  333. if pattern.endswith(sep):
  334. pattern = os.path.normpath(pattern).rstrip(sep) + sep + "**" + sep + "*" + sep
  335. else:
  336. pattern = os.path.normpath(pattern) + sep + "**" + sep + "*"
  337. self.pattern = pattern
  338. self.regex = re.compile(shellpattern.translate(self.pattern))
  339. def _match(self, path):
  340. return (self.regex.match(path + os.path.sep) is not None)
  341. class RegexPattern(PatternBase):
  342. """Regular expression to exclude.
  343. """
  344. PREFIX = "re"
  345. def _prepare(self, pattern):
  346. self.pattern = pattern
  347. self.regex = re.compile(pattern)
  348. def _match(self, path):
  349. # Normalize path separators
  350. if os.path.sep != '/':
  351. path = path.replace(os.path.sep, '/')
  352. return (self.regex.search(path) is not None)
  353. _PATTERN_STYLES = set([
  354. FnmatchPattern,
  355. PathPrefixPattern,
  356. RegexPattern,
  357. ShellPattern,
  358. ])
  359. _PATTERN_STYLE_BY_PREFIX = dict((i.PREFIX, i) for i in _PATTERN_STYLES)
  360. def parse_pattern(pattern, fallback=FnmatchPattern):
  361. """Read pattern from string and return an instance of the appropriate implementation class.
  362. """
  363. if len(pattern) > 2 and pattern[2] == ":" and pattern[:2].isalnum():
  364. (style, pattern) = (pattern[:2], pattern[3:])
  365. cls = _PATTERN_STYLE_BY_PREFIX.get(style, None)
  366. if cls is None:
  367. raise ValueError("Unknown pattern style: {}".format(style))
  368. else:
  369. cls = fallback
  370. return cls(pattern)
  371. def timestamp(s):
  372. """Convert a --timestamp=s argument to a datetime object"""
  373. try:
  374. # is it pointing to a file / directory?
  375. ts = os.stat(s).st_mtime
  376. return datetime.utcfromtimestamp(ts)
  377. except OSError:
  378. # didn't work, try parsing as timestamp. UTC, no TZ, no microsecs support.
  379. for format in ('%Y-%m-%dT%H:%M:%SZ', '%Y-%m-%dT%H:%M:%S+00:00',
  380. '%Y-%m-%dT%H:%M:%S', '%Y-%m-%d %H:%M:%S',
  381. '%Y-%m-%dT%H:%M', '%Y-%m-%d %H:%M',
  382. '%Y-%m-%d', '%Y-%j',
  383. ):
  384. try:
  385. return datetime.strptime(s, format)
  386. except ValueError:
  387. continue
  388. raise ValueError
  389. def ChunkerParams(s):
  390. chunk_min, chunk_max, chunk_mask, window_size = s.split(',')
  391. if int(chunk_max) > 23:
  392. raise ValueError('max. chunk size exponent must not be more than 23 (2^23 = 8MiB max. chunk size)')
  393. return int(chunk_min), int(chunk_max), int(chunk_mask), int(window_size)
  394. def CompressionSpec(s):
  395. values = s.split(',')
  396. count = len(values)
  397. if count < 1:
  398. raise ValueError
  399. # --compression algo[,level]
  400. name = values[0]
  401. if name in ('none', 'lz4', ):
  402. return dict(name=name)
  403. if name in ('zlib', 'lzma', ):
  404. if count < 2:
  405. level = 6 # default compression level in py stdlib
  406. elif count == 2:
  407. level = int(values[1])
  408. if not 0 <= level <= 9:
  409. raise ValueError
  410. else:
  411. raise ValueError
  412. return dict(name=name, level=level)
  413. raise ValueError
  414. def PrefixSpec(s):
  415. return replace_placeholders(s)
  416. def dir_is_cachedir(path):
  417. """Determines whether the specified path is a cache directory (and
  418. therefore should potentially be excluded from the backup) according to
  419. the CACHEDIR.TAG protocol
  420. (http://www.brynosaurus.com/cachedir/spec.html).
  421. """
  422. tag_contents = b'Signature: 8a477f597d28d172789f06886806bc55'
  423. tag_path = os.path.join(path, 'CACHEDIR.TAG')
  424. try:
  425. if os.path.exists(tag_path):
  426. with open(tag_path, 'rb') as tag_file:
  427. tag_data = tag_file.read(len(tag_contents))
  428. if tag_data == tag_contents:
  429. return True
  430. except OSError:
  431. pass
  432. return False
  433. def dir_is_tagged(path, exclude_caches, exclude_if_present):
  434. """Determines whether the specified path is excluded by being a cache
  435. directory or containing user-specified tag files. Returns a list of the
  436. paths of the tag files (either CACHEDIR.TAG or the matching
  437. user-specified files).
  438. """
  439. tag_paths = []
  440. if exclude_caches and dir_is_cachedir(path):
  441. tag_paths.append(os.path.join(path, 'CACHEDIR.TAG'))
  442. if exclude_if_present is not None:
  443. for tag in exclude_if_present:
  444. tag_path = os.path.join(path, tag)
  445. if os.path.isfile(tag_path):
  446. tag_paths.append(tag_path)
  447. return tag_paths
  448. def format_line(format, data):
  449. try:
  450. return format.format(**data)
  451. except Exception as e:
  452. raise PlaceholderError(format, data, e.__class__.__name__, str(e))
  453. def replace_placeholders(text):
  454. """Replace placeholders in text with their values."""
  455. current_time = datetime.now()
  456. data = {
  457. 'pid': os.getpid(),
  458. 'fqdn': socket.getfqdn(),
  459. 'hostname': socket.gethostname(),
  460. 'now': current_time.now(),
  461. 'utcnow': current_time.utcnow(),
  462. 'user': uid2user(os.getuid(), os.getuid()),
  463. 'borgversion': borg_version,
  464. }
  465. return format_line(text, data)
  466. def safe_timestamp(item_timestamp_ns):
  467. try:
  468. return datetime.fromtimestamp(bigint_to_int(item_timestamp_ns) / 1e9)
  469. except OverflowError:
  470. # likely a broken file time and datetime did not want to go beyond year 9999
  471. return datetime(9999, 12, 31, 23, 59, 59)
  472. def format_time(t):
  473. """use ISO-8601 date and time format
  474. """
  475. return t.strftime('%a, %Y-%m-%d %H:%M:%S')
  476. def format_timedelta(td):
  477. """Format timedelta in a human friendly format
  478. """
  479. # Since td.total_seconds() requires python 2.7
  480. ts = (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 ** 6) / float(10 ** 6)
  481. s = ts % 60
  482. m = int(ts / 60) % 60
  483. h = int(ts / 3600) % 24
  484. txt = '%.2f seconds' % s
  485. if m:
  486. txt = '%d minutes %s' % (m, txt)
  487. if h:
  488. txt = '%d hours %s' % (h, txt)
  489. if td.days:
  490. txt = '%d days %s' % (td.days, txt)
  491. return txt
  492. def format_file_size(v, precision=2):
  493. """Format file size into a human friendly format
  494. """
  495. return sizeof_fmt_decimal(v, suffix='B', sep=' ', precision=precision)
  496. def sizeof_fmt(num, suffix='B', units=None, power=None, sep='', precision=2):
  497. for unit in units[:-1]:
  498. if abs(round(num, precision)) < power:
  499. if isinstance(num, int):
  500. return "{}{}{}{}".format(num, sep, unit, suffix)
  501. else:
  502. return "{:3.{}f}{}{}{}".format(num, precision, sep, unit, suffix)
  503. num /= float(power)
  504. return "{:.{}f}{}{}{}".format(num, precision, sep, units[-1], suffix)
  505. def sizeof_fmt_iec(num, suffix='B', sep='', precision=2):
  506. return sizeof_fmt(num, suffix=suffix, sep=sep, precision=precision, units=['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi'], power=1024)
  507. def sizeof_fmt_decimal(num, suffix='B', sep='', precision=2):
  508. return sizeof_fmt(num, suffix=suffix, sep=sep, precision=precision, units=['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'], power=1000)
  509. def format_archive(archive):
  510. return '%-36s %s' % (archive.name, format_time(to_localtime(archive.ts)))
  511. def memoize(function):
  512. cache = {}
  513. def decorated_function(*args):
  514. try:
  515. return cache[args]
  516. except KeyError:
  517. val = function(*args)
  518. cache[args] = val
  519. return val
  520. return decorated_function
  521. class Buffer:
  522. """
  523. provide a thread-local buffer
  524. """
  525. def __init__(self, allocator, size=4096, limit=None):
  526. """
  527. Initialize the buffer: use allocator(size) call to allocate a buffer.
  528. Optionally, set the upper <limit> for the buffer size.
  529. """
  530. assert callable(allocator), 'must give alloc(size) function as first param'
  531. assert limit is None or size <= limit, 'initial size must be <= limit'
  532. self._thread_local = threading.local()
  533. self.allocator = allocator
  534. self.limit = limit
  535. self.resize(size, init=True)
  536. def __len__(self):
  537. return len(self._thread_local.buffer)
  538. def resize(self, size, init=False):
  539. """
  540. resize the buffer - to avoid frequent reallocation, we usually always grow (if needed).
  541. giving init=True it is possible to first-time initialize or shrink the buffer.
  542. if a buffer size beyond the limit is requested, raise ValueError.
  543. """
  544. size = int(size)
  545. if self.limit is not None and size > self.limit:
  546. raise ValueError('Requested buffer size %d is above the limit of %d.' % (size, self.limit))
  547. if init or len(self) < size:
  548. self._thread_local.buffer = self.allocator(size)
  549. def get(self, size=None, init=False):
  550. """
  551. return a buffer of at least the requested size (None: any current size).
  552. init=True can be given to trigger shrinking of the buffer to the given size.
  553. """
  554. if size is not None:
  555. self.resize(size, init)
  556. return self._thread_local.buffer
  557. @memoize
  558. def uid2user(uid, default=None):
  559. try:
  560. return pwd.getpwuid(uid).pw_name
  561. except KeyError:
  562. return default
  563. @memoize
  564. def user2uid(user, default=None):
  565. try:
  566. return user and pwd.getpwnam(user).pw_uid
  567. except KeyError:
  568. return default
  569. @memoize
  570. def gid2group(gid, default=None):
  571. try:
  572. return grp.getgrgid(gid).gr_name
  573. except KeyError:
  574. return default
  575. @memoize
  576. def group2gid(group, default=None):
  577. try:
  578. return group and grp.getgrnam(group).gr_gid
  579. except KeyError:
  580. return default
  581. def posix_acl_use_stored_uid_gid(acl):
  582. """Replace the user/group field with the stored uid/gid
  583. """
  584. entries = []
  585. for entry in safe_decode(acl).split('\n'):
  586. if entry:
  587. fields = entry.split(':')
  588. if len(fields) == 4:
  589. entries.append(':'.join([fields[0], fields[3], fields[2]]))
  590. else:
  591. entries.append(entry)
  592. return safe_encode('\n'.join(entries))
  593. def safe_decode(s, coding='utf-8', errors='surrogateescape'):
  594. """decode bytes to str, with round-tripping "invalid" bytes"""
  595. return s.decode(coding, errors)
  596. def safe_encode(s, coding='utf-8', errors='surrogateescape'):
  597. """encode str to bytes, with round-tripping "invalid" bytes"""
  598. return s.encode(coding, errors)
  599. def bin_to_hex(binary):
  600. return hexlify(binary).decode('ascii')
  601. class Location:
  602. """Object representing a repository / archive location
  603. """
  604. proto = user = host = port = path = archive = None
  605. # path must not contain :: (it ends at :: or string end), but may contain single colons.
  606. # to avoid ambiguities with other regexes, it must also not start with ":".
  607. path_re = r"""
  608. (?!:) # not starting with ":"
  609. (?P<path>([^:]|(:(?!:)))+) # any chars, but no "::"
  610. """
  611. # optional ::archive_name at the end, archive name must not contain "/".
  612. # borg mount's FUSE filesystem creates one level of directories from
  613. # the archive names and of course "/" is not valid in a directory name.
  614. optional_archive_re = r"""
  615. (?:
  616. :: # "::" as separator
  617. (?P<archive>[^/]+) # archive name must not contain "/"
  618. )?$""" # must match until the end
  619. # regexes for misc. kinds of supported location specifiers:
  620. ssh_re = re.compile(r"""
  621. (?P<proto>ssh):// # ssh://
  622. (?:(?P<user>[^@]+)@)? # user@ (optional)
  623. (?P<host>[^:/]+)(?::(?P<port>\d+))? # host or host:port
  624. """ + path_re + optional_archive_re, re.VERBOSE) # path or path::archive
  625. file_re = re.compile(r"""
  626. (?P<proto>file):// # file://
  627. """ + path_re + optional_archive_re, re.VERBOSE) # path or path::archive
  628. # note: scp_re is also use for local pathes
  629. scp_re = re.compile(r"""
  630. (
  631. (?:(?P<user>[^@]+)@)? # user@ (optional)
  632. (?P<host>[^:/]+): # host: (don't match / in host to disambiguate from file:)
  633. )? # user@host: part is optional
  634. """ + path_re + optional_archive_re, re.VERBOSE) # path with optional archive
  635. # get the repo from BORG_REPO env and the optional archive from param.
  636. # if the syntax requires giving REPOSITORY (see "borg mount"),
  637. # use "::" to let it use the env var.
  638. # if REPOSITORY argument is optional, it'll automatically use the env.
  639. env_re = re.compile(r""" # the repo part is fetched from BORG_REPO
  640. (?:::$) # just "::" is ok (when a pos. arg is required, no archive)
  641. | # or
  642. """ + optional_archive_re, re.VERBOSE) # archive name (optional, may be empty)
  643. def __init__(self, text=''):
  644. self.orig = text
  645. if not self.parse(self.orig):
  646. raise ValueError
  647. def parse(self, text):
  648. text = replace_placeholders(text)
  649. valid = self._parse(text)
  650. if valid:
  651. return True
  652. m = self.env_re.match(text)
  653. if not m:
  654. return False
  655. repo = os.environ.get('BORG_REPO')
  656. if repo is None:
  657. return False
  658. valid = self._parse(repo)
  659. if not valid:
  660. return False
  661. self.archive = m.group('archive')
  662. return True
  663. def _parse(self, text):
  664. m = self.ssh_re.match(text)
  665. if m:
  666. self.proto = m.group('proto')
  667. self.user = m.group('user')
  668. self.host = m.group('host')
  669. self.port = m.group('port') and int(m.group('port')) or None
  670. self.path = os.path.normpath(m.group('path'))
  671. self.archive = m.group('archive')
  672. return True
  673. m = self.file_re.match(text)
  674. if m:
  675. self.proto = m.group('proto')
  676. self.path = os.path.normpath(m.group('path'))
  677. self.archive = m.group('archive')
  678. return True
  679. m = self.scp_re.match(text)
  680. if m:
  681. self.user = m.group('user')
  682. self.host = m.group('host')
  683. self.path = os.path.normpath(m.group('path'))
  684. self.archive = m.group('archive')
  685. self.proto = self.host and 'ssh' or 'file'
  686. return True
  687. return False
  688. def __str__(self):
  689. items = [
  690. 'proto=%r' % self.proto,
  691. 'user=%r' % self.user,
  692. 'host=%r' % self.host,
  693. 'port=%r' % self.port,
  694. 'path=%r' % self.path,
  695. 'archive=%r' % self.archive,
  696. ]
  697. return ', '.join(items)
  698. def to_key_filename(self):
  699. name = re.sub('[^\w]', '_', self.path).strip('_')
  700. if self.proto != 'file':
  701. name = self.host + '__' + name
  702. return os.path.join(get_keys_dir(), name)
  703. def __repr__(self):
  704. return "Location(%s)" % self
  705. def canonical_path(self):
  706. if self.proto == 'file':
  707. return self.path
  708. else:
  709. if self.path and self.path.startswith('~'):
  710. path = '/' + self.path
  711. elif self.path and not self.path.startswith('/'):
  712. path = '/~/' + self.path
  713. else:
  714. path = self.path
  715. return 'ssh://{}{}{}{}'.format('{}@'.format(self.user) if self.user else '',
  716. self.host,
  717. ':{}'.format(self.port) if self.port else '',
  718. path)
  719. def location_validator(archive=None):
  720. def validator(text):
  721. try:
  722. loc = Location(text)
  723. except ValueError:
  724. raise argparse.ArgumentTypeError('Invalid location format: "%s"' % text) from None
  725. if archive is True and not loc.archive:
  726. raise argparse.ArgumentTypeError('"%s": No archive specified' % text)
  727. elif archive is False and loc.archive:
  728. raise argparse.ArgumentTypeError('"%s" No archive can be specified' % text)
  729. return loc
  730. return validator
  731. def archivename_validator():
  732. def validator(text):
  733. if '/' in text or '::' in text or not text:
  734. raise argparse.ArgumentTypeError('Invalid repository name: "%s"' % text)
  735. return text
  736. return validator
  737. def decode_dict(d, keys, encoding='utf-8', errors='surrogateescape'):
  738. for key in keys:
  739. if isinstance(d.get(key), bytes):
  740. d[key] = d[key].decode(encoding, errors)
  741. return d
  742. def remove_surrogates(s, errors='replace'):
  743. """Replace surrogates generated by fsdecode with '?'
  744. """
  745. return s.encode('utf-8', errors).decode('utf-8')
  746. _safe_re = re.compile(r'^((\.\.)?/+)+')
  747. def make_path_safe(path):
  748. """Make path safe by making it relative and local
  749. """
  750. return _safe_re.sub('', path) or '.'
  751. def daemonize():
  752. """Detach process from controlling terminal and run in background
  753. """
  754. pid = os.fork()
  755. if pid:
  756. os._exit(0)
  757. os.setsid()
  758. pid = os.fork()
  759. if pid:
  760. os._exit(0)
  761. os.chdir('/')
  762. os.close(0)
  763. os.close(1)
  764. os.close(2)
  765. fd = os.open('/dev/null', os.O_RDWR)
  766. os.dup2(fd, 0)
  767. os.dup2(fd, 1)
  768. os.dup2(fd, 2)
  769. class StableDict(dict):
  770. """A dict subclass with stable items() ordering"""
  771. def items(self):
  772. return sorted(super().items())
  773. def bigint_to_int(mtime):
  774. """Convert bytearray to int
  775. """
  776. if isinstance(mtime, bytes):
  777. return int.from_bytes(mtime, 'little', signed=True)
  778. return mtime
  779. def int_to_bigint(value):
  780. """Convert integers larger than 64 bits to bytearray
  781. Smaller integers are left alone
  782. """
  783. if value.bit_length() > 63:
  784. return value.to_bytes((value.bit_length() + 9) // 8, 'little', signed=True)
  785. return value
  786. def is_slow_msgpack():
  787. return msgpack.Packer is msgpack.fallback.Packer
  788. FALSISH = ('No', 'NO', 'no', 'N', 'n', '0', )
  789. TRUISH = ('Yes', 'YES', 'yes', 'Y', 'y', '1', )
  790. DEFAULTISH = ('Default', 'DEFAULT', 'default', 'D', 'd', '', )
  791. def yes(msg=None, false_msg=None, true_msg=None, default_msg=None,
  792. retry_msg=None, invalid_msg=None, env_msg='{} (from {})',
  793. falsish=FALSISH, truish=TRUISH, defaultish=DEFAULTISH,
  794. default=False, retry=True, env_var_override=None, ofile=None, input=input):
  795. """Output <msg> (usually a question) and let user input an answer.
  796. Qualifies the answer according to falsish, truish and defaultish as True, False or <default>.
  797. If it didn't qualify and retry is False (no retries wanted), return the default [which
  798. defaults to False]. If retry is True let user retry answering until answer is qualified.
  799. If env_var_override is given and this var is present in the environment, do not ask
  800. the user, but just use the env var contents as answer as if it was typed in.
  801. Otherwise read input from stdin and proceed as normal.
  802. If EOF is received instead an input or an invalid input without retry possibility,
  803. return default.
  804. :param msg: introducing message to output on ofile, no \n is added [None]
  805. :param retry_msg: retry message to output on ofile, no \n is added [None]
  806. :param false_msg: message to output before returning False [None]
  807. :param true_msg: message to output before returning True [None]
  808. :param default_msg: message to output before returning a <default> [None]
  809. :param invalid_msg: message to output after a invalid answer was given [None]
  810. :param env_msg: message to output when using input from env_var_override ['{} (from {})'],
  811. needs to have 2 placeholders for answer and env var name
  812. :param falsish: sequence of answers qualifying as False
  813. :param truish: sequence of answers qualifying as True
  814. :param defaultish: sequence of answers qualifying as <default>
  815. :param default: default return value (defaultish answer was given or no-answer condition) [False]
  816. :param retry: if True and input is incorrect, retry. Otherwise return default. [True]
  817. :param env_var_override: environment variable name [None]
  818. :param ofile: output stream [sys.stderr]
  819. :param input: input function [input from builtins]
  820. :return: boolean answer value, True or False
  821. """
  822. # note: we do not assign sys.stderr as default above, so it is
  823. # really evaluated NOW, not at function definition time.
  824. if ofile is None:
  825. ofile = sys.stderr
  826. if default not in (True, False):
  827. raise ValueError("invalid default value, must be True or False")
  828. if msg:
  829. print(msg, file=ofile, end='', flush=True)
  830. while True:
  831. answer = None
  832. if env_var_override:
  833. answer = os.environ.get(env_var_override)
  834. if answer is not None and env_msg:
  835. print(env_msg.format(answer, env_var_override), file=ofile)
  836. if answer is None:
  837. try:
  838. answer = input()
  839. except EOFError:
  840. # avoid defaultish[0], defaultish could be empty
  841. answer = truish[0] if default else falsish[0]
  842. if answer in defaultish:
  843. if default_msg:
  844. print(default_msg, file=ofile)
  845. return default
  846. if answer in truish:
  847. if true_msg:
  848. print(true_msg, file=ofile)
  849. return True
  850. if answer in falsish:
  851. if false_msg:
  852. print(false_msg, file=ofile)
  853. return False
  854. # if we get here, the answer was invalid
  855. if invalid_msg:
  856. print(invalid_msg, file=ofile)
  857. if not retry:
  858. return default
  859. if retry_msg:
  860. print(retry_msg, file=ofile, end='', flush=True)
  861. # in case we used an environment variable and it gave an invalid answer, do not use it again:
  862. env_var_override = None
  863. class ProgressIndicatorPercent:
  864. def __init__(self, total, step=5, start=0, same_line=False, msg="%3.0f%%", file=None):
  865. """
  866. Percentage-based progress indicator
  867. :param total: total amount of items
  868. :param step: step size in percent
  869. :param start: at which percent value to start
  870. :param same_line: if True, emit output always on same line
  871. :param msg: output message, must contain one %f placeholder for the percentage
  872. :param file: output file, default: sys.stderr
  873. """
  874. self.counter = 0 # 0 .. (total-1)
  875. self.total = total
  876. self.trigger_at = start # output next percentage value when reaching (at least) this
  877. self.step = step
  878. if file is None:
  879. file = sys.stderr
  880. self.file = file
  881. self.msg = msg
  882. self.same_line = same_line
  883. def progress(self, current=None):
  884. if current is not None:
  885. self.counter = current
  886. pct = self.counter * 100 / self.total
  887. self.counter += 1
  888. if pct >= self.trigger_at:
  889. self.trigger_at += self.step
  890. return pct
  891. def show(self, current=None):
  892. pct = self.progress(current)
  893. if pct is not None:
  894. return self.output(pct)
  895. def output(self, percent):
  896. print(self.msg % percent, file=self.file, end='\r' if self.same_line else '\n', flush=True)
  897. def finish(self):
  898. if self.same_line:
  899. print(" " * len(self.msg % 100.0), file=self.file, end='\r')
  900. class ProgressIndicatorEndless:
  901. def __init__(self, step=10, file=None):
  902. """
  903. Progress indicator (long row of dots)
  904. :param step: every Nth call, call the func
  905. :param file: output file, default: sys.stderr
  906. """
  907. self.counter = 0 # call counter
  908. self.triggered = 0 # increases 1 per trigger event
  909. self.step = step # trigger every <step> calls
  910. if file is None:
  911. file = sys.stderr
  912. self.file = file
  913. def progress(self):
  914. self.counter += 1
  915. trigger = self.counter % self.step == 0
  916. if trigger:
  917. self.triggered += 1
  918. return trigger
  919. def show(self):
  920. trigger = self.progress()
  921. if trigger:
  922. return self.output(self.triggered)
  923. def output(self, triggered):
  924. print('.', end='', file=self.file, flush=True)
  925. def finish(self):
  926. print(file=self.file)
  927. def sysinfo():
  928. info = []
  929. info.append('Platform: %s' % (' '.join(platform.uname()), ))
  930. if sys.platform.startswith('linux'):
  931. info.append('Linux: %s %s %s' % platform.linux_distribution())
  932. info.append('Borg: %s Python: %s %s' % (borg_version, platform.python_implementation(), platform.python_version()))
  933. info.append('PID: %d CWD: %s' % (os.getpid(), os.getcwd()))
  934. info.append('sys.argv: %r' % sys.argv)
  935. info.append('SSH_ORIGINAL_COMMAND: %r' % os.environ.get('SSH_ORIGINAL_COMMAND'))
  936. info.append('')
  937. return '\n'.join(info)
  938. def log_multi(*msgs, level=logging.INFO):
  939. """
  940. log multiple lines of text, each line by a separate logging call for cosmetic reasons
  941. each positional argument may be a single or multiple lines (separated by newlines) of text.
  942. """
  943. lines = []
  944. for msg in msgs:
  945. lines.extend(msg.splitlines())
  946. for line in lines:
  947. logger.log(level, line)
  948. class ErrorIgnoringTextIOWrapper(io.TextIOWrapper):
  949. def read(self, n):
  950. if not self.closed:
  951. try:
  952. return super().read(n)
  953. except BrokenPipeError:
  954. try:
  955. super().close()
  956. except OSError:
  957. pass
  958. return ''
  959. def write(self, s):
  960. if not self.closed:
  961. try:
  962. return super().write(s)
  963. except BrokenPipeError:
  964. try:
  965. super().close()
  966. except OSError:
  967. pass
  968. return len(s)
  969. class SignalException(BaseException):
  970. """base class for all signal-based exceptions"""
  971. class SigHup(SignalException):
  972. """raised on SIGHUP signal"""
  973. class SigTerm(SignalException):
  974. """raised on SIGTERM signal"""
  975. @contextlib.contextmanager
  976. def signal_handler(sig, handler):
  977. """
  978. when entering context, set up signal handler <handler> for signal <sig>.
  979. when leaving context, restore original signal handler.
  980. <sig> can bei either a str when giving a signal.SIGXXX attribute name (it
  981. won't crash if the attribute name does not exist as some names are platform
  982. specific) or a int, when giving a signal number.
  983. <handler> is any handler value as accepted by the signal.signal(sig, handler).
  984. """
  985. if isinstance(sig, str):
  986. sig = getattr(signal, sig, None)
  987. if sig is not None:
  988. orig_handler = signal.signal(sig, handler)
  989. try:
  990. yield
  991. finally:
  992. if sig is not None:
  993. signal.signal(sig, orig_handler)
  994. def raising_signal_handler(exc_cls):
  995. def handler(sig_no, frame):
  996. # setting SIG_IGN avoids that an incoming second signal of this
  997. # kind would raise a 2nd exception while we still process the
  998. # exception handler for exc_cls for the 1st signal.
  999. signal.signal(sig_no, signal.SIG_IGN)
  1000. raise exc_cls
  1001. return handler