helpers.py 35 KB

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