Added an explicit data folder permissions check on startup
It will try resolve the permission issue on its own, but if not successful it will crash with a helpful message.
This commit is contained in:
@@ -2,6 +2,8 @@
|
||||
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from datetime import datetime
|
||||
from enum import Enum
|
||||
from pathlib import Path
|
||||
@@ -11,6 +13,8 @@ from urllib import parse
|
||||
import pkg_resources
|
||||
from platformdirs import user_data_dir
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class DatabaseType(Enum):
|
||||
"""The database type."""
|
||||
@@ -272,3 +276,53 @@ def get_build_date() -> Optional[datetime]:
|
||||
if build_date == "unknown":
|
||||
return None
|
||||
return datetime.fromisoformat(build_date)
|
||||
|
||||
|
||||
def can_write_to_data_dir() -> bool:
|
||||
"""Check if the data directory is writable."""
|
||||
try:
|
||||
test_file = get_data_dir().joinpath("test.txt")
|
||||
test_file.touch()
|
||||
test_file.unlink()
|
||||
except: # noqa: E722
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def chown_dir(path: str) -> bool:
|
||||
"""Try to chown the data directory to the current user."""
|
||||
if os.name == "nt":
|
||||
return False
|
||||
|
||||
try:
|
||||
uid = os.getuid()
|
||||
gid = os.getgid()
|
||||
subprocess.run(["chown", "-R", f"{uid}:{gid}", path], check=True) # noqa: S603, S607
|
||||
except: # noqa: E722
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def check_write_permissions() -> None:
|
||||
"""Verify that the data directory is writable, crash with a helpful error message if not."""
|
||||
if not can_write_to_data_dir():
|
||||
# If windows we can't fix the permissions, so just crash
|
||||
if os.name == "nt":
|
||||
logger.error("Data directory is not writable.")
|
||||
sys.exit(1)
|
||||
|
||||
# Try fixing it by chowning the directory to the current user
|
||||
logger.warning("Data directory is not writable, trying to fix it...")
|
||||
if not chown_dir(get_data_dir()) or not can_write_to_data_dir():
|
||||
uid = os.getuid()
|
||||
gid = os.getgid()
|
||||
|
||||
logger.error(
|
||||
(
|
||||
"Data directory is not writable. "
|
||||
'Please run "sudo chown -R %s:%s /path/to/spoolman/datadir" on the host OS.'
|
||||
),
|
||||
uid,
|
||||
gid,
|
||||
)
|
||||
sys.exit(1)
|
||||
|
||||
Reference in New Issue
Block a user