Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions install.sh
Original file line number Diff line number Diff line change
Expand Up @@ -357,6 +357,15 @@ if is_msys2; then
else
mkdir -p /var/run/runtime
chmod 775 /var/run/runtime 2>/dev/null || true # Ignore permission errors in Docker

# Create persistent data directory for native Linux installs
# This directory stores .env and database files that must survive reboot
# In Docker, /var/run/runtime is mounted as a persistent volume instead
if has_systemd_support; then
mkdir -p /var/lib/openplc-runtime
chmod 755 /var/lib/openplc-runtime
log_info "Created persistent data directory at /var/lib/openplc-runtime"
fi
fi

# Make scripts executable
Expand Down
67 changes: 64 additions & 3 deletions webserver/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,49 @@
logger, buffer = get_logger("logger", use_buffer=True)


def is_running_in_container():
"""
Detect if running inside a container (Docker, Podman, etc.).
Returns True if running in a container, False otherwise.
"""
# Check for /.dockerenv file (Docker-specific)
if os.path.exists("/.dockerenv"):
return True

# Check for container environment variables
if os.environ.get("container") or os.environ.get("DOCKER_CONTAINER"):
return True

# Check cgroup for container indicators
try:
with open("/proc/1/cgroup", "r", encoding="utf-8") as f:
cgroup_content = f.read()
if "docker" in cgroup_content or "kubepods" in cgroup_content:
return True
# Also check for containerd/cri-o patterns
if "/lxc/" in cgroup_content or "containerd" in cgroup_content:
return True
Comment on lines +31 to +36

Copilot AI Jan 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reading the entire cgroup file and performing multiple substring searches is inefficient. Consider checking for all patterns in a single pass or stopping at the first match to avoid unnecessary string operations.

Suggested change
cgroup_content = f.read()
if "docker" in cgroup_content or "kubepods" in cgroup_content:
return True
# Also check for containerd/cri-o patterns
if "/lxc/" in cgroup_content or "containerd" in cgroup_content:
return True
indicators = ("docker", "kubepods", "/lxc/", "containerd")
for line in f:
if any(indicator in line for indicator in indicators):
return True

Copilot uses AI. Check for mistakes.
except (FileNotFoundError, PermissionError):
pass

# Check for container runtime in /proc/1/environ
try:
with open("/proc/1/environ", "rb") as f:
environ_content = f.read().decode("utf-8", errors="ignore")
if "container=" in environ_content:
return True
Comment on lines +42 to +45

Copilot AI Jan 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reading and decoding the entire /proc/1/environ file is inefficient. The file can be large and contain many null-separated environment variables. Consider reading in chunks or using a more targeted search approach.

Suggested change
with open("/proc/1/environ", "rb") as f:
environ_content = f.read().decode("utf-8", errors="ignore")
if "container=" in environ_content:
return True
pattern = b"container="
tail_len = len(pattern) - 1
with open("/proc/1/environ", "rb") as f:
leftover = b""
while True:
chunk = f.read(4096)
if not chunk:
break
data = leftover + chunk
if pattern in data:
return True
if tail_len > 0:
leftover = data[-tail_len:]

Copilot uses AI. Check for mistakes.
except (FileNotFoundError, PermissionError):
pass

return False


def get_runtime_dir():
"""
Get the runtime directory path based on the platform.
On MSYS2/Cygwin, use /run/runtime (which maps to a Windows path).
On Linux, use /var/run/runtime for Docker volume compatibility.
On Linux in containers, use /var/run/runtime for Docker volume compatibility.
On native Linux, use /var/run/runtime for ephemeral data (sockets).
"""
if platform.system() != "Linux":
runtime_dir = Path("/run/runtime")
Expand All @@ -28,9 +66,32 @@ def get_runtime_dir():
return runtime_dir


def get_persistent_data_dir():
"""
Get the directory for persistent data (database, .env file).
On containers (Docker), use /var/run/runtime (mounted as persistent volume).
On native Linux, use /var/lib/openplc-runtime (survives reboot).
On MSYS2/Windows, use /run/runtime.
"""
if platform.system() != "Linux":
# MSYS2/Windows: use /run/runtime
data_dir = Path("/run/runtime")
elif is_running_in_container():
# Container: use /var/run/runtime (expected to be a mounted volume)
data_dir = Path("/var/run/runtime")
else:
# Native Linux: use persistent directory that survives reboot
data_dir = Path("/var/lib/openplc-runtime")

# Ensure the directory exists with appropriate permissions
data_dir.mkdir(parents=True, exist_ok=True)

Copilot AI Jan 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Creating the directory without explicit permission checks could lead to security issues if the directory is created with unexpected ownership or permissions. On native Linux, /var/lib/openplc-runtime should have restricted permissions (e.g., 0755) and appropriate ownership to prevent unauthorized access to sensitive data like .env files containing secrets.

Suggested change
data_dir.mkdir(parents=True, exist_ok=True)
if data_dir == Path("/var/lib/openplc-runtime"):
# Explicitly set permissions for sensitive persistent data directory
data_dir.mkdir(parents=True, mode=0o755, exist_ok=True)
try:
os.chmod(data_dir, 0o755)
except PermissionError:
logger.warning(
"Could not set permissions on %s to 0755 due to insufficient privileges",
data_dir,
)
else:
data_dir.mkdir(parents=True, exist_ok=True)

Copilot uses AI. Check for mistakes.
return data_dir


RUNTIME_DIR = get_runtime_dir()
ENV_PATH = RUNTIME_DIR / ".env"
DB_PATH = RUNTIME_DIR / "restapi.db"
PERSISTENT_DATA_DIR = get_persistent_data_dir()
ENV_PATH = PERSISTENT_DATA_DIR / ".env"
DB_PATH = PERSISTENT_DATA_DIR / "restapi.db"
BASE_DIR = os.path.abspath(os.path.dirname(__file__))


Expand Down