helpers.py 50 KB

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