system.py 3.9 KB

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