helpers.py 42 KB

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