helpers.py 51 KB

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