logging_util.py 19 KB

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