system.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. __package__ = 'archivebox'
  2. import os
  3. import shutil
  4. from json import dump
  5. from pathlib import Path
  6. from typing import Optional, Union, Set, Tuple
  7. from subprocess import run as subprocess_run
  8. from crontab import CronTab
  9. from atomicwrites import atomic_write as lib_atomic_write
  10. from .util import enforce_types, ExtendedEncoder
  11. from .config import OUTPUT_PERMISSIONS
  12. def run(*args, input=None, capture_output=True, text=False, **kwargs):
  13. """Patched of subprocess.run to fix blocking io making timeout=innefective"""
  14. if input is not None:
  15. if 'stdin' in kwargs:
  16. raise ValueError('stdin and input arguments may not both be used.')
  17. if capture_output:
  18. if ('stdout' in kwargs) or ('stderr' in kwargs):
  19. raise ValueError('stdout and stderr arguments may not be used '
  20. 'with capture_output.')
  21. return subprocess_run(*args, input=input, capture_output=capture_output, text=text, **kwargs)
  22. @enforce_types
  23. def atomic_write(path: Union[Path, str], contents: Union[dict, str, bytes], overwrite: bool=True) -> None:
  24. """Safe atomic write to filesystem by writing to temp file + atomic rename"""
  25. mode = 'wb+' if isinstance(contents, bytes) else 'w'
  26. encoding = None if isinstance(contents, bytes) else 'utf-8' # enforce utf-8 on all text writes
  27. # print('\n> Atomic Write:', mode, path, len(contents), f'overwrite={overwrite}')
  28. try:
  29. with lib_atomic_write(path, mode=mode, overwrite=overwrite, encoding=encoding) as f:
  30. if isinstance(contents, dict):
  31. dump(contents, f, indent=4, sort_keys=True, cls=ExtendedEncoder)
  32. elif isinstance(contents, (bytes, str)):
  33. f.write(contents)
  34. except OSError as e:
  35. print(f"[X] OSError: Failed to write {path} with fcntl.F_FULLFSYNC. ({e})")
  36. print(" You can store the archive/ subfolder on a hard drive or network share that doesn't support support syncronous writes,")
  37. print(" but the main folder containing the index.sqlite3 and ArchiveBox.conf files must be on a filesystem that supports FSYNC.")
  38. raise SystemExit(1)
  39. os.chmod(path, int(OUTPUT_PERMISSIONS, base=8))
  40. @enforce_types
  41. def chmod_file(path: str, cwd: str='.', permissions: str=OUTPUT_PERMISSIONS) -> None:
  42. """chmod -R <permissions> <cwd>/<path>"""
  43. root = Path(cwd) / path
  44. if not root.exists():
  45. raise Exception('Failed to chmod: {} does not exist (did the previous step fail?)'.format(path))
  46. if not root.is_dir():
  47. os.chmod(root, int(OUTPUT_PERMISSIONS, base=8))
  48. else:
  49. for subpath in Path(path).glob('**/*'):
  50. os.chmod(subpath, int(OUTPUT_PERMISSIONS, base=8))
  51. @enforce_types
  52. def copy_and_overwrite(from_path: Union[str, Path], to_path: Union[str, Path]):
  53. """copy a given file or directory to a given path, overwriting the destination"""
  54. if Path(from_path).is_dir():
  55. shutil.rmtree(to_path, ignore_errors=True)
  56. shutil.copytree(from_path, to_path)
  57. else:
  58. with open(from_path, 'rb') as src:
  59. contents = src.read()
  60. atomic_write(to_path, contents)
  61. @enforce_types
  62. def get_dir_size(path: Union[str, Path], recursive: bool=True, pattern: Optional[str]=None) -> Tuple[int, int, int]:
  63. """get the total disk size of a given directory, optionally summing up
  64. recursively and limiting to a given filter list
  65. """
  66. num_bytes, num_dirs, num_files = 0, 0, 0
  67. for entry in os.scandir(path):
  68. if (pattern is not None) and (pattern not in entry.path):
  69. continue
  70. if entry.is_dir(follow_symlinks=False):
  71. if not recursive:
  72. continue
  73. num_dirs += 1
  74. bytes_inside, dirs_inside, files_inside = get_dir_size(entry.path)
  75. num_bytes += bytes_inside
  76. num_dirs += dirs_inside
  77. num_files += files_inside
  78. else:
  79. num_bytes += entry.stat(follow_symlinks=False).st_size
  80. num_files += 1
  81. return num_bytes, num_dirs, num_files
  82. CRON_COMMENT = 'archivebox_schedule'
  83. @enforce_types
  84. def dedupe_cron_jobs(cron: CronTab) -> CronTab:
  85. deduped: Set[Tuple[str, str]] = set()
  86. for job in list(cron):
  87. unique_tuple = (str(job.slices), job.command)
  88. if unique_tuple not in deduped:
  89. deduped.add(unique_tuple)
  90. cron.remove(job)
  91. for schedule, command in deduped:
  92. job = cron.new(command=command, comment=CRON_COMMENT)
  93. job.setall(schedule)
  94. job.enable()
  95. return cron
  96. class suppress_output(object):
  97. '''
  98. A context manager for doing a "deep suppression" of stdout and stderr in
  99. Python, i.e. will suppress all print, even if the print originates in a
  100. compiled C/Fortran sub-function.
  101. This will not suppress raised exceptions, since exceptions are printed
  102. to stderr just before a script exits, and after the context manager has
  103. exited (at least, I think that is why it lets exceptions through).
  104. with suppress_stdout_stderr():
  105. rogue_function()
  106. '''
  107. def __init__(self, stdout=True, stderr=True):
  108. # Open a pair of null files
  109. # Save the actual stdout (1) and stderr (2) file descriptors.
  110. self.stdout, self.stderr = stdout, stderr
  111. if stdout:
  112. self.null_stdout = os.open(os.devnull, os.O_RDWR)
  113. self.real_stdout = os.dup(1)
  114. if stderr:
  115. self.null_stderr = os.open(os.devnull, os.O_RDWR)
  116. self.real_stderr = os.dup(2)
  117. def __enter__(self):
  118. # Assign the null pointers to stdout and stderr.
  119. if self.stdout:
  120. os.dup2(self.null_stdout, 1)
  121. if self.stderr:
  122. os.dup2(self.null_stderr, 2)
  123. def __exit__(self, *_):
  124. # Re-assign the real stdout/stderr back to (1) and (2)
  125. if self.stdout:
  126. os.dup2(self.real_stdout, 1)
  127. os.close(self.null_stdout)
  128. if self.stderr:
  129. os.dup2(self.real_stderr, 2)
  130. os.close(self.null_stderr)