logging_util.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. __package__ = 'archivebox'
  2. import re
  3. import os
  4. import sys
  5. import time
  6. import argparse
  7. import logging
  8. import signal
  9. from multiprocessing import Process
  10. from datetime import datetime
  11. from dataclasses import dataclass
  12. from typing import Optional, List, Dict, Union, IO, TYPE_CHECKING
  13. if TYPE_CHECKING:
  14. from .index.schema import Link, ArchiveResult
  15. from .util import enforce_types
  16. from .config import (
  17. ConfigDict,
  18. PYTHON_ENCODING,
  19. ANSI,
  20. IS_TTY,
  21. SHOW_PROGRESS,
  22. TERM_WIDTH,
  23. OUTPUT_DIR,
  24. SOURCES_DIR_NAME,
  25. HTML_INDEX_FILENAME,
  26. stderr,
  27. )
  28. @dataclass
  29. class RuntimeStats:
  30. """mutable stats counter for logging archiving timing info to CLI output"""
  31. skipped: int = 0
  32. succeeded: int = 0
  33. failed: int = 0
  34. parse_start_ts: Optional[datetime] = None
  35. parse_end_ts: Optional[datetime] = None
  36. index_start_ts: Optional[datetime] = None
  37. index_end_ts: Optional[datetime] = None
  38. archiving_start_ts: Optional[datetime] = None
  39. archiving_end_ts: Optional[datetime] = None
  40. # globals are bad, mmkay
  41. _LAST_RUN_STATS = RuntimeStats()
  42. class SmartFormatter(argparse.HelpFormatter):
  43. """Patched formatter that prints newlines in argparse help strings"""
  44. def _split_lines(self, text, width):
  45. if '\n' in text:
  46. return text.splitlines()
  47. return argparse.HelpFormatter._split_lines(self, text, width)
  48. def reject_stdin(caller: str, stdin: Optional[IO]=sys.stdin) -> None:
  49. """Tell the user they passed stdin to a command that doesn't accept it"""
  50. if stdin and not stdin.isatty():
  51. stdin_raw_text = stdin.read().strip()
  52. if stdin_raw_text:
  53. stderr(f'[X] The "{caller}" command does not accept stdin.', color='red')
  54. stderr(f' Run archivebox "{caller} --help" to see usage and examples.')
  55. stderr()
  56. raise SystemExit(1)
  57. def accept_stdin(stdin: Optional[IO]=sys.stdin) -> Optional[str]:
  58. """accept any standard input and return it as a string or None"""
  59. if not stdin:
  60. return None
  61. elif stdin and not stdin.isatty():
  62. stdin_str = stdin.read().strip()
  63. return stdin_str or None
  64. return None
  65. class TimedProgress:
  66. """Show a progress bar and measure elapsed time until .end() is called"""
  67. def __init__(self, seconds, prefix=''):
  68. if SHOW_PROGRESS:
  69. self.p = Process(target=progress_bar, args=(seconds, prefix))
  70. self.p.start()
  71. self.stats = {'start_ts': datetime.now(), 'end_ts': None}
  72. def end(self):
  73. """immediately end progress, clear the progressbar line, and save end_ts"""
  74. end_ts = datetime.now()
  75. self.stats['end_ts'] = end_ts
  76. if SHOW_PROGRESS:
  77. # terminate if we havent already terminated
  78. self.p.terminate()
  79. self.p.join()
  80. self.p.close()
  81. # clear whole terminal line
  82. try:
  83. sys.stdout.write('\r{}{}\r'.format((' ' * TERM_WIDTH()), ANSI['reset']))
  84. except (IOError, BrokenPipeError):
  85. # ignore when the parent proc has stopped listening to our stdout
  86. pass
  87. @enforce_types
  88. def progress_bar(seconds: int, prefix: str='') -> None:
  89. """show timer in the form of progress bar, with percentage and seconds remaining"""
  90. chunk = '█' if PYTHON_ENCODING == 'UTF-8' else '#'
  91. chunks = TERM_WIDTH() - len(prefix) - 20 # number of progress chunks to show (aka max bar width)
  92. try:
  93. for s in range(seconds * chunks):
  94. chunks = TERM_WIDTH() - len(prefix) - 20
  95. progress = s / chunks / seconds * 100
  96. bar_width = round(progress/(100/chunks))
  97. # ████████████████████ 0.9% (1/60sec)
  98. sys.stdout.write('\r{0}{1}{2}{3} {4}% ({5}/{6}sec)'.format(
  99. prefix,
  100. ANSI['green'],
  101. (chunk * bar_width).ljust(chunks),
  102. ANSI['reset'],
  103. round(progress, 1),
  104. round(s/chunks),
  105. seconds,
  106. ))
  107. sys.stdout.flush()
  108. time.sleep(1 / chunks)
  109. # ██████████████████████████████████ 100.0% (60/60sec)
  110. sys.stdout.write('\r{0}{1}{2}{3} {4}% ({5}/{6}sec)\n'.format(
  111. prefix,
  112. ANSI['red'],
  113. chunk * chunks,
  114. ANSI['reset'],
  115. 100.0,
  116. seconds,
  117. seconds,
  118. ))
  119. sys.stdout.flush()
  120. except (KeyboardInterrupt, BrokenPipeError):
  121. print()
  122. pass
  123. def log_cli_command(subcommand: str, subcommand_args: List[str], stdin: Optional[str], pwd: str):
  124. from .config import VERSION, ANSI
  125. cmd = ' '.join(('archivebox', subcommand, *subcommand_args))
  126. stdin_hint = ' < /dev/stdin' if not stdin.isatty() else ''
  127. stderr('{black}[i] [{now}] ArchiveBox v{VERSION}: {cmd}{stdin_hint}{reset}'.format(
  128. now=datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
  129. VERSION=VERSION,
  130. cmd=cmd,
  131. stdin_hint=stdin_hint,
  132. **ANSI,
  133. ))
  134. stderr('{black} > {pwd}{reset}'.format(pwd=pwd, **ANSI))
  135. stderr()
  136. ### Parsing Stage
  137. def log_importing_started(urls: Union[str, List[str]], depth: int, index_only: bool):
  138. _LAST_RUN_STATS.parse_start_ts = datetime.now()
  139. print('{green}[+] [{}] Adding {} links to index (crawl depth={}){}...{reset}'.format(
  140. _LAST_RUN_STATS.parse_start_ts.strftime('%Y-%m-%d %H:%M:%S'),
  141. len(urls) if isinstance(urls, list) else len(urls.split('\n')),
  142. depth,
  143. ' (index only)' if index_only else '',
  144. **ANSI,
  145. ))
  146. def log_source_saved(source_file: str):
  147. print(' > Saved verbatim input to {}/{}'.format(SOURCES_DIR_NAME, source_file.rsplit('/', 1)[-1]))
  148. def log_parsing_finished(num_parsed: int, parser_name: str):
  149. _LAST_RUN_STATS.parse_end_ts = datetime.now()
  150. print(' > Parsed {} URLs from input ({})'.format(num_parsed, parser_name))
  151. def log_deduping_finished(num_new_links: int):
  152. print(' > Found {} new URLs not already in index'.format(num_new_links))
  153. def log_crawl_started(new_links):
  154. print('{lightred}[*] Starting crawl of {} sites 1 hop out from starting point{reset}'.format(len(new_links), **ANSI))
  155. ### Indexing Stage
  156. def log_indexing_process_started(num_links: int):
  157. start_ts = datetime.now()
  158. _LAST_RUN_STATS.index_start_ts = start_ts
  159. print()
  160. print('{black}[*] [{}] Writing {} links to main index...{reset}'.format(
  161. start_ts.strftime('%Y-%m-%d %H:%M:%S'),
  162. num_links,
  163. **ANSI,
  164. ))
  165. def log_indexing_process_finished():
  166. end_ts = datetime.now()
  167. _LAST_RUN_STATS.index_end_ts = end_ts
  168. def log_indexing_started(out_path: str):
  169. if IS_TTY:
  170. sys.stdout.write(f' > {out_path}')
  171. def log_indexing_finished(out_path: str):
  172. print(f'\r √ {out_path}')
  173. ### Archiving Stage
  174. def log_archiving_started(num_links: int, resume: Optional[float]=None):
  175. start_ts = datetime.now()
  176. _LAST_RUN_STATS.archiving_start_ts = start_ts
  177. print()
  178. if resume:
  179. print('{green}[▶] [{}] Resuming archive updating for {} pages starting from {}...{reset}'.format(
  180. start_ts.strftime('%Y-%m-%d %H:%M:%S'),
  181. num_links,
  182. resume,
  183. **ANSI,
  184. ))
  185. else:
  186. print('{green}[▶] [{}] Collecting content for {} Snapshots in archive...{reset}'.format(
  187. start_ts.strftime('%Y-%m-%d %H:%M:%S'),
  188. num_links,
  189. **ANSI,
  190. ))
  191. def log_archiving_paused(num_links: int, idx: int, timestamp: str):
  192. end_ts = datetime.now()
  193. _LAST_RUN_STATS.archiving_end_ts = end_ts
  194. print()
  195. print('\n{lightyellow}[X] [{now}] Downloading paused on link {timestamp} ({idx}/{total}){reset}'.format(
  196. **ANSI,
  197. now=end_ts.strftime('%Y-%m-%d %H:%M:%S'),
  198. idx=idx+1,
  199. timestamp=timestamp,
  200. total=num_links,
  201. ))
  202. print()
  203. print(' {lightred}Hint:{reset} To view your archive index, open:'.format(**ANSI))
  204. print(' {}/{}'.format(OUTPUT_DIR, HTML_INDEX_FILENAME))
  205. print(' Continue archiving where you left off by running:')
  206. print(' archivebox update --resume={}'.format(timestamp))
  207. def log_archiving_finished(num_links: int):
  208. end_ts = datetime.now()
  209. _LAST_RUN_STATS.archiving_end_ts = end_ts
  210. assert _LAST_RUN_STATS.archiving_start_ts is not None
  211. seconds = end_ts.timestamp() - _LAST_RUN_STATS.archiving_start_ts.timestamp()
  212. if seconds > 60:
  213. duration = '{0:.2f} min'.format(seconds / 60, 2)
  214. else:
  215. duration = '{0:.2f} sec'.format(seconds, 2)
  216. print()
  217. print('{}[√] [{}] Update of {} pages complete ({}){}'.format(
  218. ANSI['green'],
  219. end_ts.strftime('%Y-%m-%d %H:%M:%S'),
  220. num_links,
  221. duration,
  222. ANSI['reset'],
  223. ))
  224. print(' - {} links skipped'.format(_LAST_RUN_STATS.skipped))
  225. print(' - {} links updated'.format(_LAST_RUN_STATS.succeeded))
  226. print(' - {} links had errors'.format(_LAST_RUN_STATS.failed))
  227. print()
  228. print(' {lightred}Hint:{reset} To view your archive index, open:'.format(**ANSI))
  229. print(' {}/{}'.format(OUTPUT_DIR, HTML_INDEX_FILENAME))
  230. print(' Or run the built-in webserver:')
  231. print(' archivebox server')
  232. def log_link_archiving_started(link: "Link", link_dir: str, is_new: bool):
  233. # [*] [2019-03-22 13:46:45] "Log Structured Merge Trees - ben stopford"
  234. # http://www.benstopford.com/2015/02/14/log-structured-merge-trees/
  235. # > output/archive/1478739709
  236. print('\n[{symbol_color}{symbol}{reset}] [{symbol_color}{now}{reset}] "{title}"'.format(
  237. symbol_color=ANSI['green' if is_new else 'black'],
  238. symbol='+' if is_new else '√',
  239. now=datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
  240. title=link.title or link.base_url,
  241. **ANSI,
  242. ))
  243. print(' {blue}{url}{reset}'.format(url=link.url, **ANSI))
  244. print(' {} {}'.format(
  245. '>' if is_new else '√',
  246. pretty_path(link_dir),
  247. ))
  248. def log_link_archiving_finished(link: "Link", link_dir: str, is_new: bool, stats: dict):
  249. total = sum(stats.values())
  250. if stats['failed'] > 0 :
  251. _LAST_RUN_STATS.failed += 1
  252. elif stats['skipped'] == total:
  253. _LAST_RUN_STATS.skipped += 1
  254. else:
  255. _LAST_RUN_STATS.succeeded += 1
  256. def log_archive_method_started(method: str):
  257. print(' > {}'.format(method))
  258. def log_archive_method_finished(result: "ArchiveResult"):
  259. """quote the argument with whitespace in a command so the user can
  260. copy-paste the outputted string directly to run the cmd
  261. """
  262. # Prettify CMD string and make it safe to copy-paste by quoting arguments
  263. quoted_cmd = ' '.join(
  264. '"{}"'.format(arg) if ' ' in arg else arg
  265. for arg in result.cmd
  266. )
  267. if result.status == 'failed':
  268. # Prettify error output hints string and limit to five lines
  269. hints = getattr(result.output, 'hints', None) or ()
  270. if hints:
  271. hints = hints if isinstance(hints, (list, tuple)) else hints.split('\n')
  272. hints = (
  273. ' {}{}{}'.format(ANSI['lightyellow'], line.strip(), ANSI['reset'])
  274. for line in hints[:5] if line.strip()
  275. )
  276. # Collect and prefix output lines with indentation
  277. output_lines = [
  278. '{lightred}Failed:{reset}'.format(**ANSI),
  279. ' {reset}{} {red}{}{reset}'.format(
  280. result.output.__class__.__name__.replace('ArchiveError', ''),
  281. result.output,
  282. **ANSI,
  283. ),
  284. *hints,
  285. '{}Run to see full output:{}'.format(ANSI['lightred'], ANSI['reset']),
  286. *([' cd {};'.format(result.pwd)] if result.pwd else []),
  287. ' {}'.format(quoted_cmd),
  288. ]
  289. print('\n'.join(
  290. ' {}'.format(line)
  291. for line in output_lines
  292. if line
  293. ))
  294. print()
  295. def log_list_started(filter_patterns: Optional[List[str]], filter_type: str):
  296. print('{green}[*] Finding links in the archive index matching these {} patterns:{reset}'.format(
  297. filter_type,
  298. **ANSI,
  299. ))
  300. print(' {}'.format(' '.join(filter_patterns or ())))
  301. def log_list_finished(links):
  302. from .index.csv import links_to_csv
  303. print()
  304. print('---------------------------------------------------------------------------------------------------')
  305. print(links_to_csv(links, cols=['timestamp', 'is_archived', 'num_outputs', 'url'], header=True, ljust=16, separator=' | '))
  306. print('---------------------------------------------------------------------------------------------------')
  307. print()
  308. def log_removal_started(links: List["Link"], yes: bool, delete: bool):
  309. print('{lightyellow}[i] Found {} matching URLs to remove.{reset}'.format(len(links), **ANSI))
  310. if delete:
  311. file_counts = [link.num_outputs for link in links if os.path.exists(link.link_dir)]
  312. print(
  313. f' {len(links)} Links will be de-listed from the main index, and their archived content folders will be deleted from disk.\n'
  314. f' ({len(file_counts)} data folders with {sum(file_counts)} archived files will be deleted!)'
  315. )
  316. else:
  317. print(
  318. f' Matching links will be de-listed from the main index, but their archived content folders will remain in place on disk.\n'
  319. f' (Pass --delete if you also want to permanently delete the data folders)'
  320. )
  321. if not yes:
  322. print()
  323. print('{lightyellow}[?] Do you want to proceed with removing these {} links?{reset}'.format(len(links), **ANSI))
  324. try:
  325. assert input(' y/[n]: ').lower() == 'y'
  326. except (KeyboardInterrupt, EOFError, AssertionError):
  327. raise SystemExit(0)
  328. def log_removal_finished(all_links: int, to_keep: int):
  329. if all_links == 0:
  330. print()
  331. print('{red}[X] No matching links found.{reset}'.format(**ANSI))
  332. else:
  333. num_removed = all_links - to_keep
  334. print()
  335. print('{red}[√] Removed {} out of {} links from the archive index.{reset}'.format(
  336. num_removed,
  337. all_links,
  338. **ANSI,
  339. ))
  340. print(' Index now contains {} links.'.format(to_keep))
  341. def log_shell_welcome_msg():
  342. from .cli import list_subcommands
  343. print('{green}# ArchiveBox Imports{reset}'.format(**ANSI))
  344. print('{green}from archivebox.core.models import Snapshot, User{reset}'.format(**ANSI))
  345. print('{green}from archivebox import *\n {}{reset}'.format("\n ".join(list_subcommands().keys()), **ANSI))
  346. print()
  347. print('[i] Welcome to the ArchiveBox Shell!')
  348. print(' https://github.com/pirate/ArchiveBox/wiki/Usage#Shell-Usage')
  349. print()
  350. print(' {lightred}Hint:{reset} Example use:'.format(**ANSI))
  351. print(' print(Snapshot.objects.filter(is_archived=True).count())')
  352. print(' Snapshot.objects.get(url="https://example.com").as_json()')
  353. print(' add("https://example.com/some/new/url")')
  354. ### Helpers
  355. @enforce_types
  356. def pretty_path(path: str) -> str:
  357. """convert paths like .../ArchiveBox/archivebox/../output/abc into output/abc"""
  358. pwd = os.path.abspath('.')
  359. # parent = os.path.abspath(os.path.join(pwd, os.path.pardir))
  360. return path.replace(pwd + '/', './')
  361. @enforce_types
  362. def printable_filesize(num_bytes: Union[int, float]) -> str:
  363. for count in ['Bytes','KB','MB','GB']:
  364. if num_bytes > -1024.0 and num_bytes < 1024.0:
  365. return '%3.1f %s' % (num_bytes, count)
  366. num_bytes /= 1024.0
  367. return '%3.1f %s' % (num_bytes, 'TB')
  368. @enforce_types
  369. def printable_folders(folders: Dict[str, Optional["Link"]],
  370. json: bool=False,
  371. csv: Optional[str]=None) -> str:
  372. if json:
  373. from .index.json import to_json
  374. return to_json(folders.values(), indent=4, sort_keys=True)
  375. elif csv:
  376. from .index.csv import links_to_csv
  377. return links_to_csv(folders.values(), cols=csv.split(','), header=True)
  378. return '\n'.join(f'{folder} {link}' for folder, link in folders.items())
  379. @enforce_types
  380. def printable_config(config: ConfigDict, prefix: str='') -> str:
  381. return f'\n{prefix}'.join(
  382. f'{key}={val}'
  383. for key, val in config.items()
  384. if not (isinstance(val, dict) or callable(val))
  385. )
  386. @enforce_types
  387. def printable_folder_status(name: str, folder: Dict) -> str:
  388. if folder['enabled']:
  389. if folder['is_valid']:
  390. color, symbol, note = 'green', '√', 'valid'
  391. else:
  392. color, symbol, note, num_files = 'red', 'X', 'invalid', '?'
  393. else:
  394. color, symbol, note, num_files = 'lightyellow', '-', 'disabled', '-'
  395. if folder['path']:
  396. if os.path.exists(folder['path']):
  397. num_files = (
  398. f'{len(os.listdir(folder["path"]))} files'
  399. if os.path.isdir(folder['path']) else
  400. printable_filesize(os.path.getsize(folder['path']))
  401. )
  402. else:
  403. num_files = 'missing'
  404. if ' ' in folder['path']:
  405. folder['path'] = f'"{folder["path"]}"'
  406. return ' '.join((
  407. ANSI[color],
  408. symbol,
  409. ANSI['reset'],
  410. name.ljust(22),
  411. (folder["path"] or '').ljust(76),
  412. num_files.ljust(14),
  413. ANSI[color],
  414. note,
  415. ANSI['reset'],
  416. ))
  417. @enforce_types
  418. def printable_dependency_version(name: str, dependency: Dict) -> str:
  419. if dependency['enabled']:
  420. if dependency['is_valid']:
  421. color, symbol, note, version = 'green', '√', 'valid', ''
  422. parsed_version_num = re.search(r'[\d\.]+', dependency['version'])
  423. if parsed_version_num:
  424. version = f'v{parsed_version_num[0]}'
  425. if not version:
  426. color, symbol, note, version = 'red', 'X', 'invalid', '?'
  427. else:
  428. color, symbol, note, version = 'lightyellow', '-', 'disabled', '-'
  429. if ' ' in dependency["path"]:
  430. dependency["path"] = f'"{dependency["path"]}"'
  431. return ' '.join((
  432. ANSI[color],
  433. symbol,
  434. ANSI['reset'],
  435. name.ljust(22),
  436. (dependency["path"] or '').ljust(76),
  437. version.ljust(14),
  438. ANSI[color],
  439. note,
  440. ANSI['reset'],
  441. ))