system.py 7.8 KB

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