system.py 8.7 KB

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