logging_util.py 18 KB

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