helpers.py 35 KB

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