helpers.py 45 KB

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