Skip to content

Instantly share code, notes, and snippets.

@centminmod
Last active September 26, 2022 20:57
Show Gist options
  • Save centminmod/38b4f2dde2a13936fed2f0536fc27c13 to your computer and use it in GitHub Desktop.
Save centminmod/38b4f2dde2a13936fed2f0536fc27c13 to your computer and use it in GitHub Desktop.
el8 native appstream mariadb 10.3

/usr/lib/systemd/system/mariadb.service

# It's not recommended to modify this file in-place, because it will be
# overwritten during package upgrades.  If you want to customize, the
# best way is to create a file "/etc/systemd/system/mariadb.service",
# containing
#       .include /usr/lib/systemd/system/mariadb.service
#       ...make your changes here...
# or create a file "/etc/systemd/system/mariadb.service.d/foo.conf",
# which doesn't need to include ".include" call and which will be parsed
# after the file mariadb.service itself is parsed.
#
# For more info about custom unit files, see systemd.unit(5) or
# http://fedoraproject.org/wiki/Systemd#How_do_I_customize_a_unit_file.2F_add_a_custom_unit_file.3F

# For example, if you want to increase mysql's open-files-limit to 10000,
# you need to increase systemd's LimitNOFILE setting, so create a file named
# "/etc/systemd/system/mariadb.service.d/limits.conf" containing:
#       [Service]
#       LimitNOFILE=10000

# Note: /usr/lib/... is recommended in the .include line though /lib/...
# still works.
# Don't forget to reload systemd daemon after you change unit configuration:
# root> systemctl --system daemon-reload

# Use [mysqld.INSTANCENAME] as sections in my.cnf to configure this instance.

[Unit]
Description=MariaDB 10.3 database server
Documentation=man:mysqld(8)
Documentation=https://mariadb.com/kb/en/library/systemd/
After=network.target

[Install]
WantedBy=multi-user.target
Alias=mysql.service
Alias=mysqld.service

[Service]
Type=notify
User=mysql
Group=mysql

ExecStartPre=/usr/libexec/mysql-check-socket
# '%n' expands to 'Full unit name'; man systemd.unit
ExecStartPre=/usr/libexec/mysql-prepare-db-dir %n
# MYSQLD_OPTS here is for users to set in /etc/systemd/system/mariadb@.service.d/MY_SPECIAL.conf
# Note: we set --basedir to prevent probes that might trigger SELinux alarms,
# per bug #547485
ExecStart=/usr/libexec/mysqld --basedir=/usr $MYSQLD_OPTS $_WSREP_NEW_CLUSTER
ExecStartPost=/usr/libexec/mysql-check-upgrade

# Setting this to true can break replication and the Type=notify settings
# See also bind-address mysqld option.
PrivateNetwork=false

KillMode=process
KillSignal=SIGTERM

# Don't want to see an automated SIGKILL ever
SendSIGKILL=no

# Restart crashed server only, on-failure would also restart, for example, when
# my.cnf contains unknown option
Restart=on-abort
RestartSec=5s

UMask=007

# Give a reasonable amount of time for the server to start up/shut down
TimeoutSec=300

# Place temp files in a secure directory, not /tmp
PrivateTmp=true
systemctl status mariadb
● mariadb.service - MariaDB 10.3 database server
   Loaded: loaded (/usr/lib/systemd/system/mariadb.service; enabled; vendor preset: disabled)
  Drop-In: /etc/systemd/system/mariadb.service.d
           └─migrated-from-my.cnf-settings.conf, notifyaccess.conf, openfileslimit.conf, protecthome.conf
   Active: active (running) since Mon 2022-09-26 02:21:24 UTC; 2s ago
     Docs: man:mysqld(8)
           https://mariadb.com/kb/en/library/systemd/
  Process: 1909 ExecStartPost=/usr/libexec/mysql-check-upgrade (code=exited, status=0/SUCCESS)
  Process: 1846 ExecStartPre=/usr/libexec/mysql-prepare-db-dir mariadb.service (code=exited, status=0/SUCCESS)
  Process: 1822 ExecStartPre=/usr/libexec/mysql-check-socket (code=exited, status=0/SUCCESS)
 Main PID: 1884 (mysqld)
   Status: "Taking your SQL requests now..."
    Tasks: 23 (limit: 24704)
   Memory: 45.9M
   CGroup: /system.slice/mariadb.service
           └─1884 /usr/libexec/mysqld --basedir=/usr

Sep 26 02:21:23 build.domain.com systemd[1]: Starting MariaDB 10.3 database server...
Sep 26 02:21:23 build.domain.com mysql-prepare-db-dir[1846]: Database MariaDB is probably initialized in /var/lib/mysql already, nothing is done.
Sep 26 02:21:23 build.domain.com mysql-prepare-db-dir[1846]: If this is not the case, make sure the /var/lib/mysql is empty before running mysql-prepare-db-dir.
Sep 26 02:21:24 build.domain.com mysqld[1884]: 2022-09-26  2:21:24 0 [Note] /usr/libexec/mysqld (mysqld 10.3.35-MariaDB) starting as process 1884 ...
Sep 26 02:21:24 build.domain.com systemd[1]: Started MariaDB 10.3 database server.

/usr/libexec/mysql-check-upgrade

#!/bin/sh

source "`dirname ${BASH_SOURCE[0]}`/mysql-scripts-common"

upgrade_info_file="$datadir/mysql_upgrade_info"
version=0
# get version as integer from mysql_upgrade_info file
if [ -f "$upgrade_info_file" ] && [ -r "$upgrade_info_file" ] ; then
    version_major=$(cat "$upgrade_info_file" | head -n 1 | sed -e 's/\([0-9]*\)\.\([0-9]*\)\..*$/\1/')
    version_minor=$(cat "$upgrade_info_file" | head -n 1 | sed -e 's/\([0-9]*\)\.\([0-9]*\)\..*$/\2/')
    if [[ $version_major =~ ^[0-9]+$ ]] && [[ $version_minor =~ ^[0-9]+$ ]] ; then
        version=$((version_major*100+version_minor))
    fi
fi

# compute current version as integer
thisversion=$((10*100+3))

# provide warning in cases we should run mysql_upgrade
if [ $version -ne $thisversion ] ; then

    # give extra warning if some version seems to be skipped
    if [ $version -gt 0 ] && [ $version -lt 505 ] ; then
        echo "The datadir located at $datadir seems to be older than of a version 5.5. Please, mind that as a general rule, to upgrade from one release series to another, go to the next series rather than skipping a series." >&2
    fi

    cat <<EOF >&2
The datadir located at $datadir needs to be upgraded using 'mysql_upgrade' tool. This can be done using the following steps:

  1. Back-up your data before with 'mysql_upgrade'
  2. Start the database daemon using 'service mariadb start'
  3. Run 'mysql_upgrade' with a database user that has sufficient privileges

Read more about 'mysql_upgrade' usage at:
https://mariadb.com/kb/en/mariadb/documentation/sql-commands/table-commands/mysql_upgrade/
EOF
fi

exit 0

/usr/libexec/mysql-prepare-db-dir

#!/bin/sh

# This script creates the mysql data directory during first service start.
# In subsequent starts, it does nothing much.

source "`dirname ${BASH_SOURCE[0]}`/mysql-scripts-common"

export LC_ALL=C

# Returns content of the specified directory
# If listing files fails, fake-file is returned so which means
# we'll behave like there was some data initialized
# Some files or directories are fine to be there, so those are
# explicitly removed from the listing
# @param <dir> datadir
list_datadir ()
{
    ( ls -1A "$1" 2>/dev/null || echo "fake-file" ) | grep -v \
    -e '^lost+found$' \
    -e '\.err$' \
    -e '^.bash_history$'
}

# Checks whether datadir should be initialized
# @param <dir> datadir
should_initialize ()
{
    test -z "$(list_datadir "$1")"
}

# If two args given first is user, second is group
# otherwise the arg is the systemd service file
if [ "$#" -eq 2 ]
then
    myuser="$1"
    mygroup="$2"
else
    # Absorb configuration settings from the specified systemd service file,
    # or the default service if not specified
    SERVICE_NAME="$1"
    if [ x"$SERVICE_NAME" = x ]
    then
        SERVICE_NAME=mariadb.service
    fi

    myuser=`systemctl show -p User "${SERVICE_NAME}" |
      sed 's/^User=//'`
    if [ x"$myuser" = x ]
    then
        myuser=mysql
    fi

    mygroup=`systemctl show -p Group "${SERVICE_NAME}" |
      sed 's/^Group=//'`
    if [ x"$mygroup" = x ]
    then
        mygroup=mysql
    fi
fi

# Set up the errlogfile with appropriate permissions
if [ ! -e "$errlogfile" -a ! -h "$errlogfile" -a x$(dirname "$errlogfile") = "x/var/log" ]; then
    case $(basename "$errlogfile") in
        mysql*.log|mariadb*.log) install /dev/null -m0640 -o$myuser -g$mygroup "$errlogfile" ;;
        *) ;;
    esac
else
    # Provide some advice if the log file cannot be created by this script
    errlogdir=$(dirname "$errlogfile")
    if ! [ -d "$errlogdir" ] ; then
        echo "The directory $errlogdir does not exist." >&2
        exit 1
    elif [ -e "$errlogfile" -a ! -w "$errlogfile" ] ; then
        echo "The log file $errlogfile cannot be written, please, fix its permissions." >&2
        echo "The daemon will be run under $myuser:$mygroup" >&2
        exit 1
    fi
fi

# Make the data directory if doesn't exist or empty
if should_initialize "$datadir" ; then
    # First, make sure $datadir is there with correct permissions
    # (note: if it's not, and we're not root, this'll fail ...)
    if [ ! -e "$datadir" -a ! -h "$datadir" ]
    then
        mkdir -p "$datadir" || exit 1
    fi
    chown "$myuser:$mygroup" "$datadir"
    chmod 0755 "$datadir"
    [ -x /sbin/restorecon ] && /sbin/restorecon "$datadir"

    # Now create the database
    echo "Initializing MariaDB database" >&2
    # Avoiding deletion of files not created by mysql_install_db is
    # guarded by time check and sleep should help work-arounded
    # potential issues on systems with 1 second resolution timestamps
    # https://bugzilla.redhat.com/show_bug.cgi?id=1335849#c19
    INITDB_TIMESTAMP=`LANG=C date -u`
    sleep 1
    /usr/bin/mysql_install_db --rpm --datadir="$datadir" --user="$myuser" --skip-test-db >&2
    ret=$?
    if [ $ret -ne 0 ] ; then
        echo "Initialization of MariaDB database failed." >&2
        echo "Perhaps /etc/my.cnf is misconfigured or there is some problem with permissions of $datadir." >&2
        # Clean up any partially-created database files
        if [ ! -e "$datadir/mysql/user.frm" ] && [ -d "$datadir" ] ; then
            echo "Initialization of MariaDB database was not finished successfully." >&2
            echo "Files created so far will be removed." >&2
            find "$datadir" -mindepth 1 -maxdepth 1 -newermt "$INITDB_TIMESTAMP" \
                 -not -name "lost+found" -exec rm -rf {} +
            if [ $? -ne 0 ] ; then
                echo "Removing of created files was not successfull." >&2
                echo "Please, clean directory $datadir manually." >&2
            fi
        else
            echo "However, part of data has been initialized and those will not be removed." >&2
            echo "Please, clean directory $datadir manually." >&2
        fi
        exit $ret
    fi
    # upgrade does not need to be run on a fresh datadir
    echo "10.3.35-MariaDB" >"$datadir/mysql_upgrade_info"
else
    if [ -d "$datadir/mysql/" ] ; then
        # mysql dir exists, it seems data are initialized properly
        echo "Database MariaDB is probably initialized in $datadir already, nothing is done."
        echo "If this is not the case, make sure the $datadir is empty before running `basename $0`."
    else
        # if the directory is not empty but mysql/ directory is missing, then
        # print error and let user to initialize manually or empty the directory
        echo "Database MariaDB is not initialized, but the directory $datadir is not empty, so initialization cannot be done." >&2
        echo "Make sure the $datadir is empty before running `basename $0`." >&2
        exit 1
    fi
fi

exit 0

/usr/libexec/mysql-check-socket

#!/bin/sh

# We check if there is already a process using the socket file,
# since otherwise the systemd service file could report false
# positive result when starting and mysqld_safe could remove
# a socket file, which is actually being used by a different daemon.

source "`dirname ${BASH_SOURCE[0]}`/mysql-scripts-common"

if test -e "$socketfile" ; then
    echo "Socket file $socketfile exists." >&2

    # no write permissions
    if ! test -w "$socketfile" ; then
        echo "Not enough permission to write to the socket file $socketfile, which is suspicious." >&2
        echo "Please, remove $socketfile manually to start the service." >&2
        exit 1
    fi

    # not a socket file
    if ! test -S "$socketfile" ; then
        echo "The file $socketfile is not a socket file, which is suspicious." >&2
        echo "Please, remove $socketfile manually to start the service." >&2
        exit 1
    fi

    # some process uses the socket file
    response=`/usr/bin/mysqladmin --no-defaults --socket="$socketfile" --user=UNKNOWN_MYSQL_USER --connect-timeout="${CHECKSOCKETTIMEOUT:-10}" ping 2>&1`
    if [ $? -eq 0 ] || echo "$response" | grep -q "Access denied for user" ; then
        echo "Is another MySQL daemon already running with the same unix socket?" >&2
        echo "Please, stop the process using the socket $socketfile or remove the file manually to start the service." >&2
        exit 1
    fi

    # socket file is a garbage
    echo "No process is using $socketfile, which means it is a garbage, so it will be removed automatically." >&2
fi

exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment