helpers.py 36 KB

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