From 10538b82df08bf719c388bd937ec550c9ec8ddf7 Mon Sep 17 00:00:00 2001 From: Felix Uhl Date: Wed, 31 Jul 2024 15:49:23 +0200 Subject: [PATCH] nixos/mysql: fix permission error during first startup When mysql starts up for the first time, the binary `mysql_install_db` will run and try to set up the correct folder structure and permissions. The very first step is to change the owner and group of the data directory. This can fail in some cases, for example if `cfg.dataDir` is something like `/mnt/mysql`: ``` Jul 31 15:24:35 junction systemd[1]: Starting MySQL Server... Jul 31 15:24:36 junction mysql-pre-start[1346]: chown: changing ownership of '/mnt/mysql': Operation not permitted Jul 31 15:24:36 junction mysql-pre-start[1309]: Cannot change ownership of the database directories to the 'mysql' Jul 31 15:24:36 junction mysql-pre-start[1309]: user. Check that you have the necessary permissions and try again. Jul 31 15:24:36 junction systemd[1]: mysql.service: Control process exited, code=exited, status=1/FAILURE Jul 31 15:24:36 junction systemd[1]: mysql.service: Failed with result 'exit-code'. Jul 31 15:24:36 junction systemd[1]: Failed to start MySQL Server. ``` This is because `/mnt` usually is owned by root. To work around this issue, use `systemd.tmpfiles` to set the owner, group and permissions. This will always work, and if the permissions are already set as expected, mysql will not try to alter them again. --- nixos/modules/services/databases/mysql.nix | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/nixos/modules/services/databases/mysql.nix b/nixos/modules/services/databases/mysql.nix index 4b2e83e71e20..7fcc423b4c91 100644 --- a/nixos/modules/services/databases/mysql.nix +++ b/nixos/modules/services/databases/mysql.nix @@ -337,6 +337,12 @@ in environment.etc."my.cnf".source = cfg.configFile; + # The mysql_install_db binary will try to adjust the permissions, but fail to do so with a permission + # denied error in some circumstances. Setting the permissions manually with tmpfiles is a workaround. + systemd.tmpfiles.rules = [ + "d ${cfg.dataDir} 0755 ${cfg.user} ${cfg.group} - -" + ]; + systemd.services.mysql = { description = "MySQL Server";