archivebox_schedule.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. #!/usr/bin/env python3
  2. __package__ = 'archivebox.cli'
  3. import sys
  4. from pathlib import Path
  5. import rich_click as click
  6. from rich import print
  7. from archivebox.misc.util import enforce_types, docstring
  8. from archivebox.config import DATA_DIR, CONSTANTS
  9. from archivebox.config.common import ARCHIVING_CONFIG
  10. from archivebox.config.permissions import USER
  11. CRON_COMMENT = 'ArchiveBox'
  12. @enforce_types
  13. def schedule(add: bool=False,
  14. show: bool=False,
  15. clear: bool=False,
  16. foreground: bool=False,
  17. run_all: bool=False,
  18. quiet: bool=False,
  19. every: str | None=None,
  20. tag: str='',
  21. depth: int | str=0,
  22. overwrite: bool=False,
  23. update: bool=not ARCHIVING_CONFIG.ONLY_NEW,
  24. import_path: str | None=None,
  25. out_dir: Path=DATA_DIR) -> None:
  26. """Set ArchiveBox to regularly import URLs at specific times using cron"""
  27. depth = int(depth)
  28. from crontab import CronTab, CronSlices
  29. from archivebox.misc.system import dedupe_cron_jobs
  30. from abx_plugin_pip.binaries import ARCHIVEBOX_BINARY
  31. Path(CONSTANTS.LOGS_DIR).mkdir(exist_ok=True)
  32. cron = CronTab(user=True)
  33. cron = dedupe_cron_jobs(cron)
  34. if clear:
  35. print(cron.remove_all(comment=CRON_COMMENT))
  36. cron.write()
  37. raise SystemExit(0)
  38. existing_jobs = list(cron.find_comment(CRON_COMMENT))
  39. if every or add:
  40. every = every or 'day'
  41. quoted = lambda s: f'"{s}"' if (s and ' ' in str(s)) else str(s)
  42. cmd = [
  43. 'cd',
  44. quoted(out_dir),
  45. '&&',
  46. quoted(ARCHIVEBOX_BINARY.load().abspath),
  47. *([
  48. 'add',
  49. *(['--overwrite'] if overwrite else []),
  50. *(['--update'] if update else []),
  51. *([f'--tag={tag}'] if tag else []),
  52. f'--depth={depth}',
  53. f'"{import_path}"',
  54. ] if import_path else ['update']),
  55. '>>',
  56. quoted(Path(CONSTANTS.LOGS_DIR) / 'schedule.log'),
  57. '2>&1',
  58. ]
  59. new_job = cron.new(command=' '.join(cmd), comment=CRON_COMMENT)
  60. if every in ('minute', 'hour', 'day', 'month', 'year'):
  61. set_every = getattr(new_job.every(), every)
  62. set_every()
  63. elif CronSlices.is_valid(every):
  64. new_job.setall(every)
  65. else:
  66. print('[red]\\[X] Got invalid timeperiod for cron task.[/red]')
  67. print(' It must be one of minute/hour/day/month')
  68. print(' or a quoted cron-format schedule like:')
  69. print(' archivebox init --every=day --depth=1 https://example.com/some/rss/feed.xml')
  70. print(' archivebox init --every="0/5 * * * *" --depth=1 https://example.com/some/rss/feed.xml')
  71. raise SystemExit(1)
  72. cron = dedupe_cron_jobs(cron)
  73. print(cron)
  74. cron.write()
  75. total_runs = sum(j.frequency_per_year() for j in cron)
  76. existing_jobs = list(cron.find_command('archivebox'))
  77. print()
  78. print('[green]\\[√] Scheduled new ArchiveBox cron job for user: {} ({} jobs are active).[/green]'.format(USER, len(existing_jobs)))
  79. print('\n'.join(f' > {cmd}' if str(cmd) == str(new_job) else f' {cmd}' for cmd in existing_jobs))
  80. if total_runs > 60 and not quiet:
  81. print()
  82. print('[yellow]\\[!] With the current cron config, ArchiveBox is estimated to run >{} times per year.[/yellow]'.format(total_runs))
  83. print(' Congrats on being an enthusiastic internet archiver! 👌')
  84. print()
  85. print(' [violet]Make sure you have enough storage space available to hold all the data.[/violet]')
  86. print(' Using a compressed/deduped filesystem like ZFS is recommended if you plan on archiving a lot.')
  87. print()
  88. elif show:
  89. if existing_jobs:
  90. print('\n'.join(str(cmd) for cmd in existing_jobs))
  91. else:
  92. print('[red]\\[X] There are no ArchiveBox cron jobs scheduled for your user ({}).[/red]'.format(USER))
  93. print(' To schedule a new job, run:')
  94. print(' archivebox schedule --every=[timeperiod] --depth=1 https://example.com/some/rss/feed.xml')
  95. raise SystemExit(0)
  96. if foreground or run_all:
  97. if not existing_jobs:
  98. print('[red]\\[X] You must schedule some jobs first before running in foreground mode.[/red]')
  99. print(' archivebox schedule --every=hour --depth=1 https://example.com/some/rss/feed.xml')
  100. raise SystemExit(1)
  101. print('[green]\\[*] Running {} ArchiveBox jobs in foreground task scheduler...[/green]'.format(len(existing_jobs)))
  102. if run_all:
  103. try:
  104. for job in existing_jobs:
  105. sys.stdout.write(f' > {job.command.split("/archivebox ")[0].split(" && ")[0]}\n')
  106. sys.stdout.write(f' > {job.command.split("/archivebox ")[-1].split(" >> ")[0]}')
  107. sys.stdout.flush()
  108. job.run()
  109. sys.stdout.write(f'\r √ {job.command.split("/archivebox ")[-1]}\n')
  110. except KeyboardInterrupt:
  111. print('\n[green]\\[√] Stopped.[/green] (Ctrl+C)')
  112. raise SystemExit(1)
  113. if foreground:
  114. try:
  115. for job in existing_jobs:
  116. print(f' > {job.command.split("/archivebox ")[-1].split(" >> ")[0]}')
  117. for result in cron.run_scheduler():
  118. print(result)
  119. except KeyboardInterrupt:
  120. print('\n[green]\\[√] Stopped.[/green] (Ctrl+C)')
  121. raise SystemExit(1)
  122. @click.command()
  123. @click.option('--quiet', '-q', is_flag=True, help="Don't warn about storage space")
  124. @click.option('--add', is_flag=True, help='Add a new scheduled ArchiveBox update job to cron')
  125. @click.option('--every', type=str, help='Run ArchiveBox once every [timeperiod] (hour/day/month/year or cron format e.g. "0 0 * * *")')
  126. @click.option('--tag', '-t', default='', help='Tag the added URLs with the provided tags e.g. --tag=tag1,tag2,tag3')
  127. @click.option('--depth', type=click.Choice(['0', '1']), default='0', help='Depth to archive to [0] or 1')
  128. @click.option('--overwrite', is_flag=True, help='Re-archive any URLs that have been previously archived, overwriting existing Snapshots')
  129. @click.option('--update', is_flag=True, help='Re-pull any URLs that have been previously added, as needed to fill missing ArchiveResults')
  130. @click.option('--clear', is_flag=True, help='Stop all ArchiveBox scheduled runs (remove cron jobs)')
  131. @click.option('--show', is_flag=True, help='Print a list of currently active ArchiveBox cron jobs')
  132. @click.option('--foreground', '-f', is_flag=True, help='Launch ArchiveBox scheduler as a long-running foreground task instead of using cron')
  133. @click.option('--run-all', is_flag=True, help='Run all the scheduled jobs once immediately, independent of their configured schedules')
  134. @click.argument('import_path', required=False)
  135. @docstring(schedule.__doc__)
  136. def main(**kwargs):
  137. """Set ArchiveBox to regularly import URLs at specific times using cron"""
  138. schedule(**kwargs)
  139. if __name__ == '__main__':
  140. main()