logging_util.py 19 KB

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