59 lines
2.3 KiB
Python
59 lines
2.3 KiB
Python
"""Initialize named volumes once; never replace an existing Homegate configuration."""
|
|
import fcntl
|
|
import os
|
|
from pathlib import Path
|
|
import stat
|
|
import sys
|
|
|
|
import yaml
|
|
|
|
import homegate as h
|
|
|
|
|
|
def initialize(seed, config, state, control, uid=1000, gid=1000):
|
|
config, state, control = map(Path, (config, state, control))
|
|
seed = Path(seed)
|
|
for directory in (config.parent, state, control):
|
|
h.require(not directory.is_symlink(), f"Volume must not be a symlink: {directory}")
|
|
directory.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
h.require(directory.is_dir(), f"Expected a directory: {directory}")
|
|
# The short-lived initializer is the only root container. No recursive chown:
|
|
# existing CA material and backups must not be traversed or replaced.
|
|
if os.geteuid() == 0:
|
|
os.chown(directory, uid, gid)
|
|
os.chmod(directory, 0o700)
|
|
lock_path = config.parent / '.bootstrap.lock'
|
|
h.require(not lock_path.is_symlink(), 'Bootstrap lock must not be a symlink')
|
|
with lock_path.open('a') as lock:
|
|
fcntl.flock(lock, fcntl.LOCK_EX)
|
|
h.require(not config.is_symlink(), 'services.yaml must not be a symlink')
|
|
if config.exists():
|
|
h.require(stat.S_ISREG(config.stat().st_mode), 'services.yaml must be a regular file')
|
|
h.load_config(config)
|
|
created = False
|
|
else:
|
|
h.load_config(seed) # Reject invalid seed before touching the live config.
|
|
h.atomic(config, seed.read_bytes(), 0o600)
|
|
created = True
|
|
if os.geteuid() == 0:
|
|
os.chown(config, uid, gid)
|
|
return created
|
|
|
|
|
|
def main():
|
|
os.umask(0o077)
|
|
created = initialize(os.environ.get('HOMEGATE_SEED', '/run/configs/homegate-seed.yaml'),
|
|
os.environ.get('HOMEGATE_CONFIG', '/config/services.yaml'),
|
|
os.environ.get('HOMEGATE_STATE', '/data'),
|
|
os.environ.get('HOMEGATE_CONTROL', '/control'))
|
|
print('Created initial configuration' if created else 'Existing configuration retained')
|
|
return 0
|
|
|
|
|
|
if __name__ == '__main__':
|
|
try:
|
|
sys.exit(main())
|
|
except (h.Error, ValueError, KeyError, TypeError, OSError, yaml.YAMLError) as exc:
|
|
print(f'Initialization failed: {exc}', file=sys.stderr)
|
|
sys.exit(1)
|