#!/bin/bash
# create lwmonitoring mysql user
# check/cleanup existing config/user
# todo: verify if mysql is running
# fail if there is no client.
which mysql > /dev/null
if [ $? -ne 0 ]; then
echo "A mysql client doesn't seem to exist."
exit
fi
#fail nicely if we can't connect to mysql, since we run this script on install
mysql -B -h localhost -e "select user(); " > /dev/null 2>&1
if [ $? -ne 0 ] ; then
echo "Couldn't connect to mysql server to setup mysqld_exporter."
exit
fi
MY_CNF=/usr/local/lp/etc/exporters/my.cnf
owner="systuser"
mysql_user="lwmonitoring"
mysql_pass=$(echo -n \' ; tr -dc '_A-Z-a-z-0-9!@#$%^&*()[];:,.<>|~' < /dev/urandom | head -c16 ; echo -n \')
create_mysql_user() {
# echo "creating $mysql_user with $mysql_pass"
# Create MySQL user
mysql -h localhost -e "GRANT REPLICATION CLIENT, PROCESS on *.* TO '${mysql_user}'@'localhost' IDENTIFIED BY ${mysql_pass} WITH MAX_USER_CONNECTIONS 3"
mysql -h localhost -e "GRANT select on performance_schema.* to '${mysql_user}'@'localhost'"
# mysql -h -e "SELECT User FROM mysql.user where User='$mysql_user'"
}
create_cnf() {
# Update environment file
# echo "DATA_SOURCE_NAME='${mysql_user}:${mysql_pass}@(localhost:3306)/'" > /usr/local/lp/prometheus/env_files/mysqld_exporter
# seems to use a my.cnf file now, set it up here;
MY_CNF=/usr/local/lp/etc/exporters/my.cnf
cat << EOF > $MY_CNF
[client]
user=$mysql_user
password=$mysql_pass
EOF
chown systuser: $MY_CNF
chmod 600 $MY_CNF
}
get_creds(){
if [ -f "$MY_CNF" ]; then
if [ `grep '^password=' $MY_CNF` ]; then
mysql_pass=`grep '^password=' $MY_CNF |cut -d= -f2-`
export mysql_pass
else
return 1
fi
else
return 1
fi
}
check_connection() {
mysql --defaults-file=$MY_CNF -e 'select user();' -B |grep "$mysql_user@localhost"
}
cleanup(){
mysql -e "DROP USER '$mysql_user'@'localhost'"
rm -f $MY_CNF
}
main() {
if [ ! -f $MY_CNF ] || [ $force ]; then
echo "creating $MY_CNF"
create_cnf
else
get_creds
fi
# check if we can connect, create user if not
if [ ! `check_connection` ] || [ $force ]; then
echo "creating $mysql_user"
create_mysql_user
fi
}
case "$1" in
"--force" )
force=true
;;
"get_creds")
get_creds && echo "got $mysql_pass" || echo "failed"
exit
;;
"check")
get_creds && echo $mysql_pass || echo "failed to get credentials"
check_connection && echo "connected" || echo "Failed to connect"
exit
;;
"clean")
cleanup
exit
;;
*)
esac
main
|