system.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  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. # print('\n> Atomic Write:', mode, path, len(contents), f'overwrite={overwrite}')
  27. with lib_atomic_write(path, mode=mode, overwrite=overwrite) as f:
  28. if isinstance(contents, dict):
  29. dump(contents, f, indent=4, sort_keys=True, cls=ExtendedEncoder)
  30. elif isinstance(contents, (bytes, str)):
  31. f.write(contents)
  32. @enforce_types
  33. def chmod_file(path: str, cwd: str='.', permissions: str=OUTPUT_PERMISSIONS) -> None:
  34. """chmod -R <permissions> <cwd>/<path>"""
  35. root = Path(cwd) / path
  36. if not root.exists():
  37. raise Exception('Failed to chmod: {} does not exist (did the previous step fail?)'.format(path))
  38. for subpath in Path(path).glob('**/*'):
  39. os.chmod(subpath, int(OUTPUT_PERMISSIONS, base=8))
  40. @enforce_types
  41. def copy_and_overwrite(from_path: str, to_path: str):
  42. """copy a given file or directory to a given path, overwriting the destination"""
  43. if os.path.isdir(from_path):
  44. shutil.rmtree(to_path, ignore_errors=True)
  45. shutil.copytree(from_path, to_path)
  46. else:
  47. with open(from_path, 'rb') as src:
  48. contents = src.read()
  49. atomic_write(to_path, contents)
  50. @enforce_types
  51. def get_dir_size(path: str, recursive: bool=True, pattern: Optional[str]=None) -> Tuple[int, int, int]:
  52. """get the total disk size of a given directory, optionally summing up
  53. recursively and limiting to a given filter list
  54. """
  55. num_bytes, num_dirs, num_files = 0, 0, 0
  56. for entry in os.scandir(path):
  57. if (pattern is not None) and (pattern not in entry.path):
  58. continue
  59. if entry.is_dir(follow_symlinks=False):
  60. if not recursive:
  61. continue
  62. num_dirs += 1
  63. bytes_inside, dirs_inside, files_inside = get_dir_size(entry.path)
  64. num_bytes += bytes_inside
  65. num_dirs += dirs_inside
  66. num_files += files_inside
  67. else:
  68. num_bytes += entry.stat(follow_symlinks=False).st_size
  69. num_files += 1
  70. return num_bytes, num_dirs, num_files
  71. CRON_COMMENT = 'archivebox_schedule'
  72. @enforce_types
  73. def dedupe_cron_jobs(cron: CronTab) -> CronTab:
  74. deduped: Set[Tuple[str, str]] = set()
  75. for job in list(cron):
  76. unique_tuple = (str(job.slices), job.command)
  77. if unique_tuple not in deduped:
  78. deduped.add(unique_tuple)
  79. cron.remove(job)
  80. for schedule, command in deduped:
  81. job = cron.new(command=command, comment=CRON_COMMENT)
  82. job.setall(schedule)
  83. job.enable()
  84. return cron