logging_util.py 20 KB

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