system.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. __package__ = 'archivebox'
  2. import os
  3. import signal
  4. import shutil
  5. from json import dump
  6. from pathlib import Path
  7. from typing import Optional, Union, Set, Tuple
  8. from subprocess import _mswindows, PIPE, Popen, CalledProcessError, CompletedProcess, TimeoutExpired
  9. from crontab import CronTab
  10. from .vendor.atomicwrites import atomic_write as lib_atomic_write
  11. from .util import enforce_types, ExtendedEncoder
  12. from .config import PYTHON_BINARY, OUTPUT_PERMISSIONS, DIR_OUTPUT_PERMISSIONS, ENFORCE_ATOMIC_WRITES
  13. def run(cmd, *args, input=None, capture_output=True, timeout=None, check=False, text=False, start_new_session=True, **kwargs):
  14. """Patched of subprocess.run to kill forked child subprocesses and fix blocking io making timeout=innefective
  15. Mostly copied from https://github.com/python/cpython/blob/master/Lib/subprocess.py
  16. """
  17. if input is not None:
  18. if kwargs.get('stdin') is not None:
  19. raise ValueError('stdin and input arguments may not both be used.')
  20. kwargs['stdin'] = PIPE
  21. if capture_output:
  22. if ('stdout' in kwargs) or ('stderr' in kwargs):
  23. raise ValueError('stdout and stderr arguments may not be used with capture_output.')
  24. kwargs['stdout'] = PIPE
  25. kwargs['stderr'] = PIPE
  26. pgid = None
  27. try:
  28. if isinstance(cmd, (list, tuple)) and cmd[0].endswith('.py'):
  29. cmd = (PYTHON_BINARY, *cmd)
  30. with Popen(cmd, *args, start_new_session=start_new_session, **kwargs) as process:
  31. pgid = os.getpgid(process.pid)
  32. try:
  33. stdout, stderr = process.communicate(input, timeout=timeout)
  34. except TimeoutExpired as exc:
  35. process.kill()
  36. if _mswindows:
  37. # Windows accumulates the output in a single blocking
  38. # read() call run on child threads, with the timeout
  39. # being done in a join() on those threads. communicate()
  40. # _after_ kill() is required to collect that and add it
  41. # to the exception.
  42. exc.stdout, exc.stderr = process.communicate()
  43. else:
  44. # POSIX _communicate already populated the output so
  45. # far into the TimeoutExpired exception.
  46. process.wait()
  47. raise
  48. except: # Including KeyboardInterrupt, communicate handled that.
  49. process.kill()
  50. # We don't call process.wait() as .__exit__ does that for us.
  51. raise
  52. retcode = process.poll()
  53. if check and retcode:
  54. raise CalledProcessError(retcode, process.args,
  55. output=stdout, stderr=stderr)
  56. finally:
  57. # force kill any straggler subprocesses that were forked from the main proc
  58. try:
  59. os.killpg(pgid, signal.SIGINT)
  60. except Exception:
  61. pass
  62. return CompletedProcess(process.args, retcode, stdout, stderr)
  63. @enforce_types
  64. def atomic_write(path: Union[Path, str], contents: Union[dict, str, bytes], overwrite: bool=True) -> None:
  65. """Safe atomic write to filesystem by writing to temp file + atomic rename"""
  66. mode = 'wb+' if isinstance(contents, bytes) else 'w'
  67. encoding = None if isinstance(contents, bytes) else 'utf-8' # enforce utf-8 on all text writes
  68. # print('\n> Atomic Write:', mode, path, len(contents), f'overwrite={overwrite}')
  69. try:
  70. with lib_atomic_write(path, mode=mode, overwrite=overwrite, encoding=encoding) as f:
  71. if isinstance(contents, dict):
  72. dump(contents, f, indent=4, sort_keys=True, cls=ExtendedEncoder)
  73. elif isinstance(contents, (bytes, str)):
  74. f.write(contents)
  75. except OSError as e:
  76. if ENFORCE_ATOMIC_WRITES:
  77. print(f"[X] OSError: Failed to write {path} with fcntl.F_FULLFSYNC. ({e})")
  78. print(" You can store the archive/ subfolder on a hard drive or network share that doesn't support support syncronous writes,")
  79. print(" but the main folder containing the index.sqlite3 and ArchiveBox.conf files must be on a filesystem that supports FSYNC.")
  80. raise SystemExit(1)
  81. # retry the write without forcing FSYNC (aka atomic mode)
  82. with open(path, mode=mode, encoding=encoding) as f:
  83. if isinstance(contents, dict):
  84. dump(contents, f, indent=4, sort_keys=True, cls=ExtendedEncoder)
  85. elif isinstance(contents, (bytes, str)):
  86. f.write(contents)
  87. # set file permissions
  88. os.chmod(path, int(OUTPUT_PERMISSIONS, base=8))
  89. @enforce_types
  90. def chmod_file(path: str, cwd: str='.') -> None:
  91. """chmod -R <permissions> <cwd>/<path>"""
  92. root = Path(cwd) / path
  93. if not root.exists():
  94. raise Exception('Failed to chmod: {} does not exist (did the previous step fail?)'.format(path))
  95. if not root.is_dir():
  96. # path is just a plain file
  97. os.chmod(root, int(OUTPUT_PERMISSIONS, base=8))
  98. else:
  99. for subpath in Path(path).glob('**/*'):
  100. if subpath.is_dir():
  101. # directories need execute permissions to be able to list contents
  102. os.chmod(subpath, int(DIR_OUTPUT_PERMISSIONS, base=8))
  103. else:
  104. os.chmod(subpath, int(OUTPUT_PERMISSIONS, base=8))
  105. @enforce_types
  106. def copy_and_overwrite(from_path: Union[str, Path], to_path: Union[str, Path]):
  107. """copy a given file or directory to a given path, overwriting the destination"""
  108. if Path(from_path).is_dir():
  109. shutil.rmtree(to_path, ignore_errors=True)
  110. shutil.copytree(from_path, to_path)
  111. else:
  112. with open(from_path, 'rb') as src:
  113. contents = src.read()
  114. atomic_write(to_path, contents)
  115. @enforce_types
  116. def get_dir_size(path: Union[str, Path], recursive: bool=True, pattern: Optional[str]=None) -> Tuple[int, int, int]:
  117. """get the total disk size of a given directory, optionally summing up
  118. recursively and limiting to a given filter list
  119. """
  120. num_bytes, num_dirs, num_files = 0, 0, 0
  121. try:
  122. for entry in os.scandir(path):
  123. if (pattern is not None) and (pattern not in entry.path):
  124. continue
  125. if entry.is_dir(follow_symlinks=False):
  126. if not recursive:
  127. continue
  128. num_dirs += 1
  129. bytes_inside, dirs_inside, files_inside = get_dir_size(entry.path)
  130. num_bytes += bytes_inside
  131. num_dirs += dirs_inside
  132. num_files += files_inside
  133. else:
  134. num_bytes += entry.stat(follow_symlinks=False).st_size
  135. num_files += 1
  136. except OSError:
  137. # e.g. FileNameTooLong or other error while trying to read dir
  138. pass
  139. return num_bytes, num_dirs, num_files
  140. CRON_COMMENT = 'archivebox_schedule'
  141. @enforce_types
  142. def dedupe_cron_jobs(cron: CronTab) -> CronTab:
  143. deduped: Set[Tuple[str, str]] = set()
  144. for job in list(cron):
  145. unique_tuple = (str(job.slices), str(job.command))
  146. if unique_tuple not in deduped:
  147. deduped.add(unique_tuple)
  148. cron.remove(job)
  149. for schedule, command in deduped:
  150. job = cron.new(command=command, comment=CRON_COMMENT)
  151. job.setall(schedule)
  152. job.enable()
  153. return cron
  154. class suppress_output(object):
  155. """
  156. A context manager for doing a "deep suppression" of stdout and stderr in
  157. Python, i.e. will suppress all print, even if the print originates in a
  158. compiled C/Fortran sub-function.
  159. This will not suppress raised exceptions, since exceptions are printed
  160. to stderr just before a script exits, and after the context manager has
  161. exited (at least, I think that is why it lets exceptions through).
  162. with suppress_stdout_stderr():
  163. rogue_function()
  164. """
  165. def __init__(self, stdout=True, stderr=True):
  166. # Open a pair of null files
  167. # Save the actual stdout (1) and stderr (2) file descriptors.
  168. self.stdout, self.stderr = stdout, stderr
  169. if stdout:
  170. self.null_stdout = os.open(os.devnull, os.O_RDWR)
  171. self.real_stdout = os.dup(1)
  172. if stderr:
  173. self.null_stderr = os.open(os.devnull, os.O_RDWR)
  174. self.real_stderr = os.dup(2)
  175. def __enter__(self):
  176. # Assign the null pointers to stdout and stderr.
  177. if self.stdout:
  178. os.dup2(self.null_stdout, 1)
  179. if self.stderr:
  180. os.dup2(self.null_stderr, 2)
  181. def __exit__(self, *_):
  182. # Re-assign the real stdout/stderr back to (1) and (2)
  183. if self.stdout:
  184. os.dup2(self.real_stdout, 1)
  185. os.close(self.null_stdout)
  186. if self.stderr:
  187. os.dup2(self.real_stderr, 2)
  188. os.close(self.null_stderr)