helpers.py 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926
  1. import argparse
  2. import contextlib
  3. import grp
  4. import hashlib
  5. import logging
  6. import io
  7. import os
  8. import os.path
  9. import platform
  10. import pwd
  11. import re
  12. import signal
  13. import socket
  14. import stat
  15. import sys
  16. import textwrap
  17. import threading
  18. import time
  19. import unicodedata
  20. import uuid
  21. from binascii import hexlify
  22. from collections import namedtuple, deque, abc
  23. from datetime import datetime, timezone, timedelta
  24. from fnmatch import translate
  25. from functools import wraps, partial, lru_cache
  26. from itertools import islice
  27. from operator import attrgetter
  28. from string import Formatter
  29. from shutil import get_terminal_size
  30. import msgpack
  31. import msgpack.fallback
  32. from .logger import create_logger
  33. logger = create_logger()
  34. from . import __version__ as borg_version
  35. from . import __version_tuple__ as borg_version_tuple
  36. from . import chunker
  37. from . import crypto
  38. from . import hashindex
  39. from . import shellpattern
  40. from .constants import * # NOQA
  41. # meta dict, data bytes
  42. _Chunk = namedtuple('_Chunk', 'meta data')
  43. def Chunk(data, **meta):
  44. return _Chunk(meta, data)
  45. class Error(Exception):
  46. """Error base class"""
  47. # if we raise such an Error and it is only catched by the uppermost
  48. # exception handler (that exits short after with the given exit_code),
  49. # it is always a (fatal and abrupt) EXIT_ERROR, never just a warning.
  50. exit_code = EXIT_ERROR
  51. # show a traceback?
  52. traceback = False
  53. def __init__(self, *args):
  54. super().__init__(*args)
  55. self.args = args
  56. def get_message(self):
  57. return type(self).__doc__.format(*self.args)
  58. __str__ = get_message
  59. class ErrorWithTraceback(Error):
  60. """like Error, but show a traceback also"""
  61. traceback = True
  62. class IntegrityError(ErrorWithTraceback):
  63. """Data integrity error: {}"""
  64. class ExtensionModuleError(Error):
  65. """The Borg binary extension modules do not seem to be properly installed"""
  66. class NoManifestError(Error):
  67. """Repository has no manifest."""
  68. class PlaceholderError(Error):
  69. """Formatting Error: "{}".format({}): {}({})"""
  70. def check_extension_modules():
  71. from . import platform, compress, item
  72. if hashindex.API_VERSION != '1.1_01':
  73. raise ExtensionModuleError
  74. if chunker.API_VERSION != '1.1_01':
  75. raise ExtensionModuleError
  76. if compress.API_VERSION != '1.1_01':
  77. raise ExtensionModuleError
  78. if crypto.API_VERSION != '1.1_01':
  79. raise ExtensionModuleError
  80. if platform.API_VERSION != platform.OS_API_VERSION != '1.1_01':
  81. raise ExtensionModuleError
  82. if item.API_VERSION != '1.1_01':
  83. raise ExtensionModuleError
  84. ArchiveInfo = namedtuple('ArchiveInfo', 'name id ts')
  85. class Archives(abc.MutableMapping):
  86. """
  87. Nice wrapper around the archives dict, making sure only valid types/values get in
  88. and we can deal with str keys (and it internally encodes to byte keys) and eiter
  89. str timestamps or datetime timestamps.
  90. """
  91. def __init__(self):
  92. # key: encoded archive name, value: dict(b'id': bytes_id, b'time': bytes_iso_ts)
  93. self._archives = {}
  94. def __len__(self):
  95. return len(self._archives)
  96. def __iter__(self):
  97. return iter(safe_decode(name) for name in self._archives)
  98. def __getitem__(self, name):
  99. assert isinstance(name, str)
  100. _name = safe_encode(name)
  101. values = self._archives.get(_name)
  102. if values is None:
  103. raise KeyError
  104. ts = parse_timestamp(values[b'time'].decode('utf-8'))
  105. return ArchiveInfo(name=name, id=values[b'id'], ts=ts)
  106. def __setitem__(self, name, info):
  107. assert isinstance(name, str)
  108. name = safe_encode(name)
  109. assert isinstance(info, tuple)
  110. id, ts = info
  111. assert isinstance(id, bytes)
  112. if isinstance(ts, datetime):
  113. ts = ts.replace(tzinfo=None).isoformat()
  114. assert isinstance(ts, str)
  115. ts = ts.encode()
  116. self._archives[name] = {b'id': id, b'time': ts}
  117. def __delitem__(self, name):
  118. assert isinstance(name, str)
  119. name = safe_encode(name)
  120. del self._archives[name]
  121. def list(self, sort_by=(), reverse=False, prefix='', first=None, last=None):
  122. """
  123. Inexpensive Archive.list_archives replacement if we just need .name, .id, .ts
  124. Returns list of borg.helpers.ArchiveInfo instances.
  125. sort_by can be a list of sort keys, they are applied in reverse order.
  126. """
  127. if isinstance(sort_by, (str, bytes)):
  128. raise TypeError('sort_by must be a sequence of str')
  129. archives = [x for x in self.values() if x.name.startswith(prefix)]
  130. for sortkey in reversed(sort_by):
  131. archives.sort(key=attrgetter(sortkey))
  132. if reverse or last:
  133. archives.reverse()
  134. n = first or last or len(archives)
  135. return archives[:n]
  136. def list_considering(self, args):
  137. """
  138. get a list of archives, considering --first/last/prefix/sort cmdline args
  139. """
  140. if args.location.archive:
  141. raise Error('The options --first, --last and --prefix can only be used on repository targets.')
  142. return self.list(sort_by=args.sort_by.split(','), prefix=args.prefix, first=args.first, last=args.last)
  143. def set_raw_dict(self, d):
  144. """set the dict we get from the msgpack unpacker"""
  145. for k, v in d.items():
  146. assert isinstance(k, bytes)
  147. assert isinstance(v, dict) and b'id' in v and b'time' in v
  148. self._archives[k] = v
  149. def get_raw_dict(self):
  150. """get the dict we can give to the msgpack packer"""
  151. return self._archives
  152. class Manifest:
  153. MANIFEST_ID = b'\0' * 32
  154. def __init__(self, key, repository, item_keys=None):
  155. self.archives = Archives()
  156. self.config = {}
  157. self.key = key
  158. self.repository = repository
  159. self.item_keys = frozenset(item_keys) if item_keys is not None else ITEM_KEYS
  160. self.tam_verified = False
  161. @property
  162. def id_str(self):
  163. return bin_to_hex(self.id)
  164. @classmethod
  165. def load(cls, repository, key=None, force_tam_not_required=False):
  166. from .item import ManifestItem
  167. from .key import key_factory, tam_required_file, tam_required
  168. from .repository import Repository
  169. try:
  170. cdata = repository.get(cls.MANIFEST_ID)
  171. except Repository.ObjectNotFound:
  172. raise NoManifestError
  173. if not key:
  174. key = key_factory(repository, cdata)
  175. manifest = cls(key, repository)
  176. data = key.decrypt(None, cdata).data
  177. manifest_dict, manifest.tam_verified = key.unpack_and_verify_manifest(data, force_tam_not_required=force_tam_not_required)
  178. m = ManifestItem(internal_dict=manifest_dict)
  179. manifest.id = key.id_hash(data)
  180. if m.get('version') != 1:
  181. raise ValueError('Invalid manifest version')
  182. manifest.archives.set_raw_dict(m.archives)
  183. manifest.timestamp = m.get('timestamp')
  184. manifest.config = m.config
  185. # valid item keys are whatever is known in the repo or every key we know
  186. manifest.item_keys = ITEM_KEYS | frozenset(key.decode() for key in m.get('item_keys', []))
  187. if manifest.tam_verified:
  188. manifest_required = manifest.config.get(b'tam_required', False)
  189. security_required = tam_required(repository)
  190. if manifest_required and not security_required:
  191. logger.debug('Manifest is TAM verified and says TAM is required, updating security database...')
  192. file = tam_required_file(repository)
  193. open(file, 'w').close()
  194. if not manifest_required and security_required:
  195. logger.debug('Manifest is TAM verified and says TAM is *not* required, updating security database...')
  196. os.unlink(tam_required_file(repository))
  197. return manifest, key
  198. def write(self):
  199. from .item import ManifestItem
  200. if self.key.tam_required:
  201. self.config[b'tam_required'] = True
  202. self.timestamp = datetime.utcnow().isoformat()
  203. manifest = ManifestItem(
  204. version=1,
  205. archives=StableDict(self.archives.get_raw_dict()),
  206. timestamp=self.timestamp,
  207. config=StableDict(self.config),
  208. item_keys=tuple(sorted(self.item_keys)),
  209. )
  210. self.tam_verified = True
  211. data = self.key.pack_and_authenticate_metadata(manifest.as_dict())
  212. self.id = self.key.id_hash(data)
  213. self.repository.put(self.MANIFEST_ID, self.key.encrypt(Chunk(data, compression={'name': 'none'})))
  214. def prune_within(archives, within):
  215. multiplier = {'H': 1, 'd': 24, 'w': 24 * 7, 'm': 24 * 31, 'y': 24 * 365}
  216. try:
  217. hours = int(within[:-1]) * multiplier[within[-1]]
  218. except (KeyError, ValueError):
  219. # I don't like how this displays the original exception too:
  220. raise argparse.ArgumentTypeError('Unable to parse --within option: "%s"' % within)
  221. if hours <= 0:
  222. raise argparse.ArgumentTypeError('Number specified using --within option must be positive')
  223. target = datetime.now(timezone.utc) - timedelta(seconds=hours * 3600)
  224. return [a for a in archives if a.ts > target]
  225. def prune_split(archives, pattern, n, skip=[]):
  226. last = None
  227. keep = []
  228. if n == 0:
  229. return keep
  230. for a in sorted(archives, key=attrgetter('ts'), reverse=True):
  231. period = to_localtime(a.ts).strftime(pattern)
  232. if period != last:
  233. last = period
  234. if a not in skip:
  235. keep.append(a)
  236. if len(keep) == n:
  237. break
  238. return keep
  239. def get_home_dir():
  240. """Get user's home directory while preferring a possibly set HOME
  241. environment variable
  242. """
  243. # os.path.expanduser() behaves differently for '~' and '~someuser' as
  244. # parameters: when called with an explicit username, the possibly set
  245. # environment variable HOME is no longer respected. So we have to check if
  246. # it is set and only expand the user's home directory if HOME is unset.
  247. if os.environ.get('HOME', ''):
  248. return os.environ.get('HOME')
  249. else:
  250. return os.path.expanduser('~%s' % os.environ.get('USER', ''))
  251. def get_keys_dir():
  252. """Determine where to repository keys and cache"""
  253. xdg_config = os.environ.get('XDG_CONFIG_HOME', os.path.join(get_home_dir(), '.config'))
  254. keys_dir = os.environ.get('BORG_KEYS_DIR', os.path.join(xdg_config, 'borg', 'keys'))
  255. if not os.path.exists(keys_dir):
  256. os.makedirs(keys_dir)
  257. os.chmod(keys_dir, stat.S_IRWXU)
  258. return keys_dir
  259. def get_security_dir(repository_id=None):
  260. """Determine where to store local security information."""
  261. xdg_config = os.environ.get('XDG_CONFIG_HOME', os.path.join(get_home_dir(), '.config'))
  262. security_dir = os.environ.get('BORG_SECURITY_DIR', os.path.join(xdg_config, 'borg', 'security'))
  263. if repository_id:
  264. security_dir = os.path.join(security_dir, repository_id)
  265. if not os.path.exists(security_dir):
  266. os.makedirs(security_dir)
  267. os.chmod(security_dir, stat.S_IRWXU)
  268. return security_dir
  269. def get_cache_dir():
  270. """Determine where to repository keys and cache"""
  271. xdg_cache = os.environ.get('XDG_CACHE_HOME', os.path.join(get_home_dir(), '.cache'))
  272. cache_dir = os.environ.get('BORG_CACHE_DIR', os.path.join(xdg_cache, 'borg'))
  273. if not os.path.exists(cache_dir):
  274. os.makedirs(cache_dir)
  275. os.chmod(cache_dir, stat.S_IRWXU)
  276. with open(os.path.join(cache_dir, CACHE_TAG_NAME), 'wb') as fd:
  277. fd.write(CACHE_TAG_CONTENTS)
  278. fd.write(textwrap.dedent("""
  279. # This file is a cache directory tag created by Borg.
  280. # For information about cache directory tags, see:
  281. # http://www.brynosaurus.com/cachedir/
  282. """).encode('ascii'))
  283. return cache_dir
  284. def to_localtime(ts):
  285. """Convert datetime object from UTC to local time zone"""
  286. return datetime(*time.localtime((ts - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds())[:6])
  287. def parse_timestamp(timestamp):
  288. """Parse a ISO 8601 timestamp string"""
  289. if '.' in timestamp: # microseconds might not be present
  290. return datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S.%f').replace(tzinfo=timezone.utc)
  291. else:
  292. return datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc)
  293. def load_excludes(fh):
  294. """Load and parse exclude patterns from file object. Lines empty or starting with '#' after stripping whitespace on
  295. both line ends are ignored.
  296. """
  297. return [parse_pattern(pattern) for pattern in clean_lines(fh)]
  298. def update_excludes(args):
  299. """Merge exclude patterns from files with those on command line."""
  300. if hasattr(args, 'exclude_files') and args.exclude_files:
  301. if not hasattr(args, 'excludes') or args.excludes is None:
  302. args.excludes = []
  303. for file in args.exclude_files:
  304. args.excludes += load_excludes(file)
  305. file.close()
  306. class PatternMatcher:
  307. def __init__(self, fallback=None):
  308. self._items = []
  309. # Value to return from match function when none of the patterns match.
  310. self.fallback = fallback
  311. def empty(self):
  312. return not len(self._items)
  313. def add(self, patterns, value):
  314. """Add list of patterns to internal list. The given value is returned from the match function when one of the
  315. given patterns matches.
  316. """
  317. self._items.extend((i, value) for i in patterns)
  318. def match(self, path):
  319. for (pattern, value) in self._items:
  320. if pattern.match(path):
  321. return value
  322. return self.fallback
  323. def normalized(func):
  324. """ Decorator for the Pattern match methods, returning a wrapper that
  325. normalizes OSX paths to match the normalized pattern on OSX, and
  326. returning the original method on other platforms"""
  327. @wraps(func)
  328. def normalize_wrapper(self, path):
  329. return func(self, unicodedata.normalize("NFD", path))
  330. if sys.platform in ('darwin',):
  331. # HFS+ converts paths to a canonical form, so users shouldn't be
  332. # required to enter an exact match
  333. return normalize_wrapper
  334. else:
  335. # Windows and Unix filesystems allow different forms, so users
  336. # always have to enter an exact match
  337. return func
  338. class PatternBase:
  339. """Shared logic for inclusion/exclusion patterns.
  340. """
  341. PREFIX = NotImplemented
  342. def __init__(self, pattern):
  343. self.pattern_orig = pattern
  344. self.match_count = 0
  345. if sys.platform in ('darwin',):
  346. pattern = unicodedata.normalize("NFD", pattern)
  347. self._prepare(pattern)
  348. @normalized
  349. def match(self, path):
  350. matches = self._match(path)
  351. if matches:
  352. self.match_count += 1
  353. return matches
  354. def __repr__(self):
  355. return '%s(%s)' % (type(self), self.pattern)
  356. def __str__(self):
  357. return self.pattern_orig
  358. def _prepare(self, pattern):
  359. raise NotImplementedError
  360. def _match(self, path):
  361. raise NotImplementedError
  362. # For PathPrefixPattern, FnmatchPattern and ShellPattern, we require that the pattern either match the whole path
  363. # or an initial segment of the path up to but not including a path separator. To unify the two cases, we add a path
  364. # separator to the end of the path before matching.
  365. class PathPrefixPattern(PatternBase):
  366. """Literal files or directories listed on the command line
  367. for some operations (e.g. extract, but not create).
  368. If a directory is specified, all paths that start with that
  369. path match as well. A trailing slash makes no difference.
  370. """
  371. PREFIX = "pp"
  372. def _prepare(self, pattern):
  373. self.pattern = os.path.normpath(pattern).rstrip(os.path.sep) + os.path.sep
  374. def _match(self, path):
  375. return (path + os.path.sep).startswith(self.pattern)
  376. class FnmatchPattern(PatternBase):
  377. """Shell glob patterns to exclude. A trailing slash means to
  378. exclude the contents of a directory, but not the directory itself.
  379. """
  380. PREFIX = "fm"
  381. def _prepare(self, pattern):
  382. if pattern.endswith(os.path.sep):
  383. pattern = os.path.normpath(pattern).rstrip(os.path.sep) + os.path.sep + '*' + os.path.sep
  384. else:
  385. pattern = os.path.normpath(pattern) + os.path.sep + '*'
  386. self.pattern = pattern
  387. # fnmatch and re.match both cache compiled regular expressions.
  388. # Nevertheless, this is about 10 times faster.
  389. self.regex = re.compile(translate(self.pattern))
  390. def _match(self, path):
  391. return (self.regex.match(path + os.path.sep) is not None)
  392. class ShellPattern(PatternBase):
  393. """Shell glob patterns to exclude. A trailing slash means to
  394. exclude the contents of a directory, but not the directory itself.
  395. """
  396. PREFIX = "sh"
  397. def _prepare(self, pattern):
  398. sep = os.path.sep
  399. if pattern.endswith(sep):
  400. pattern = os.path.normpath(pattern).rstrip(sep) + sep + "**" + sep + "*" + sep
  401. else:
  402. pattern = os.path.normpath(pattern) + sep + "**" + sep + "*"
  403. self.pattern = pattern
  404. self.regex = re.compile(shellpattern.translate(self.pattern))
  405. def _match(self, path):
  406. return (self.regex.match(path + os.path.sep) is not None)
  407. class RegexPattern(PatternBase):
  408. """Regular expression to exclude.
  409. """
  410. PREFIX = "re"
  411. def _prepare(self, pattern):
  412. self.pattern = pattern
  413. self.regex = re.compile(pattern)
  414. def _match(self, path):
  415. # Normalize path separators
  416. if os.path.sep != '/':
  417. path = path.replace(os.path.sep, '/')
  418. return (self.regex.search(path) is not None)
  419. _PATTERN_STYLES = set([
  420. FnmatchPattern,
  421. PathPrefixPattern,
  422. RegexPattern,
  423. ShellPattern,
  424. ])
  425. _PATTERN_STYLE_BY_PREFIX = dict((i.PREFIX, i) for i in _PATTERN_STYLES)
  426. def parse_pattern(pattern, fallback=FnmatchPattern):
  427. """Read pattern from string and return an instance of the appropriate implementation class.
  428. """
  429. if len(pattern) > 2 and pattern[2] == ":" and pattern[:2].isalnum():
  430. (style, pattern) = (pattern[:2], pattern[3:])
  431. cls = _PATTERN_STYLE_BY_PREFIX.get(style, None)
  432. if cls is None:
  433. raise ValueError("Unknown pattern style: {}".format(style))
  434. else:
  435. cls = fallback
  436. return cls(pattern)
  437. def timestamp(s):
  438. """Convert a --timestamp=s argument to a datetime object"""
  439. try:
  440. # is it pointing to a file / directory?
  441. ts = os.stat(s).st_mtime
  442. return datetime.utcfromtimestamp(ts)
  443. except OSError:
  444. # didn't work, try parsing as timestamp. UTC, no TZ, no microsecs support.
  445. for format in ('%Y-%m-%dT%H:%M:%SZ', '%Y-%m-%dT%H:%M:%S+00:00',
  446. '%Y-%m-%dT%H:%M:%S', '%Y-%m-%d %H:%M:%S',
  447. '%Y-%m-%dT%H:%M', '%Y-%m-%d %H:%M',
  448. '%Y-%m-%d', '%Y-%j',
  449. ):
  450. try:
  451. return datetime.strptime(s, format)
  452. except ValueError:
  453. continue
  454. raise ValueError
  455. def ChunkerParams(s):
  456. if s.strip().lower() == "default":
  457. return CHUNKER_PARAMS
  458. chunk_min, chunk_max, chunk_mask, window_size = s.split(',')
  459. if int(chunk_max) > 23:
  460. raise ValueError('max. chunk size exponent must not be more than 23 (2^23 = 8MiB max. chunk size)')
  461. return int(chunk_min), int(chunk_max), int(chunk_mask), int(window_size)
  462. def CompressionSpec(s):
  463. values = s.split(',')
  464. count = len(values)
  465. if count < 1:
  466. raise ValueError
  467. # --compression algo[,level]
  468. name = values[0]
  469. if name in ('none', 'lz4', ):
  470. return dict(name=name)
  471. if name in ('zlib', 'lzma', ):
  472. if count < 2:
  473. level = 6 # default compression level in py stdlib
  474. elif count == 2:
  475. level = int(values[1])
  476. if not 0 <= level <= 9:
  477. raise ValueError
  478. else:
  479. raise ValueError
  480. return dict(name=name, level=level)
  481. if name == 'auto':
  482. if 2 <= count <= 3:
  483. compression = ','.join(values[1:])
  484. else:
  485. raise ValueError
  486. return dict(name=name, spec=CompressionSpec(compression))
  487. raise ValueError
  488. def dir_is_cachedir(path):
  489. """Determines whether the specified path is a cache directory (and
  490. therefore should potentially be excluded from the backup) according to
  491. the CACHEDIR.TAG protocol
  492. (http://www.brynosaurus.com/cachedir/spec.html).
  493. """
  494. tag_path = os.path.join(path, CACHE_TAG_NAME)
  495. try:
  496. if os.path.exists(tag_path):
  497. with open(tag_path, 'rb') as tag_file:
  498. tag_data = tag_file.read(len(CACHE_TAG_CONTENTS))
  499. if tag_data == CACHE_TAG_CONTENTS:
  500. return True
  501. except OSError:
  502. pass
  503. return False
  504. def dir_is_tagged(path, exclude_caches, exclude_if_present):
  505. """Determines whether the specified path is excluded by being a cache
  506. directory or containing user-specified tag files. Returns a list of the
  507. paths of the tag files (either CACHEDIR.TAG or the matching
  508. user-specified files).
  509. """
  510. tag_paths = []
  511. if exclude_caches and dir_is_cachedir(path):
  512. tag_paths.append(os.path.join(path, CACHE_TAG_NAME))
  513. if exclude_if_present is not None:
  514. for tag in exclude_if_present:
  515. tag_path = os.path.join(path, tag)
  516. if os.path.isfile(tag_path):
  517. tag_paths.append(tag_path)
  518. return tag_paths
  519. def partial_format(format, mapping):
  520. """
  521. Apply format.format_map(mapping) while preserving unknown keys
  522. Does not support attribute access, indexing and ![rsa] conversions
  523. """
  524. for key, value in mapping.items():
  525. key = re.escape(key)
  526. format = re.sub(r'(?<!\{)((\{%s\})|(\{%s:[^\}]*\}))' % (key, key),
  527. lambda match: match.group(1).format_map(mapping),
  528. format)
  529. return format
  530. class DatetimeWrapper:
  531. def __init__(self, dt):
  532. self.dt = dt
  533. def __format__(self, format_spec):
  534. if format_spec == '':
  535. format_spec = '%Y-%m-%dT%H:%M:%S'
  536. return self.dt.__format__(format_spec)
  537. def format_line(format, data):
  538. try:
  539. return format.format(**data)
  540. except Exception as e:
  541. raise PlaceholderError(format, data, e.__class__.__name__, str(e))
  542. def replace_placeholders(text):
  543. """Replace placeholders in text with their values."""
  544. current_time = datetime.now()
  545. data = {
  546. 'pid': os.getpid(),
  547. 'fqdn': socket.getfqdn(),
  548. 'hostname': socket.gethostname(),
  549. 'now': DatetimeWrapper(current_time.now()),
  550. 'utcnow': DatetimeWrapper(current_time.utcnow()),
  551. 'user': uid2user(os.getuid(), os.getuid()),
  552. 'uuid4': str(uuid.uuid4()),
  553. 'borgversion': borg_version,
  554. 'borgmajor': '%d' % borg_version_tuple[:1],
  555. 'borgminor': '%d.%d' % borg_version_tuple[:2],
  556. 'borgpatch': '%d.%d.%d' % borg_version_tuple[:3],
  557. }
  558. return format_line(text, data)
  559. PrefixSpec = replace_placeholders
  560. HUMAN_SORT_KEYS = ['timestamp'] + list(ArchiveInfo._fields)
  561. HUMAN_SORT_KEYS.remove('ts')
  562. def SortBySpec(text):
  563. for token in text.split(','):
  564. if token not in HUMAN_SORT_KEYS:
  565. raise ValueError('Invalid sort key: %s' % token)
  566. return text.replace('timestamp', 'ts')
  567. def safe_timestamp(item_timestamp_ns):
  568. try:
  569. return datetime.fromtimestamp(item_timestamp_ns / 1e9)
  570. except OverflowError:
  571. # likely a broken file time and datetime did not want to go beyond year 9999
  572. return datetime(9999, 12, 31, 23, 59, 59)
  573. def format_time(t):
  574. """use ISO-8601 date and time format
  575. """
  576. return t.strftime('%a, %Y-%m-%d %H:%M:%S')
  577. def format_timedelta(td):
  578. """Format timedelta in a human friendly format
  579. """
  580. ts = td.total_seconds()
  581. s = ts % 60
  582. m = int(ts / 60) % 60
  583. h = int(ts / 3600) % 24
  584. txt = '%.2f seconds' % s
  585. if m:
  586. txt = '%d minutes %s' % (m, txt)
  587. if h:
  588. txt = '%d hours %s' % (h, txt)
  589. if td.days:
  590. txt = '%d days %s' % (td.days, txt)
  591. return txt
  592. def format_file_size(v, precision=2, sign=False):
  593. """Format file size into a human friendly format
  594. """
  595. return sizeof_fmt_decimal(v, suffix='B', sep=' ', precision=precision, sign=sign)
  596. def parse_file_size(s):
  597. """Return int from file size (1234, 55G, 1.7T)."""
  598. if not s:
  599. return int(s) # will raise
  600. suffix = s[-1]
  601. power = 1000
  602. try:
  603. factor = {
  604. 'K': power,
  605. 'M': power**2,
  606. 'G': power**3,
  607. 'T': power**4,
  608. 'P': power**5,
  609. }[suffix]
  610. s = s[:-1]
  611. except KeyError:
  612. factor = 1
  613. return int(float(s) * factor)
  614. def sizeof_fmt(num, suffix='B', units=None, power=None, sep='', precision=2, sign=False):
  615. prefix = '+' if sign and num > 0 else ''
  616. for unit in units[:-1]:
  617. if abs(round(num, precision)) < power:
  618. if isinstance(num, int):
  619. return "{}{}{}{}{}".format(prefix, num, sep, unit, suffix)
  620. else:
  621. return "{}{:3.{}f}{}{}{}".format(prefix, num, precision, sep, unit, suffix)
  622. num /= float(power)
  623. return "{}{:.{}f}{}{}{}".format(prefix, num, precision, sep, units[-1], suffix)
  624. def sizeof_fmt_iec(num, suffix='B', sep='', precision=2, sign=False):
  625. return sizeof_fmt(num, suffix=suffix, sep=sep, precision=precision, sign=sign,
  626. units=['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi'], power=1024)
  627. def sizeof_fmt_decimal(num, suffix='B', sep='', precision=2, sign=False):
  628. return sizeof_fmt(num, suffix=suffix, sep=sep, precision=precision, sign=sign,
  629. units=['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'], power=1000)
  630. def format_archive(archive):
  631. return '%-36s %s [%s]' % (
  632. archive.name,
  633. format_time(to_localtime(archive.ts)),
  634. bin_to_hex(archive.id),
  635. )
  636. class Buffer:
  637. """
  638. provide a thread-local buffer
  639. """
  640. class MemoryLimitExceeded(Error, OSError):
  641. """Requested buffer size {} is above the limit of {}."""
  642. def __init__(self, allocator, size=4096, limit=None):
  643. """
  644. Initialize the buffer: use allocator(size) call to allocate a buffer.
  645. Optionally, set the upper <limit> for the buffer size.
  646. """
  647. assert callable(allocator), 'must give alloc(size) function as first param'
  648. assert limit is None or size <= limit, 'initial size must be <= limit'
  649. self._thread_local = threading.local()
  650. self.allocator = allocator
  651. self.limit = limit
  652. self.resize(size, init=True)
  653. def __len__(self):
  654. return len(self._thread_local.buffer)
  655. def resize(self, size, init=False):
  656. """
  657. resize the buffer - to avoid frequent reallocation, we usually always grow (if needed).
  658. giving init=True it is possible to first-time initialize or shrink the buffer.
  659. if a buffer size beyond the limit is requested, raise Buffer.MemoryLimitExceeded (OSError).
  660. """
  661. size = int(size)
  662. if self.limit is not None and size > self.limit:
  663. raise Buffer.MemoryLimitExceeded(size, self.limit)
  664. if init or len(self) < size:
  665. self._thread_local.buffer = self.allocator(size)
  666. def get(self, size=None, init=False):
  667. """
  668. return a buffer of at least the requested size (None: any current size).
  669. init=True can be given to trigger shrinking of the buffer to the given size.
  670. """
  671. if size is not None:
  672. self.resize(size, init)
  673. return self._thread_local.buffer
  674. @lru_cache(maxsize=None)
  675. def uid2user(uid, default=None):
  676. try:
  677. return pwd.getpwuid(uid).pw_name
  678. except KeyError:
  679. return default
  680. @lru_cache(maxsize=None)
  681. def user2uid(user, default=None):
  682. try:
  683. return user and pwd.getpwnam(user).pw_uid
  684. except KeyError:
  685. return default
  686. @lru_cache(maxsize=None)
  687. def gid2group(gid, default=None):
  688. try:
  689. return grp.getgrgid(gid).gr_name
  690. except KeyError:
  691. return default
  692. @lru_cache(maxsize=None)
  693. def group2gid(group, default=None):
  694. try:
  695. return group and grp.getgrnam(group).gr_gid
  696. except KeyError:
  697. return default
  698. def posix_acl_use_stored_uid_gid(acl):
  699. """Replace the user/group field with the stored uid/gid
  700. """
  701. entries = []
  702. for entry in safe_decode(acl).split('\n'):
  703. if entry:
  704. fields = entry.split(':')
  705. if len(fields) == 4:
  706. entries.append(':'.join([fields[0], fields[3], fields[2]]))
  707. else:
  708. entries.append(entry)
  709. return safe_encode('\n'.join(entries))
  710. def safe_decode(s, coding='utf-8', errors='surrogateescape'):
  711. """decode bytes to str, with round-tripping "invalid" bytes"""
  712. if s is None:
  713. return None
  714. return s.decode(coding, errors)
  715. def safe_encode(s, coding='utf-8', errors='surrogateescape'):
  716. """encode str to bytes, with round-tripping "invalid" bytes"""
  717. if s is None:
  718. return None
  719. return s.encode(coding, errors)
  720. def bin_to_hex(binary):
  721. return hexlify(binary).decode('ascii')
  722. class Location:
  723. """Object representing a repository / archive location
  724. """
  725. proto = user = host = port = path = archive = None
  726. # user must not contain "@", ":" or "/".
  727. # Quoting adduser error message:
  728. # "To avoid problems, the username should consist only of letters, digits,
  729. # underscores, periods, at signs and dashes, and not start with a dash
  730. # (as defined by IEEE Std 1003.1-2001)."
  731. # We use "@" as separator between username and hostname, so we must
  732. # disallow it within the pure username part.
  733. optional_user_re = r"""
  734. (?:(?P<user>[^@:/]+)@)?
  735. """
  736. # path must not contain :: (it ends at :: or string end), but may contain single colons.
  737. # to avoid ambiguities with other regexes, it must also not start with ":" nor with "//" nor with "ssh://".
  738. path_re = r"""
  739. (?!(:|//|ssh://)) # not starting with ":" or // or ssh://
  740. (?P<path>([^:]|(:(?!:)))+) # any chars, but no "::"
  741. """
  742. # abs_path must not contain :: (it ends at :: or string end), but may contain single colons.
  743. # it must start with a / and that slash is part of the path.
  744. abs_path_re = r"""
  745. (?P<path>(/([^:]|(:(?!:)))+)) # start with /, then any chars, but no "::"
  746. """
  747. # optional ::archive_name at the end, archive name must not contain "/".
  748. # borg mount's FUSE filesystem creates one level of directories from
  749. # the archive names and of course "/" is not valid in a directory name.
  750. optional_archive_re = r"""
  751. (?:
  752. :: # "::" as separator
  753. (?P<archive>[^/]+) # archive name must not contain "/"
  754. )?$""" # must match until the end
  755. # regexes for misc. kinds of supported location specifiers:
  756. ssh_re = re.compile(r"""
  757. (?P<proto>ssh):// # ssh://
  758. """ + optional_user_re + r""" # user@ (optional)
  759. (?P<host>[^:/]+)(?::(?P<port>\d+))? # host or host:port
  760. """ + abs_path_re + optional_archive_re, re.VERBOSE) # path or path::archive
  761. file_re = re.compile(r"""
  762. (?P<proto>file):// # file://
  763. """ + path_re + optional_archive_re, re.VERBOSE) # path or path::archive
  764. # note: scp_re is also use for local pathes
  765. scp_re = re.compile(r"""
  766. (
  767. """ + optional_user_re + r""" # user@ (optional)
  768. (?P<host>[^:/]+): # host: (don't match / in host to disambiguate from file:)
  769. )? # user@host: part is optional
  770. """ + path_re + optional_archive_re, re.VERBOSE) # path with optional archive
  771. # get the repo from BORG_REPO env and the optional archive from param.
  772. # if the syntax requires giving REPOSITORY (see "borg mount"),
  773. # use "::" to let it use the env var.
  774. # if REPOSITORY argument is optional, it'll automatically use the env.
  775. env_re = re.compile(r""" # the repo part is fetched from BORG_REPO
  776. (?:::$) # just "::" is ok (when a pos. arg is required, no archive)
  777. | # or
  778. """ + optional_archive_re, re.VERBOSE) # archive name (optional, may be empty)
  779. def __init__(self, text=''):
  780. self.orig = text
  781. if not self.parse(self.orig):
  782. raise ValueError
  783. def parse(self, text):
  784. text = replace_placeholders(text)
  785. valid = self._parse(text)
  786. if valid:
  787. return True
  788. m = self.env_re.match(text)
  789. if not m:
  790. return False
  791. repo = os.environ.get('BORG_REPO')
  792. if repo is None:
  793. return False
  794. valid = self._parse(repo)
  795. if not valid:
  796. return False
  797. self.archive = m.group('archive')
  798. return True
  799. def _parse(self, text):
  800. def normpath_special(p):
  801. # avoid that normpath strips away our relative path hack and even makes p absolute
  802. relative = p.startswith('/./')
  803. p = os.path.normpath(p)
  804. return ('/.' + p) if relative else p
  805. m = self.ssh_re.match(text)
  806. if m:
  807. self.proto = m.group('proto')
  808. self.user = m.group('user')
  809. self.host = m.group('host')
  810. self.port = m.group('port') and int(m.group('port')) or None
  811. self.path = normpath_special(m.group('path'))
  812. self.archive = m.group('archive')
  813. return True
  814. m = self.file_re.match(text)
  815. if m:
  816. self.proto = m.group('proto')
  817. self.path = normpath_special(m.group('path'))
  818. self.archive = m.group('archive')
  819. return True
  820. m = self.scp_re.match(text)
  821. if m:
  822. self.user = m.group('user')
  823. self.host = m.group('host')
  824. self.path = normpath_special(m.group('path'))
  825. self.archive = m.group('archive')
  826. self.proto = self.host and 'ssh' or 'file'
  827. return True
  828. return False
  829. def __str__(self):
  830. items = [
  831. 'proto=%r' % self.proto,
  832. 'user=%r' % self.user,
  833. 'host=%r' % self.host,
  834. 'port=%r' % self.port,
  835. 'path=%r' % self.path,
  836. 'archive=%r' % self.archive,
  837. ]
  838. return ', '.join(items)
  839. def to_key_filename(self):
  840. name = re.sub('[^\w]', '_', self.path).strip('_')
  841. if self.proto != 'file':
  842. name = self.host + '__' + name
  843. return os.path.join(get_keys_dir(), name)
  844. def __repr__(self):
  845. return "Location(%s)" % self
  846. def canonical_path(self):
  847. if self.proto == 'file':
  848. return self.path
  849. else:
  850. if self.path and self.path.startswith('~'):
  851. path = '/' + self.path # /~/x = path x relative to home dir
  852. elif self.path and not self.path.startswith('/'):
  853. path = '/./' + self.path # /./x = path x relative to cwd
  854. else:
  855. path = self.path
  856. return 'ssh://{}{}{}{}'.format('{}@'.format(self.user) if self.user else '',
  857. self.host,
  858. ':{}'.format(self.port) if self.port else '',
  859. path)
  860. def location_validator(archive=None):
  861. def validator(text):
  862. try:
  863. loc = Location(text)
  864. except ValueError:
  865. raise argparse.ArgumentTypeError('Invalid location format: "%s"' % text) from None
  866. if archive is True and not loc.archive:
  867. raise argparse.ArgumentTypeError('"%s": No archive specified' % text)
  868. elif archive is False and loc.archive:
  869. raise argparse.ArgumentTypeError('"%s" No archive can be specified' % text)
  870. return loc
  871. return validator
  872. def archivename_validator():
  873. def validator(text):
  874. if '/' in text or '::' in text or not text:
  875. raise argparse.ArgumentTypeError('Invalid repository name: "%s"' % text)
  876. return text
  877. return validator
  878. def decode_dict(d, keys, encoding='utf-8', errors='surrogateescape'):
  879. for key in keys:
  880. if isinstance(d.get(key), bytes):
  881. d[key] = d[key].decode(encoding, errors)
  882. return d
  883. def remove_surrogates(s, errors='replace'):
  884. """Replace surrogates generated by fsdecode with '?'
  885. """
  886. return s.encode('utf-8', errors).decode('utf-8')
  887. _safe_re = re.compile(r'^((\.\.)?/+)+')
  888. def make_path_safe(path):
  889. """Make path safe by making it relative and local
  890. """
  891. return _safe_re.sub('', path) or '.'
  892. def daemonize():
  893. """Detach process from controlling terminal and run in background
  894. """
  895. pid = os.fork()
  896. if pid:
  897. os._exit(0)
  898. os.setsid()
  899. pid = os.fork()
  900. if pid:
  901. os._exit(0)
  902. os.chdir('/')
  903. os.close(0)
  904. os.close(1)
  905. os.close(2)
  906. fd = os.open(os.devnull, os.O_RDWR)
  907. os.dup2(fd, 0)
  908. os.dup2(fd, 1)
  909. os.dup2(fd, 2)
  910. class StableDict(dict):
  911. """A dict subclass with stable items() ordering"""
  912. def items(self):
  913. return sorted(super().items())
  914. def is_slow_msgpack():
  915. return msgpack.Packer is msgpack.fallback.Packer
  916. FALSISH = ('No', 'NO', 'no', 'N', 'n', '0', )
  917. TRUISH = ('Yes', 'YES', 'yes', 'Y', 'y', '1', )
  918. DEFAULTISH = ('Default', 'DEFAULT', 'default', 'D', 'd', '', )
  919. def yes(msg=None, false_msg=None, true_msg=None, default_msg=None,
  920. retry_msg=None, invalid_msg=None, env_msg='{} (from {})',
  921. falsish=FALSISH, truish=TRUISH, defaultish=DEFAULTISH,
  922. default=False, retry=True, env_var_override=None, ofile=None, input=input, prompt=True):
  923. """Output <msg> (usually a question) and let user input an answer.
  924. Qualifies the answer according to falsish, truish and defaultish as True, False or <default>.
  925. If it didn't qualify and retry is False (no retries wanted), return the default [which
  926. defaults to False]. If retry is True let user retry answering until answer is qualified.
  927. If env_var_override is given and this var is present in the environment, do not ask
  928. the user, but just use the env var contents as answer as if it was typed in.
  929. Otherwise read input from stdin and proceed as normal.
  930. If EOF is received instead an input or an invalid input without retry possibility,
  931. return default.
  932. :param msg: introducing message to output on ofile, no \n is added [None]
  933. :param retry_msg: retry message to output on ofile, no \n is added [None]
  934. :param false_msg: message to output before returning False [None]
  935. :param true_msg: message to output before returning True [None]
  936. :param default_msg: message to output before returning a <default> [None]
  937. :param invalid_msg: message to output after a invalid answer was given [None]
  938. :param env_msg: message to output when using input from env_var_override ['{} (from {})'],
  939. needs to have 2 placeholders for answer and env var name
  940. :param falsish: sequence of answers qualifying as False
  941. :param truish: sequence of answers qualifying as True
  942. :param defaultish: sequence of answers qualifying as <default>
  943. :param default: default return value (defaultish answer was given or no-answer condition) [False]
  944. :param retry: if True and input is incorrect, retry. Otherwise return default. [True]
  945. :param env_var_override: environment variable name [None]
  946. :param ofile: output stream [sys.stderr]
  947. :param input: input function [input from builtins]
  948. :return: boolean answer value, True or False
  949. """
  950. # note: we do not assign sys.stderr as default above, so it is
  951. # really evaluated NOW, not at function definition time.
  952. if ofile is None:
  953. ofile = sys.stderr
  954. if default not in (True, False):
  955. raise ValueError("invalid default value, must be True or False")
  956. if msg:
  957. print(msg, file=ofile, end='', flush=True)
  958. while True:
  959. answer = None
  960. if env_var_override:
  961. answer = os.environ.get(env_var_override)
  962. if answer is not None and env_msg:
  963. print(env_msg.format(answer, env_var_override), file=ofile)
  964. if answer is None:
  965. if not prompt:
  966. return default
  967. try:
  968. answer = input()
  969. except EOFError:
  970. # avoid defaultish[0], defaultish could be empty
  971. answer = truish[0] if default else falsish[0]
  972. if answer in defaultish:
  973. if default_msg:
  974. print(default_msg, file=ofile)
  975. return default
  976. if answer in truish:
  977. if true_msg:
  978. print(true_msg, file=ofile)
  979. return True
  980. if answer in falsish:
  981. if false_msg:
  982. print(false_msg, file=ofile)
  983. return False
  984. # if we get here, the answer was invalid
  985. if invalid_msg:
  986. print(invalid_msg, file=ofile)
  987. if not retry:
  988. return default
  989. if retry_msg:
  990. print(retry_msg, file=ofile, end='', flush=True)
  991. # in case we used an environment variable and it gave an invalid answer, do not use it again:
  992. env_var_override = None
  993. def ellipsis_truncate(msg, space):
  994. """
  995. shorten a long string by adding ellipsis between it and return it, example:
  996. this_is_a_very_long_string -------> this_is..._string
  997. """
  998. from .platform import swidth
  999. ellipsis_width = swidth('...')
  1000. msg_width = swidth(msg)
  1001. if space < 8:
  1002. # if there is very little space, just show ...
  1003. return '...' + ' ' * (space - ellipsis_width)
  1004. if space < ellipsis_width + msg_width:
  1005. return '%s...%s' % (swidth_slice(msg, space // 2 - ellipsis_width),
  1006. swidth_slice(msg, -space // 2))
  1007. return msg + ' ' * (space - msg_width)
  1008. class ProgressIndicatorBase:
  1009. LOGGER = 'borg.output.progress'
  1010. def __init__(self):
  1011. self.handler = None
  1012. self.logger = logging.getLogger(self.LOGGER)
  1013. # If there are no handlers, set one up explicitly because the
  1014. # terminator and propagation needs to be set. If there are,
  1015. # they must have been set up by BORG_LOGGING_CONF: skip setup.
  1016. if not self.logger.handlers:
  1017. self.handler = logging.StreamHandler(stream=sys.stderr)
  1018. self.handler.setLevel(logging.INFO)
  1019. self.handler.terminator = '\r'
  1020. self.logger.addHandler(self.handler)
  1021. if self.logger.level == logging.NOTSET:
  1022. self.logger.setLevel(logging.WARN)
  1023. self.logger.propagate = False
  1024. def __del__(self):
  1025. if self.handler is not None:
  1026. self.logger.removeHandler(self.handler)
  1027. self.handler.close()
  1028. def justify_to_terminal_size(message):
  1029. terminal_space = get_terminal_size(fallback=(-1, -1))[0]
  1030. # justify only if we are outputting to a terminal
  1031. if terminal_space != -1:
  1032. return message.ljust(terminal_space)
  1033. return message
  1034. class ProgressIndicatorMessage(ProgressIndicatorBase):
  1035. def output(self, msg):
  1036. self.logger.info(justify_to_terminal_size(msg))
  1037. def finish(self):
  1038. self.output('')
  1039. class ProgressIndicatorPercent(ProgressIndicatorBase):
  1040. def __init__(self, total=0, step=5, start=0, msg="%3.0f%%"):
  1041. """
  1042. Percentage-based progress indicator
  1043. :param total: total amount of items
  1044. :param step: step size in percent
  1045. :param start: at which percent value to start
  1046. :param msg: output message, must contain one %f placeholder for the percentage
  1047. """
  1048. self.counter = 0 # 0 .. (total-1)
  1049. self.total = total
  1050. self.trigger_at = start # output next percentage value when reaching (at least) this
  1051. self.step = step
  1052. self.msg = msg
  1053. super().__init__()
  1054. def progress(self, current=None, increase=1):
  1055. if current is not None:
  1056. self.counter = current
  1057. pct = self.counter * 100 / self.total
  1058. self.counter += increase
  1059. if pct >= self.trigger_at:
  1060. self.trigger_at += self.step
  1061. return pct
  1062. def show(self, current=None, increase=1, info=None):
  1063. """
  1064. Show and output the progress message
  1065. :param current: set the current percentage [None]
  1066. :param increase: increase the current percentage [None]
  1067. :param info: array of strings to be formatted with msg [None]
  1068. """
  1069. pct = self.progress(current, increase)
  1070. if pct is not None:
  1071. # truncate the last argument, if no space is available
  1072. if info is not None:
  1073. # no need to truncate if we're not outputing to a terminal
  1074. terminal_space = get_terminal_size(fallback=(-1, -1))[0]
  1075. if terminal_space != -1:
  1076. space = terminal_space - len(self.msg % tuple([pct] + info[:-1] + ['']))
  1077. info[-1] = ellipsis_truncate(info[-1], space)
  1078. return self.output(self.msg % tuple([pct] + info), justify=False)
  1079. return self.output(self.msg % pct)
  1080. def output(self, message, justify=True):
  1081. if justify:
  1082. message = justify_to_terminal_size(message)
  1083. self.logger.info(message)
  1084. def finish(self):
  1085. self.output('')
  1086. class ProgressIndicatorEndless:
  1087. def __init__(self, step=10, file=None):
  1088. """
  1089. Progress indicator (long row of dots)
  1090. :param step: every Nth call, call the func
  1091. :param file: output file, default: sys.stderr
  1092. """
  1093. self.counter = 0 # call counter
  1094. self.triggered = 0 # increases 1 per trigger event
  1095. self.step = step # trigger every <step> calls
  1096. if file is None:
  1097. file = sys.stderr
  1098. self.file = file
  1099. def progress(self):
  1100. self.counter += 1
  1101. trigger = self.counter % self.step == 0
  1102. if trigger:
  1103. self.triggered += 1
  1104. return trigger
  1105. def show(self):
  1106. trigger = self.progress()
  1107. if trigger:
  1108. return self.output(self.triggered)
  1109. def output(self, triggered):
  1110. print('.', end='', file=self.file, flush=True)
  1111. def finish(self):
  1112. print(file=self.file)
  1113. def sysinfo():
  1114. info = []
  1115. info.append('Platform: %s' % (' '.join(platform.uname()), ))
  1116. if sys.platform.startswith('linux'):
  1117. info.append('Linux: %s %s %s' % platform.linux_distribution())
  1118. info.append('Borg: %s Python: %s %s' % (borg_version, platform.python_implementation(), platform.python_version()))
  1119. info.append('PID: %d CWD: %s' % (os.getpid(), os.getcwd()))
  1120. info.append('sys.argv: %r' % sys.argv)
  1121. info.append('SSH_ORIGINAL_COMMAND: %r' % os.environ.get('SSH_ORIGINAL_COMMAND'))
  1122. info.append('')
  1123. return '\n'.join(info)
  1124. def log_multi(*msgs, level=logging.INFO, logger=logger):
  1125. """
  1126. log multiple lines of text, each line by a separate logging call for cosmetic reasons
  1127. each positional argument may be a single or multiple lines (separated by newlines) of text.
  1128. """
  1129. lines = []
  1130. for msg in msgs:
  1131. lines.extend(msg.splitlines())
  1132. for line in lines:
  1133. logger.log(level, line)
  1134. class BaseFormatter:
  1135. FIXED_KEYS = {
  1136. # Formatting aids
  1137. 'LF': '\n',
  1138. 'SPACE': ' ',
  1139. 'TAB': '\t',
  1140. 'CR': '\r',
  1141. 'NUL': '\0',
  1142. 'NEWLINE': os.linesep,
  1143. 'NL': os.linesep,
  1144. }
  1145. def get_item_data(self, item):
  1146. raise NotImplementedError
  1147. def format_item(self, item):
  1148. return self.format.format_map(self.get_item_data(item))
  1149. @staticmethod
  1150. def keys_help():
  1151. return " - NEWLINE: OS dependent line separator\n" \
  1152. " - NL: alias of NEWLINE\n" \
  1153. " - NUL: NUL character for creating print0 / xargs -0 like output, see barchive/bpath\n" \
  1154. " - SPACE\n" \
  1155. " - TAB\n" \
  1156. " - CR\n" \
  1157. " - LF"
  1158. class ArchiveFormatter(BaseFormatter):
  1159. def __init__(self, format):
  1160. self.format = partial_format(format, self.FIXED_KEYS)
  1161. def get_item_data(self, archive):
  1162. return {
  1163. 'barchive': archive.name,
  1164. 'archive': remove_surrogates(archive.name),
  1165. 'id': bin_to_hex(archive.id),
  1166. 'time': format_time(to_localtime(archive.ts)),
  1167. }
  1168. @staticmethod
  1169. def keys_help():
  1170. return " - archive: archive name interpreted as text (might be missing non-text characters, see barchive)\n" \
  1171. " - barchive: verbatim archive name, can contain any character except NUL\n" \
  1172. " - time: time of creation of the archive\n" \
  1173. " - id: internal ID of the archive"
  1174. class ItemFormatter(BaseFormatter):
  1175. KEY_DESCRIPTIONS = {
  1176. 'bpath': 'verbatim POSIX path, can contain any character except NUL',
  1177. 'path': 'path interpreted as text (might be missing non-text characters, see bpath)',
  1178. 'source': 'link target for links (identical to linktarget)',
  1179. 'extra': 'prepends {source} with " -> " for soft links and " link to " for hard links',
  1180. 'csize': 'compressed size',
  1181. 'num_chunks': 'number of chunks in this file',
  1182. 'unique_chunks': 'number of unique chunks in this file',
  1183. 'health': 'either "healthy" (file ok) or "broken" (if file has all-zero replacement chunks)',
  1184. }
  1185. KEY_GROUPS = (
  1186. ('type', 'mode', 'uid', 'gid', 'user', 'group', 'path', 'bpath', 'source', 'linktarget', 'flags'),
  1187. ('size', 'csize', 'num_chunks', 'unique_chunks'),
  1188. ('mtime', 'ctime', 'atime', 'isomtime', 'isoctime', 'isoatime'),
  1189. tuple(sorted(hashlib.algorithms_guaranteed)),
  1190. ('archiveid', 'archivename', 'extra'),
  1191. ('health', )
  1192. )
  1193. @classmethod
  1194. def available_keys(cls):
  1195. class FakeArchive:
  1196. fpr = name = ""
  1197. from .item import Item
  1198. fake_item = Item(mode=0, path='', user='', group='', mtime=0, uid=0, gid=0)
  1199. formatter = cls(FakeArchive, "")
  1200. keys = []
  1201. keys.extend(formatter.call_keys.keys())
  1202. keys.extend(formatter.get_item_data(fake_item).keys())
  1203. return keys
  1204. @classmethod
  1205. def keys_help(cls):
  1206. help = []
  1207. keys = cls.available_keys()
  1208. for key in cls.FIXED_KEYS:
  1209. keys.remove(key)
  1210. for group in cls.KEY_GROUPS:
  1211. for key in group:
  1212. keys.remove(key)
  1213. text = " - " + key
  1214. if key in cls.KEY_DESCRIPTIONS:
  1215. text += ": " + cls.KEY_DESCRIPTIONS[key]
  1216. help.append(text)
  1217. help.append("")
  1218. assert not keys, str(keys)
  1219. return "\n".join(help)
  1220. def __init__(self, archive, format):
  1221. self.archive = archive
  1222. static_keys = {
  1223. 'archivename': archive.name,
  1224. 'archiveid': archive.fpr,
  1225. }
  1226. static_keys.update(self.FIXED_KEYS)
  1227. self.format = partial_format(format, static_keys)
  1228. self.format_keys = {f[1] for f in Formatter().parse(format)}
  1229. self.call_keys = {
  1230. 'size': self.calculate_size,
  1231. 'csize': self.calculate_csize,
  1232. 'num_chunks': self.calculate_num_chunks,
  1233. 'unique_chunks': self.calculate_unique_chunks,
  1234. 'isomtime': partial(self.format_time, 'mtime'),
  1235. 'isoctime': partial(self.format_time, 'ctime'),
  1236. 'isoatime': partial(self.format_time, 'atime'),
  1237. 'mtime': partial(self.time, 'mtime'),
  1238. 'ctime': partial(self.time, 'ctime'),
  1239. 'atime': partial(self.time, 'atime'),
  1240. }
  1241. for hash_function in hashlib.algorithms_guaranteed:
  1242. self.add_key(hash_function, partial(self.hash_item, hash_function))
  1243. self.used_call_keys = set(self.call_keys) & self.format_keys
  1244. self.item_data = static_keys
  1245. def add_key(self, key, callable_with_item):
  1246. self.call_keys[key] = callable_with_item
  1247. self.used_call_keys = set(self.call_keys) & self.format_keys
  1248. def get_item_data(self, item):
  1249. mode = stat.filemode(item.mode)
  1250. item_type = mode[0]
  1251. item_data = self.item_data
  1252. source = item.get('source', '')
  1253. extra = ''
  1254. if source:
  1255. source = remove_surrogates(source)
  1256. if item_type == 'l':
  1257. extra = ' -> %s' % source
  1258. else:
  1259. mode = 'h' + mode[1:]
  1260. extra = ' link to %s' % source
  1261. item_data['type'] = item_type
  1262. item_data['mode'] = mode
  1263. item_data['user'] = item.user or item.uid
  1264. item_data['group'] = item.group or item.gid
  1265. item_data['uid'] = item.uid
  1266. item_data['gid'] = item.gid
  1267. item_data['path'] = remove_surrogates(item.path)
  1268. item_data['bpath'] = item.path
  1269. item_data['source'] = source
  1270. item_data['linktarget'] = source
  1271. item_data['extra'] = extra
  1272. item_data['flags'] = item.get('bsdflags')
  1273. item_data['health'] = 'broken' if 'chunks_healthy' in item else 'healthy'
  1274. for key in self.used_call_keys:
  1275. item_data[key] = self.call_keys[key](item)
  1276. return item_data
  1277. def calculate_num_chunks(self, item):
  1278. return len(item.get('chunks', []))
  1279. def calculate_unique_chunks(self, item):
  1280. chunk_index = self.archive.cache.chunks
  1281. return sum(1 for c in item.get('chunks', []) if chunk_index[c.id].refcount == 1)
  1282. def calculate_size(self, item):
  1283. return sum(c.size for c in item.get('chunks', []))
  1284. def calculate_csize(self, item):
  1285. return sum(c.csize for c in item.get('chunks', []))
  1286. def hash_item(self, hash_function, item):
  1287. if 'chunks' not in item:
  1288. return ""
  1289. hash = hashlib.new(hash_function)
  1290. for _, data in self.archive.pipeline.fetch_many([c.id for c in item.chunks]):
  1291. hash.update(data)
  1292. return hash.hexdigest()
  1293. def format_time(self, key, item):
  1294. return format_time(safe_timestamp(item.get(key) or item.mtime))
  1295. def time(self, key, item):
  1296. return safe_timestamp(item.get(key) or item.mtime)
  1297. class ChunkIteratorFileWrapper:
  1298. """File-like wrapper for chunk iterators"""
  1299. def __init__(self, chunk_iterator):
  1300. self.chunk_iterator = chunk_iterator
  1301. self.chunk_offset = 0
  1302. self.chunk = b''
  1303. self.exhausted = False
  1304. def _refill(self):
  1305. remaining = len(self.chunk) - self.chunk_offset
  1306. if not remaining:
  1307. try:
  1308. chunk = next(self.chunk_iterator)
  1309. self.chunk = memoryview(chunk.data)
  1310. except StopIteration:
  1311. self.exhausted = True
  1312. return 0 # EOF
  1313. self.chunk_offset = 0
  1314. remaining = len(self.chunk)
  1315. return remaining
  1316. def _read(self, nbytes):
  1317. if not nbytes:
  1318. return b''
  1319. remaining = self._refill()
  1320. will_read = min(remaining, nbytes)
  1321. self.chunk_offset += will_read
  1322. return self.chunk[self.chunk_offset - will_read:self.chunk_offset]
  1323. def read(self, nbytes):
  1324. parts = []
  1325. while nbytes and not self.exhausted:
  1326. read_data = self._read(nbytes)
  1327. nbytes -= len(read_data)
  1328. parts.append(read_data)
  1329. return b''.join(parts)
  1330. def open_item(archive, item):
  1331. """Return file-like object for archived item (with chunks)."""
  1332. chunk_iterator = archive.pipeline.fetch_many([c.id for c in item.chunks])
  1333. return ChunkIteratorFileWrapper(chunk_iterator)
  1334. def file_status(mode):
  1335. if stat.S_ISREG(mode):
  1336. return 'A'
  1337. elif stat.S_ISDIR(mode):
  1338. return 'd'
  1339. elif stat.S_ISBLK(mode):
  1340. return 'b'
  1341. elif stat.S_ISCHR(mode):
  1342. return 'c'
  1343. elif stat.S_ISLNK(mode):
  1344. return 's'
  1345. elif stat.S_ISFIFO(mode):
  1346. return 'f'
  1347. return '?'
  1348. def chunkit(it, size):
  1349. """
  1350. Chunk an iterator <it> into pieces of <size>.
  1351. >>> list(chunker('ABCDEFG', 3))
  1352. [['A', 'B', 'C'], ['D', 'E', 'F'], ['G']]
  1353. """
  1354. iterable = iter(it)
  1355. return iter(lambda: list(islice(iterable, size)), [])
  1356. def consume(iterator, n=None):
  1357. """Advance the iterator n-steps ahead. If n is none, consume entirely."""
  1358. # Use functions that consume iterators at C speed.
  1359. if n is None:
  1360. # feed the entire iterator into a zero-length deque
  1361. deque(iterator, maxlen=0)
  1362. else:
  1363. # advance to the empty slice starting at position n
  1364. next(islice(iterator, n, n), None)
  1365. # GenericDirEntry, scandir_generic (c) 2012 Ben Hoyt
  1366. # from the python-scandir package (3-clause BSD license, just like us, so no troubles here)
  1367. # note: simplified version
  1368. class GenericDirEntry:
  1369. __slots__ = ('name', '_scandir_path', '_path')
  1370. def __init__(self, scandir_path, name):
  1371. self._scandir_path = scandir_path
  1372. self.name = name
  1373. self._path = None
  1374. @property
  1375. def path(self):
  1376. if self._path is None:
  1377. self._path = os.path.join(self._scandir_path, self.name)
  1378. return self._path
  1379. def stat(self, follow_symlinks=True):
  1380. assert not follow_symlinks
  1381. return os.lstat(self.path)
  1382. def _check_type(self, type):
  1383. st = self.stat(False)
  1384. return stat.S_IFMT(st.st_mode) == type
  1385. def is_dir(self, follow_symlinks=True):
  1386. assert not follow_symlinks
  1387. return self._check_type(stat.S_IFDIR)
  1388. def is_file(self, follow_symlinks=True):
  1389. assert not follow_symlinks
  1390. return self._check_type(stat.S_IFREG)
  1391. def is_symlink(self):
  1392. return self._check_type(stat.S_IFLNK)
  1393. def inode(self):
  1394. st = self.stat(False)
  1395. return st.st_ino
  1396. def __repr__(self):
  1397. return '<{0}: {1!r}>'.format(self.__class__.__name__, self.path)
  1398. def scandir_generic(path='.'):
  1399. """Like os.listdir(), but yield DirEntry objects instead of returning a list of names."""
  1400. for name in sorted(os.listdir(path)):
  1401. yield GenericDirEntry(path, name)
  1402. try:
  1403. from os import scandir
  1404. except ImportError:
  1405. try:
  1406. # Try python-scandir on Python 3.4
  1407. from scandir import scandir
  1408. except ImportError:
  1409. # If python-scandir is not installed, then use a version that is just as slow as listdir.
  1410. scandir = scandir_generic
  1411. def scandir_inorder(path='.'):
  1412. return sorted(scandir(path), key=lambda dirent: dirent.inode())
  1413. def clean_lines(lines, lstrip=None, rstrip=None, remove_empty=True, remove_comments=True):
  1414. """
  1415. clean lines (usually read from a config file):
  1416. 1. strip whitespace (left and right), 2. remove empty lines, 3. remove comments.
  1417. note: only "pure comment lines" are supported, no support for "trailing comments".
  1418. :param lines: input line iterator (e.g. list or open text file) that gives unclean input lines
  1419. :param lstrip: lstrip call arguments or False, if lstripping is not desired
  1420. :param rstrip: rstrip call arguments or False, if rstripping is not desired
  1421. :param remove_comments: remove comment lines (lines starting with "#")
  1422. :param remove_empty: remove empty lines
  1423. :return: yields processed lines
  1424. """
  1425. for line in lines:
  1426. if lstrip is not False:
  1427. line = line.lstrip(lstrip)
  1428. if rstrip is not False:
  1429. line = line.rstrip(rstrip)
  1430. if remove_empty and not line:
  1431. continue
  1432. if remove_comments and line.startswith('#'):
  1433. continue
  1434. yield line
  1435. class CompressionDecider1:
  1436. def __init__(self, compression, compression_files):
  1437. """
  1438. Initialize a CompressionDecider instance (and read config files, if needed).
  1439. :param compression: default CompressionSpec (e.g. from --compression option)
  1440. :param compression_files: list of compression config files (e.g. from --compression-from) or
  1441. a list of other line iterators
  1442. """
  1443. self.compression = compression
  1444. if not compression_files:
  1445. self.matcher = None
  1446. else:
  1447. self.matcher = PatternMatcher(fallback=compression)
  1448. for file in compression_files:
  1449. try:
  1450. for line in clean_lines(file):
  1451. try:
  1452. compr_spec, fn_pattern = line.split(':', 1)
  1453. except:
  1454. continue
  1455. self.matcher.add([parse_pattern(fn_pattern)], CompressionSpec(compr_spec))
  1456. finally:
  1457. if hasattr(file, 'close'):
  1458. file.close()
  1459. def decide(self, path):
  1460. if self.matcher is not None:
  1461. return self.matcher.match(path)
  1462. return self.compression
  1463. class CompressionDecider2:
  1464. logger = create_logger('borg.debug.file-compression')
  1465. def __init__(self, compression):
  1466. self.compression = compression
  1467. def decide(self, chunk):
  1468. # nothing fancy here yet: we either use what the metadata says or the default
  1469. # later, we can decide based on the chunk data also.
  1470. # if we compress the data here to decide, we can even update the chunk data
  1471. # and modify the metadata as desired.
  1472. compr_spec = chunk.meta.get('compress', self.compression)
  1473. if compr_spec['name'] == 'auto':
  1474. # we did not decide yet, use heuristic:
  1475. compr_spec, chunk = self.heuristic_lz4(compr_spec, chunk)
  1476. return compr_spec, chunk
  1477. def heuristic_lz4(self, compr_args, chunk):
  1478. from .compress import get_compressor
  1479. meta, data = chunk
  1480. lz4 = get_compressor('lz4')
  1481. cdata = lz4.compress(data)
  1482. data_len = len(data)
  1483. cdata_len = len(cdata)
  1484. if cdata_len < data_len:
  1485. compr_spec = compr_args['spec']
  1486. else:
  1487. # uncompressible - we could have a special "uncompressible compressor"
  1488. # that marks such data as uncompressible via compression-type metadata.
  1489. compr_spec = CompressionSpec('none')
  1490. compr_args.update(compr_spec)
  1491. self.logger.debug("len(data) == %d, len(lz4(data)) == %d, choosing %s", data_len, cdata_len, compr_spec)
  1492. return compr_args, Chunk(data, **meta)
  1493. class ErrorIgnoringTextIOWrapper(io.TextIOWrapper):
  1494. def read(self, n):
  1495. if not self.closed:
  1496. try:
  1497. return super().read(n)
  1498. except BrokenPipeError:
  1499. try:
  1500. super().close()
  1501. except OSError:
  1502. pass
  1503. return ''
  1504. def write(self, s):
  1505. if not self.closed:
  1506. try:
  1507. return super().write(s)
  1508. except BrokenPipeError:
  1509. try:
  1510. super().close()
  1511. except OSError:
  1512. pass
  1513. return len(s)
  1514. class SignalException(BaseException):
  1515. """base class for all signal-based exceptions"""
  1516. class SigHup(SignalException):
  1517. """raised on SIGHUP signal"""
  1518. class SigTerm(SignalException):
  1519. """raised on SIGTERM signal"""
  1520. @contextlib.contextmanager
  1521. def signal_handler(sig, handler):
  1522. """
  1523. when entering context, set up signal handler <handler> for signal <sig>.
  1524. when leaving context, restore original signal handler.
  1525. <sig> can bei either a str when giving a signal.SIGXXX attribute name (it
  1526. won't crash if the attribute name does not exist as some names are platform
  1527. specific) or a int, when giving a signal number.
  1528. <handler> is any handler value as accepted by the signal.signal(sig, handler).
  1529. """
  1530. if isinstance(sig, str):
  1531. sig = getattr(signal, sig, None)
  1532. if sig is not None:
  1533. orig_handler = signal.signal(sig, handler)
  1534. try:
  1535. yield
  1536. finally:
  1537. if sig is not None:
  1538. signal.signal(sig, orig_handler)
  1539. def raising_signal_handler(exc_cls):
  1540. def handler(sig_no, frame):
  1541. # setting SIG_IGN avoids that an incoming second signal of this
  1542. # kind would raise a 2nd exception while we still process the
  1543. # exception handler for exc_cls for the 1st signal.
  1544. signal.signal(sig_no, signal.SIG_IGN)
  1545. raise exc_cls
  1546. return handler
  1547. def swidth_slice(string, max_width):
  1548. """
  1549. Return a slice of *max_width* cells from *string*.
  1550. Negative *max_width* means from the end of string.
  1551. *max_width* is in units of character cells (or "columns").
  1552. Latin characters are usually one cell wide, many CJK characters are two cells wide.
  1553. """
  1554. from .platform import swidth
  1555. reverse = max_width < 0
  1556. max_width = abs(max_width)
  1557. if reverse:
  1558. string = reversed(string)
  1559. current_swidth = 0
  1560. result = []
  1561. for character in string:
  1562. current_swidth += swidth(character)
  1563. if current_swidth > max_width:
  1564. break
  1565. result.append(character)
  1566. if reverse:
  1567. result.reverse()
  1568. return ''.join(result)