summaryrefslogtreecommitdiffstats
path: root/mysqld-prepare-db-dir
blob: f73bc660b43a984044cf6a99f0b17f5340bd3bde (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#!/bin/sh

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

# extract value of a MySQL option from config files
# Usage: get_mysql_option SECTION VARNAME DEFAULT
# result is returned in $result
# We use my_print_defaults which prints all options from multiple files,
# with the more specific ones later; hence take the last match.
get_mysql_option(){
        result=`/usr/bin/my_print_defaults "$1" | sed -n "s/^--$2=//p" | tail -n 1`
        if [ -z "$result" ]; then
            # not found, use default
            result="$3"
        fi
}

# Defaults here had better match what mysqld_safe will default to
get_mysql_option mysqld datadir "/var/lib/mysql"
datadir="$result"
get_mysql_option mysqld_safe log-error "/var/log/mysqld.log"
errlogfile="$result"

# Absorb configuration settings from the specified systemd service file,
# or the default "mysqld" service if not specified
SERVICE_NAME="$1"
if [ x"$SERVICE_NAME" = x ]
then
    SERVICE_NAME=mysqld.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

# Set up the errlogfile with appropriate permissions
touch "$errlogfile"
chown "$myuser:$mygroup" "$errlogfile"
chmod 0640 "$errlogfile"
[ -x /sbin/restorecon ] && /sbin/restorecon "$errlogfile"

# Make the data directory
if [ ! -d "$datadir/mysql" ] ; 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 MySQL database"
    /usr/bin/mysql_install_db --datadir="$datadir" --user="$myuser"
    ret=$?
    if [ $ret -ne 0 ] ; then
        echo "Initialization of MySQL database failed." >&2
        echo "Perhaps /etc/my.cnf is misconfigured." >&2
        # Clean up any partially-created database files
        if [ ! -e "$datadir/mysql/user.frm" ] ; then
            rm -rf "$datadir"/*
        fi
        exit $ret
    fi
    # In case we're running as root, make sure files are owned properly
    chown -R "$myuser:$mygroup" "$datadir"
fi

exit 0