Merge branch 'master' of git://git.puppet.immerda.ch/module-mysql

Conflicts:
	files/scripts/optimize_tables.rb
	manifests/server/base.pp
This commit is contained in:
Jerome Charaoui 2015-02-24 16:46:45 -05:00
commit a713d36aeb
21 changed files with 400 additions and 107 deletions

2
README
View file

@ -6,6 +6,8 @@ This module manages your mysql resources.
Requirements Requirements
------------ ------------
The puppetlabs-stdlib module is required for some functions used in this module.
If you are wanting munin integration, you will need the munin module installed. If you are wanting munin integration, you will need the munin module installed.
If you are wanting shorewall integration, you will need the shorewall module If you are wanting shorewall integration, you will need the shorewall module

View file

@ -3,13 +3,15 @@ datadir=/var/lib/mysql/data
log-bin=/var/lib/mysql/mysql-bin log-bin=/var/lib/mysql/mysql-bin
expire_logs_days=5 expire_logs_days=5
socket=/var/lib/mysql/mysql.sock socket=/var/lib/mysql/mysql.sock
# Default to using old password format for compatibility with mysql 3.x # Disabling symbolic-links is recommended to prevent assorted security risks
# clients (those using the mysqlclient10 compatibility package). symbolic-links=0
old_passwords=0 # Settings user and group are ignored when systemd is used.
# If you need to run mysqld under a different user or group,
# customize your systemd unit file for mariadb according to the
# instructions in http://fedoraproject.org/wiki/Systemd
bind-address=127.0.0.1 bind-address=127.0.0.1
max_allowed_packet = 10M
skip-bdb
# Query cache is used to cache SELECT results and later return them # Query cache is used to cache SELECT results and later return them
# without actual executing the same query once again. Having the query # without actual executing the same query once again. Having the query
@ -27,7 +29,7 @@ query_cache_size = 64M
# indexes well, if log_long_format is enabled. It is normally good idea # indexes well, if log_long_format is enabled. It is normally good idea
# to have this turned on if you frequently add new queries to the # to have this turned on if you frequently add new queries to the
# system. # system.
log_slow_queries slow_query_log
# How many threads we should keep in a cache for reuse. When a client # How many threads we should keep in a cache for reuse. When a client
# disconnects, the client's threads are put in the cache if there aren't # disconnects, the client's threads are put in the cache if there aren't
@ -45,16 +47,20 @@ thread_cache_size = 4
# cause paging in the operating system. Note that on 32bit systems you # cause paging in the operating system. Note that on 32bit systems you
# might be limited to 2-3.5G of user level memory per process, so do not # might be limited to 2-3.5G of user level memory per process, so do not
# set it too high. # set it too high.
innodb_data_home_dir = /var/lib/mysql/data
innodb_data_file_path = ibdata1:10M:autoextend
innodb_log_group_home_dir = /var/lib/mysql/
innodb_buffer_pool_size = 50MB innodb_buffer_pool_size = 50MB
innodb_file_per_table innodb_file_per_table
query_cache_limit=5M query_cache_limit=5M
[mysql.server]
user=mysql
basedir=/usr
[mysqld_safe] [mysqld_safe]
log-error=/var/log/mysqld.log log-error=/var/log/mariadb/mariadb.log
pid-file=/var/run/mysqld/mysqld.pid pid-file=/var/run/mariadb/mariadb.pid
#
# include all files from the config directory
#
!includedir /etc/my.cnf.d

View file

@ -0,0 +1,87 @@
[mysqld]
datadir=/var/lib/mysql/data
log-bin=/var/lib/mysql/mysql-bin
expire_logs_days=5
socket=/var/lib/mysql/mysql.sock
# Default to using old password format for compatibility with mysql 3.x
# clients (those using the mysqlclient10 compatibility package).
old_passwords=0
character-set-server = utf8
skip-name-resolve
bind-address=127.0.0.1
max_allowed_packet = 10M
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
# Query cache is used to cache SELECT results and later return them
# without actual executing the same query once again. Having the query
# cache enabled may result in significant speed improvements, if your
# have a lot of identical queries and rarely changing tables. See the
# "Qcache_lowmem_prunes" status variable to check if the current value
# is high enough for your load.
# Note: In case your tables change very often or if your queries are
# textually different every time, the query cache may result in a
# slowdown instead of a performance improvement.
query_cache_size = 64M
# Log slow queries. Slow queries are queries which take more than the
# amount of time defined in "long_query_time" or which do not use
# indexes well, if log_long_format is enabled. It is normally good idea
# to have this turned on if you frequently add new queries to the
# system.
slow_query_log
# How many threads we should keep in a cache for reuse. When a client
# disconnects, the client's threads are put in the cache if there aren't
# more than thread_cache_size threads from before. This greatly reduces
# the amount of thread creations needed if you have a lot of new
# connections. (Normally this doesn't give a notable performance
# improvement if you have a good thread implementation.)
thread_cache_size = 4
# InnoDB, unlike MyISAM, uses a buffer pool to cache both indexes and
# row data. The bigger you set this the less disk I/O is needed to
# access data in tables. On a dedicated database server you may set this
# parameter up to 80% of the machine physical memory size. Do not set it
# too large, though, because competition of the physical memory may
# cause paging in the operating system. Note that on 32bit systems you
# might be limited to 2-3.5G of user level memory per process, so do not
# set it too high.
innodb_data_home_dir = /var/lib/mysql/data
innodb_data_file_path = ibdata1:10M:autoextend
innodb_log_group_home_dir = /var/lib/mysql/
innodb_buffer_pool_size = 50MB
innodb_file_per_table
query_cache_limit=5M
[mysql]
no-auto-rehash
# Remove the next comment character if you are not familiar with SQL
#safe-updates
default-character-set=utf8
[mysqlimport]
default-character-set=utf8
[mysqlshow]
default-character-set=utf8
[mysql.server]
user=mysql
basedir=/usr
[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
[mysqldump]
quick
max_allowed_packet = 16M
default-character-set=utf8
!includedir /etc/mysql/conf.d/

View file

@ -0,0 +1,87 @@
[mysqld]
datadir=/var/lib/mysql/data
log-bin=/var/lib/mysql/mysql-bin
expire_logs_days=5
socket=/var/lib/mysql/mysql.sock
# Default to using old password format for compatibility with mysql 3.x
# clients (those using the mysqlclient10 compatibility package).
old_passwords=0
character-set-server = utf8
skip-name-resolve
bind-address=127.0.0.1
max_allowed_packet = 10M
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
# Query cache is used to cache SELECT results and later return them
# without actual executing the same query once again. Having the query
# cache enabled may result in significant speed improvements, if your
# have a lot of identical queries and rarely changing tables. See the
# "Qcache_lowmem_prunes" status variable to check if the current value
# is high enough for your load.
# Note: In case your tables change very often or if your queries are
# textually different every time, the query cache may result in a
# slowdown instead of a performance improvement.
query_cache_size = 64M
# Log slow queries. Slow queries are queries which take more than the
# amount of time defined in "long_query_time" or which do not use
# indexes well, if log_long_format is enabled. It is normally good idea
# to have this turned on if you frequently add new queries to the
# system.
slow_query_log
# How many threads we should keep in a cache for reuse. When a client
# disconnects, the client's threads are put in the cache if there aren't
# more than thread_cache_size threads from before. This greatly reduces
# the amount of thread creations needed if you have a lot of new
# connections. (Normally this doesn't give a notable performance
# improvement if you have a good thread implementation.)
thread_cache_size = 4
# InnoDB, unlike MyISAM, uses a buffer pool to cache both indexes and
# row data. The bigger you set this the less disk I/O is needed to
# access data in tables. On a dedicated database server you may set this
# parameter up to 80% of the machine physical memory size. Do not set it
# too large, though, because competition of the physical memory may
# cause paging in the operating system. Note that on 32bit systems you
# might be limited to 2-3.5G of user level memory per process, so do not
# set it too high.
innodb_data_home_dir = /var/lib/mysql/data
innodb_data_file_path = ibdata1:10M:autoextend
innodb_log_group_home_dir = /var/lib/mysql/
innodb_buffer_pool_size = 50MB
innodb_file_per_table
query_cache_limit=5M
[mysql]
no-auto-rehash
# Remove the next comment character if you are not familiar with SQL
#safe-updates
default-character-set=utf8
[mysqlimport]
default-character-set=utf8
[mysqlshow]
default-character-set=utf8
[mysql.server]
user=mysql
basedir=/usr
[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
[mysqldump]
quick
max_allowed_packet = 16M
default-character-set=utf8
!includedir /etc/mysql/conf.d/

View file

@ -24,17 +24,22 @@ must_have chown
rootpw=$(grep password /root/.my.cnf | sed -e 's/^[^=]*= *\(.*\) */\1/') rootpw=$(grep password /root/.my.cnf | sed -e 's/^[^=]*= *\(.*\) */\1/')
/sbin/service mysqld stop /usr/bin/mysqladmin -uroot --password="${rootpw}" status > /dev/null && echo "Nothing to do as the password already works" && exit 0
/usr/libexec/mysqld --skip-grant-tables --user=root --datadir=/var/lib/mysql/data --log-bin=/var/lib/mysql/mysql-bin & /usr/bin/systemctl stop mariadb
/usr/libexec/mysqld --skip-grant-tables --user=root --datadir=/var/lib/mysql/data --log-bin=/var/lib/mysql/mysql-bin --pid-file=/var/run/mariadb/mariadb.pid &
sleep 5 sleep 5
mysql -u root mysql <<EOF mysql -u root mysql <<EOF
UPDATE mysql.user SET Password=PASSWORD('$rootpw') WHERE User='root' AND Host='localhost'; UPDATE mysql.user SET Password=PASSWORD('$rootpw') WHERE User='root' AND Host='localhost';
DELETE FROM mysql.user WHERE (User='root' AND Host!='localhost') OR USER='';
FLUSH PRIVILEGES; FLUSH PRIVILEGES;
EOF EOF
killall mysqld kill `cat /var/run/mariadb/mariadb.pid`
sleep 15
# chown to be on the safe side # chown to be on the safe side
chown mysql.mysql /var/lib/mysql/mysql-bin.* ls -al /var/lib/mysql/mysql-bin.* &> /dev/null
[ $? == 0 ] && chown mysql.mysql /var/lib/mysql/mysql-bin.*
/sbin/service mysqld start chown -R mysql.mysql /var/lib/mysql/data/
/usr/bin/systemctl start mariadb

View file

@ -0,0 +1,26 @@
#!/bin/sh
test -f /root/.my.cnf || exit 1
rootpw=$(grep password /root/.my.cnf | sed -e 's/^[^=]*= *\(.*\) */\1/')
/usr/bin/mysqladmin -uroot --password="${rootpw}" status > /dev/null && echo "Nothing to do as the password already works" && exit 0
/sbin/service mysqld stop
/usr/libexec/mysqld --skip-grant-tables --user=root --datadir=/var/lib/mysql/data --log-bin=/var/lib/mysql/mysql-bin &
sleep 5
mysql -u root mysql <<EOF
UPDATE mysql.user SET Password=PASSWORD('$rootpw') WHERE User='root' AND Host='localhost';
DELETE FROM mysql.user WHERE (User='root' AND Host!='localhost') OR USER='';
FLUSH PRIVILEGES;
EOF
killall mysqld
sleep 15
# chown to be on the safe side
ls -al /var/lib/mysql/mysql-bin.* &> /dev/null
[ $? == 0 ] && chown mysql.mysql /var/lib/mysql/mysql-bin.*
chown -R mysql.mysql /var/lib/mysql/data/
/sbin/service mysqld start

View file

@ -0,0 +1,26 @@
#!/bin/sh
test -f /root/.my.cnf || exit 1
rootpw=$(grep password /root/.my.cnf | sed -e 's/^[^=]*= *\(.*\) */\1/')
/usr/bin/mysqladmin -uroot --password="${rootpw}" status > /dev/null && echo "Nothing to do as the password already works" && exit 0
/sbin/service mysqld stop
/usr/libexec/mysqld --skip-grant-tables --user=root --datadir=/var/lib/mysql/data --log-bin=/var/lib/mysql/mysql-bin &
sleep 5
mysql -u root mysql <<EOF
UPDATE mysql.user SET Password=PASSWORD('$rootpw') WHERE User='root' AND Host='localhost';
DELETE FROM mysql.user WHERE (User='root' AND Host!='localhost') OR USER='';
FLUSH PRIVILEGES;
EOF
killall mysqld
sleep 15
# chown to be on the safe side
ls -al /var/lib/mysql/mysql-bin.* &> /dev/null
[ $? == 0 ] && chown mysql.mysql /var/lib/mysql/mysql-bin.*
chown -R mysql.mysql /var/lib/mysql/data/
/sbin/service mysqld start

View file

@ -25,12 +25,15 @@ must_have chown
rootpw=$(grep password /root/.my.cnf | sed -e 's/^[^=]*= *\(.*\) */\1/') rootpw=$(grep password /root/.my.cnf | sed -e 's/^[^=]*= *\(.*\) */\1/')
/usr/bin/mysqladmin -uroot --password="${rootpw}" status > /dev/null && echo "Nothing to do as the password already works" && exit 0
/etc/init.d/mysql stop /etc/init.d/mysql stop
/usr/sbin/mysqld --skip-grant-tables --user=root --datadir=/var/lib/mysql --log-bin=/var/lib/mysql/mysql-bin & /usr/sbin/mysqld --skip-grant-tables --user=root --datadir=/var/lib/mysql --log-bin=/var/lib/mysql/mysql-bin &
sleep 5 sleep 5
mysql -u root mysql <<EOF mysql -u root mysql <<EOF
UPDATE mysql.user SET Password=PASSWORD('$rootpw') WHERE User='root' AND Host='localhost'; UPDATE mysql.user SET Password=PASSWORD('$rootpw') WHERE User='root' AND Host='localhost';
DELETE FROM mysql.user WHERE (User='root' AND Host!='localhost') OR USER='';
FLUSH PRIVILEGES; FLUSH PRIVILEGES;
EOF EOF
killall mysqld killall mysqld
@ -38,6 +41,7 @@ sleep 15
# chown to be on the safe side # chown to be on the safe side
ls -al /var/lib/mysql/mysql-bin.* &> /dev/null ls -al /var/lib/mysql/mysql-bin.* &> /dev/null
[ $? == 0 ] && chown mysql.mysql /var/lib/mysql/mysql-bin.* [ $? == 0 ] && chown mysql.mysql /var/lib/mysql/mysql-bin.*
chown -R mysql.mysql /var/lib/mysql/data/
/etc/init.d/mysql start /etc/init.d/mysql start

View file

@ -2,12 +2,13 @@
# set home as we runit as weekly cron, where HOME is / # set home as we runit as weekly cron, where HOME is /
ENV['HOME'] = '/root' ENV['HOME'] = '/root'
tables = %x(mysql -Bse "SELECT TABLE_SCHEMA,TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA NOT IN ('information_schema','mysql') AND Data_free > 0 AND ENGINE IN ('MyISAM','InnoDB','ARCHIVE')") tables = %x{mysql -Bse "SELECT TABLE_SCHEMA,TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA NOT IN ('information_schema','mysql') AND Data_free > 0 AND ENGINE IN ('MyISAM','InnoDB','ARCHIVE')"}
tables = tables.split(/\n/) tables.split("\n").each do |table|
tables.each { |table|
tableitems = table.chomp.split(/\t/) tableitems = table.chomp.split(/\t/)
system "mysql #{tableitems[0]} -Bse \"OPTIMIZE TABLE \\`#{tableitems[0]}\\`.\\`#{tableitems[1]}\\`\" | grep -q OK" output = %x{mysql #{tableitems[0]} -Bse "OPTIMIZE TABLE \\`#{tableitems[0]}\\`.\\`#{tableitems[1]}\\`" 2>&1}
if $?.to_i > 0 then unless output =~ /status\t+OK/
puts "error while optimizing #{tableitems[0]}.#{tableitems[1]}" puts "Error while optimizing #{tableitems[0]}.#{tableitems[1]}:"
puts output
puts
end
end end
}

View file

@ -7,11 +7,23 @@ Puppet::Type.type(:mysql_database).provide(:mysql,
commands :mysqladmin => '/usr/bin/mysqladmin' commands :mysqladmin => '/usr/bin/mysqladmin'
commands :mysql => '/usr/bin/mysql' commands :mysql => '/usr/bin/mysql'
def self.defaults_file
if File.file?("#{Facter.value(:root_home)}/.my.cnf")
"--defaults-file=#{Facter.value(:root_home)}/.my.cnf"
else
nil
end
end
def defaults_file
self.class.defaults_file
end
# retrieve the current set of mysql users # retrieve the current set of mysql users
def self.instances def self.instances
dbs = [] dbs = []
cmd = "#{command(:mysql)} mysql -NBe 'show databases'" cmd = "#{command(:mysql)} #{defaults_file} mysql -NBe 'show databases'"
execpipe(cmd) do |process| execpipe(cmd) do |process|
process.each do |line| process.each do |line|
dbs << new( { :ensure => :present, :name => line.chomp } ) dbs << new( { :ensure => :present, :name => line.chomp } )
@ -26,7 +38,7 @@ Puppet::Type.type(:mysql_database).provide(:mysql,
:ensure => :absent :ensure => :absent
} }
cmd = "#{command(:mysql)} mysql -NBe 'show databases'" cmd = "#{command(:mysql)} #{defaults_file} mysql -NBe 'show databases'"
execpipe(cmd) do |process| execpipe(cmd) do |process|
process.each do |line| process.each do |line|
if line.chomp.eql?(@resource[:name]) if line.chomp.eql?(@resource[:name])
@ -38,14 +50,14 @@ Puppet::Type.type(:mysql_database).provide(:mysql,
end end
def create def create
mysqladmin "create", @resource[:name] mysqladmin(defaults_file, "create", @resource[:name])
end end
def destroy def destroy
mysqladmin "-f", "drop", @resource[:name] mysqladmin(defaults_file, "-f", "drop", @resource[:name])
end end
def exists? def exists?
if mysql("mysql", "-NBe", "show databases").match(/^#{@resource[:name]}$/) if mysql(defaults_file, "mysql" ,"-NBe", "show databases").match(/^#{@resource[:name]}$/)
true true
else else
false false

View file

@ -54,8 +54,20 @@ Puppet::Type.type(:mysql_grant).provide(:mysql) do
commands :mysql => '/usr/bin/mysql' commands :mysql => '/usr/bin/mysql'
commands :mysqladmin => '/usr/bin/mysqladmin' commands :mysqladmin => '/usr/bin/mysqladmin'
# Optional defaults file
def self.defaults_file
if File.file?("#{Facter.value(:root_home)}/.my.cnf")
"--defaults-file=#{Facter.value(:root_home)}/.my.cnf"
else
nil
end
end
def defaults_file
self.class.defaults_file
end
def mysql_flush def mysql_flush
mysqladmin "flush-privileges" mysqladmin(defaults_file, "flush-privileges")
end end
# this parses the # this parses the
@ -101,24 +113,24 @@ Puppet::Type.type(:mysql_grant).provide(:mysql) do
name = split_name(@resource[:name]) name = split_name(@resource[:name])
case name[:type] case name[:type]
when :user when :user
mysql "mysql", "-e", "INSERT INTO user (host, user) VALUES ('%s', '%s')" % [ mysql(defaults_file, "mysql", "-e", "INSERT INTO user (host, user) VALUES ('%s', '%s')" % [
name[:host], name[:user], name[:host], name[:user],
] ])
when :db when :db
mysql "mysql", "-e", "INSERT INTO db (host, user, db) VALUES ('%s', '%s', '%s')" % [ mysql(defaults_file, "mysql", "-e", "INSERT INTO db (host, user, db) VALUES ('%s', '%s', '%s')" % [
name[:host], name[:user], name[:db], name[:host], name[:user], name[:db],
] ])
when :column when :column
mysql "mysql", "-e", "INSERT INTO columns_priv (host, user, db, table, column_name) VALUES ('%s', '%s', '%s', '%s', '%s')" % [ mysql(defaults_file, "mysql", "-e", "INSERT INTO columns_priv (host, user, db, table, column_name) VALUES ('%s', '%s', '%s', '%s', '%s')" % [
name[:host], name[:user], name[:db], name[:table], name[:column], name[:host], name[:user], name[:db], name[:table], name[:column],
] ])
end end
mysql_flush mysql_flush
end end
end end
def destroy def destroy
mysql "mysql", "-e", "REVOKE ALL ON '%s'.* FROM '%s@%s'" % [ @resource[:privileges], @resource[:database], @resource[:name], @resource[:host] ] mysql(defaults_file, "mysql", "-e", "REVOKE ALL ON '%s'.* FROM '%s@%s'" % [ @resource[:privileges], @resource[:database], @resource[:name], @resource[:host] ])
end end
def row_exists? def row_exists?
@ -130,7 +142,7 @@ Puppet::Type.type(:mysql_grant).provide(:mysql) do
if name[:type] == :column if name[:type] == :column
fields << :column fields << :column
end end
not mysql( "mysql", "-NBe", 'SELECT "1" FROM %s WHERE %s' % [ name[:type], fields.map do |f| "%s = '%s'" % [f, name[f]] end.join(' AND ')]).empty? not mysql(defaults_file, "mysql", "-NBe", 'SELECT "1" FROM %s WHERE %s' % [ name[:type], fields.map do |f| "%s = '%s'" % [f, name[f]] end.join(' AND ')]).empty?
end end
def all_privs_set? def all_privs_set?
@ -156,15 +168,15 @@ Puppet::Type.type(:mysql_grant).provide(:mysql) do
case name[:type] case name[:type]
when :user when :user
privs = mysql "mysql", "-Be", 'select * from user where user="%s" and host="%s"' % [ name[:user], name[:host] ] privs = mysql(defaults_file, "mysql", "-Be", 'select * from user where user="%s" and host="%s"' % [ name[:user], name[:host] ])
when :db when :db
privs = mysql "mysql", "-Be", 'select * from db where user="%s" and host="%s" and db="%s"' % [ name[:user], name[:host], name[:db] ] privs = mysql(defaults_file, "mysql", "-Be", 'select * from db where user="%s" and host="%s" and db="%s"' % [ name[:user], name[:host], name[:db] ])
when :tables_priv when :tables_priv
privs = mysql "mysql", "-NBe", 'select Table_priv from tables_priv where User="%s" and Host="%s" and Db="%s" and Table_name="%s"' % [ name[:user], name[:host], name[:db], name[:table_name] ] privs = mysql(defaults_file, "mysql", "-NBe", 'select Table_priv from tables_priv where User="%s" and Host="%s" and Db="%s" and Table_name="%s"' % [ name[:user], name[:host], name[:db], name[:table_name] ])
privs = privs.chomp.downcase privs = privs.chomp.downcase
return privs return privs
when :columns when :columns
privs = mysql "mysql", "-Be", 'select * from columns_priv where User="%s" and Host="%s" and Db="%s" and Table_name="%s" and Column_name="%s"' % [ name[:user], name[:host], name[:db], name[:table], name[:column] ] privs = mysql(defaults_file, "mysql", "-Be", 'select * from columns_priv where User="%s" and Host="%s" and Db="%s" and Table_name="%s" and Column_name="%s"' % [ name[:user], name[:host], name[:db], name[:table], name[:column] ])
end end
if privs.match(/^$/) if privs.match(/^$/)
@ -177,7 +189,7 @@ Puppet::Type.type(:mysql_grant).provide(:mysql) do
# transpose the lines, so we have key/value pairs # transpose the lines, so we have key/value pairs
privs = privs[0].zip(privs[1]) privs = privs[0].zip(privs[1])
privs = privs.select do |p| (/_priv$/) and p[1] == 'Y' end privs = privs.select do |p| (/_priv$/) and p[1] == 'Y' end
privs.collect do |p| symbolize(p[0].downcase) end privs.collect{|p| p[0].downcase.intern }
end end
end end
end end
@ -213,7 +225,7 @@ Puppet::Type.type(:mysql_grant).provide(:mysql) do
if !revoke.empty? if !revoke.empty?
#puts "Revoking table privs: ", revoke #puts "Revoking table privs: ", revoke
mysql "mysql", "-e", "REVOKE %s ON %s.%s FROM '%s'@'%s'" % [ revoke.join(", "), name[:db], name[:table_name], name[:user], name[:host] ] mysql(defaults_file, "mysql", "-e", "REVOKE %s ON %s.%s FROM '%s'@'%s'" % [ revoke.join(", "), name[:db], name[:table_name], name[:user], name[:host] ])
end end
set = privs - currently_set set = privs - currently_set
@ -245,7 +257,7 @@ Puppet::Type.type(:mysql_grant).provide(:mysql) do
#puts "stmt:", stmt #puts "stmt:", stmt
if !set.empty? if !set.empty?
mysql "mysql", "-Be", stmt mysql(defaults_file, "mysql", "-Be", stmt)
mysql_flush mysql_flush
end end
end end

View file

@ -8,11 +8,23 @@ Puppet::Type.type(:mysql_user).provide(:mysql,
commands :mysql => '/usr/bin/mysql' commands :mysql => '/usr/bin/mysql'
commands :mysqladmin => '/usr/bin/mysqladmin' commands :mysqladmin => '/usr/bin/mysqladmin'
# Optional defaults file
def self.defaults_file
if File.file?("#{Facter.value(:root_home)}/.my.cnf")
"--defaults-file=#{Facter.value(:root_home)}/.my.cnf"
else
nil
end
end
def defaults_file
self.class.defaults_file
end
# retrieve the current set of mysql users # retrieve the current set of mysql users
def self.instances def self.instances
users = [] users = []
cmd = "#{command(:mysql)} mysql -NBe 'select concat(user, \"@\", host), password from user'" cmd = "#{command(:mysql)} #{defaults_file} mysql -NBe 'select concat(user, \"@\", host), password from user'"
execpipe(cmd) do |process| execpipe(cmd) do |process|
process.each do |line| process.each do |line|
users << new( query_line_to_hash(line) ) users << new( query_line_to_hash(line) )
@ -31,13 +43,13 @@ Puppet::Type.type(:mysql_user).provide(:mysql,
end end
def mysql_flush def mysql_flush
mysqladmin "flush-privileges" mysqladmin(defaults_file,"flush-privileges")
end end
def query def query
result = {} result = {}
cmd = "#{command(:mysql)} -NBe 'select concat(user, \"@\", host), password from user where concat(user, \"@\", host) = \"%s\"'" % @resource[:name] cmd = "#{command(:mysql)} #{defaults_file} -NBe 'select concat(user, \"@\", host), password from user where concat(user, \"@\", host) = \"%s\"'" % @resource[:name]
execpipe(cmd) do |process| execpipe(cmd) do |process|
process.each do |line| process.each do |line|
unless result.empty? unless result.empty?
@ -51,17 +63,17 @@ Puppet::Type.type(:mysql_user).provide(:mysql,
end end
def create def create
mysql "mysql", "-e", "create user '%s' identified by PASSWORD '%s'" % [ @resource[:name].sub("@", "'@'"), @resource.should(:password_hash) ] mysql(defaults_file, "mysql", "-e", "create user '%s' identified by PASSWORD '%s'" % [ @resource[:name].sub("@", "'@'"), @resource.should(:password_hash) ])
mysql_flush mysql_flush
end end
def destroy def destroy
mysql "mysql", "-e", "drop user '%s'" % @resource[:name].sub("@", "'@'") mysql(defaults_file, "mysql", "-e", "drop user '%s'" % @resource[:name].sub("@", "'@'"))
mysql_flush mysql_flush
end end
def exists? def exists?
not mysql("mysql", "-NBe", "select '1' from user where CONCAT(user, '@', host) = '%s'" % @resource[:name]).empty? not mysql(defaults_file, "mysql", "-NBe", "select '1' from user where CONCAT(user, '@', host) = '%s'" % @resource[:name]).empty?
end end
def password_hash def password_hash
@ -69,7 +81,7 @@ Puppet::Type.type(:mysql_user).provide(:mysql,
end end
def password_hash=(string) def password_hash=(string)
mysql "mysql", "-e", "SET PASSWORD FOR '%s' = '%s'" % [ @resource[:name].sub("@", "'@'"), string ] mysql(defaults_file, "mysql", "-e", "SET PASSWORD FOR '%s' = '%s'" % [ @resource[:name].sub("@", "'@'"), string ])
mysql_flush mysql_flush
end end
end end

View file

@ -43,7 +43,7 @@ Puppet::Type.newtype(:mysql_grant) do
newproperty(:privileges, :array_matching => :all) do newproperty(:privileges, :array_matching => :all) do
desc "The privileges the user should have. The possible values are implementation dependent." desc "The privileges the user should have. The possible values are implementation dependent."
munge do |v| munge do |v|
symbolize(v) v.intern
end end
def should_to_s(newvalue = @should) def should_to_s(newvalue = @should)

View file

@ -12,8 +12,6 @@ Puppet::Type.newtype(:mysql_user) do
if value.split('@').first.size > 16 if value.split('@').first.size > 16
raise ArgumentError, raise ArgumentError,
"MySQL usernames are limited to a maximum of 16 characters" "MySQL usernames are limited to a maximum of 16 characters"
else
super
end end
end end
end end

View file

@ -14,8 +14,10 @@ define mysql::admin_user(
password_hash => $password_hash, password_hash => $password_hash,
require => Exec['mysql_set_rootpw'], require => Exec['mysql_set_rootpw'],
} }
if $ensure == 'present' {
mysql_grant{"${name}@${host}": mysql_grant{"${name}@${host}":
privileges => 'all', privileges => 'all',
require => Mysql_user["${name}@${host}"], require => Mysql_user["${name}@${host}"],
} }
} }
}

View file

@ -4,4 +4,10 @@ class mysql::client::base {
ensure => present, ensure => present,
alias => 'mysql-client', alias => 'mysql-client',
} }
if $::operatingsystem in ['RedHat', 'CentOS'] and
$::operatingsystemmajrelease > 6 {
Package[mysql]{
name => 'mariadb'
}
}
} }

View file

@ -1,8 +0,0 @@
# some installations have some default users which are not required.
# We remove them here. You can subclass this class to overwrite this behavior.
class mysql::server::account_security {
mysql_user{ [ "root@${::fqdn}", 'root@127.0.0.1', "@${::fqdn}", '@localhost', '@%' ]:
ensure => 'absent',
require => Exec['mysql_set_rootpw'],
}
}

View file

@ -8,10 +8,10 @@ class mysql::server::base {
path => '/etc/mysql/my.cnf', path => '/etc/mysql/my.cnf',
source => [ source => [
"puppet:///modules/site_mysql/${::fqdn}/my.cnf", "puppet:///modules/site_mysql/${::fqdn}/my.cnf",
"puppet:///modules/site_mysql/my.cnf.${::operatingsystem}.{lsbdistcodename}", "puppet:///modules/site_mysql/my.cnf.${::operatingsystem}.${::operatingsystemmajrelease}",
"puppet:///modules/site_mysql/my.cnf.${::operatingsystem}", "puppet:///modules/site_mysql/my.cnf.${::operatingsystem}",
'puppet:///modules/site_mysql/my.cnf', 'puppet:///modules/site_mysql/my.cnf',
"puppet:///modules/mysql/config/my.cnf.${::operatingsystem}.{lsbdistcodename}", "puppet:///modules/mysql/config/my.cnf.${::operatingsystem}.${::operatingsystemmajrelease}",
"puppet:///modules/mysql/config/my.cnf.${::operatingsystem}", "puppet:///modules/mysql/config/my.cnf.${::operatingsystem}",
'puppet:///modules/mysql/config/my.cnf' 'puppet:///modules/mysql/config/my.cnf'
], ],
@ -31,16 +31,10 @@ class mysql::server::base {
owner => mysql, owner => mysql,
group => mysql, group => mysql,
mode => '0755'; mode => '0755';
'mysql_ibdata1':
path => '/var/lib/mysql/data/ibdata1',
require => Package['mysql-server'],
before => File['mysql_setmysqlpass.sh'],
owner => mysql,
group => mysql,
mode => '0660';
'mysql_setmysqlpass.sh': 'mysql_setmysqlpass.sh':
path => '/usr/local/sbin/setmysqlpass.sh', path => '/usr/local/sbin/setmysqlpass.sh',
source => "puppet:///modules/mysql/scripts/${::operatingsystem}/setmysqlpass.sh", source => ["puppet:///modules/mysql/scripts/${::operatingsystem}/setmysqlpass.sh.${::operatingsystemmajrelease}",
"puppet:///modules/mysql/scripts/${::operatingsystem}/setmysqlpass.sh", ],
require => Package['mysql-server'], require => Package['mysql-server'],
owner => root, owner => root,
group => 0, group => 0,
@ -57,7 +51,6 @@ class mysql::server::base {
exec { 'mysql_set_rootpw': exec { 'mysql_set_rootpw':
command => '/usr/local/sbin/setmysqlpass.sh', command => '/usr/local/sbin/setmysqlpass.sh',
unless => 'mysqladmin -uroot status > /dev/null',
require => [ File['mysql_setmysqlpass.sh'], Service['mysql'] ], require => [ File['mysql_setmysqlpass.sh'], Service['mysql'] ],
# this is for security so that we only change the password # this is for security so that we only change the password
# if the password file itself has changed # if the password file itself has changed
@ -70,11 +63,7 @@ class mysql::server::base {
} }
if $mysql::server::optimize_cron { if $mysql::server::optimize_cron {
class { 'mysql::server::cron::optimize': include mysql::server::cron::optimize
optimize_hour => $mysql::server::optimize_hour,
optimize_minute => $mysql::server::optimize_minute,
optimize_day => $mysql::server::optimize_day,
}
} }
service { 'mysql': service { 'mysql':
@ -84,20 +73,8 @@ class mysql::server::base {
require => Package['mysql-server'], require => Package['mysql-server'],
} }
if $::mysql_exists == 'true' {
include mysql::server::account_security
# Collect all databases and users # Collect all databases and users
Mysql_database<<| tag == "mysql_${::fqdn}" |>> Mysql_database<<| tag == "mysql_${::fqdn}" |>>
Mysql_user<<| tag == "mysql_${::fqdn}" |>> Mysql_user<<| tag == "mysql_${::fqdn}" |>>
Mysql_grant<<| tag == "mysql_${::fqdn}" |>> Mysql_grant<<| tag == "mysql_${::fqdn}" |>>
} }
file { '/etc/mysql/conf.d':
ensure => directory,
owner => 'root',
group => 0,
mode => '0755',
}
}

View file

@ -1,9 +1,35 @@
# centos specific things # centos specific things
class mysql::server::centos inherits mysql::server::clientpackage { class mysql::server::centos inherits mysql::server::clientpackage {
if $::operatingsystemmajrelease > 6 {
Package['mysql-server']{
name => 'mariadb-server',
}
Service['mysql']{
name => 'mariadb',
}
} else {
Service['mysql']{ Service['mysql']{
name => 'mysqld', name => 'mysqld',
} }
}
File['mysql_main_cnf']{ File['mysql_main_cnf']{
path => '/etc/my.cnf', path => '/etc/my.cnf',
} }
file{
'/etc/mysql':
ensure => directory,
owner => root,
group => 0,
mode => '0644';
'/etc/mysql/conf.d':
ensure => directory,
recurse => true,
purge => true,
force => true,
owner => root,
group => 0,
mode => '0644',
notify => Service['mysql'];
}
} }

View file

@ -11,8 +11,14 @@ class mysql::server::cron::backup {
} }
} }
if versioncmp($::mysql_version,'5.1.68') > 0 {
$backup_command = "/usr/bin/mysqldump --default-character-set=utf8 --all-databases --create-options --flush-logs --lock-tables --single-transaction --events --ignore-table=mysql.event | gzip > ${mysql::server::backup_dir}/mysqldump.sql.gz && chmod 600 ${mysql::server::backup_dir}/mysqldump.sql.gz"
} else {
$backup_command = "/usr/bin/mysqldump --default-character-set=utf8 --all-databases --create-options --flush-logs --lock-tables --single-transaction | gzip > ${mysql::server::backup_dir}/mysqldump.sql.gz && chmod 600 ${mysql::server::backup_dir}/mysqldump.sql.gz"
}
cron { 'mysql_backup_cron': cron { 'mysql_backup_cron':
command => "/usr/bin/mysqldump --default-character-set=utf8 --all-databases --create-options --flush-logs --lock-tables --single-transaction | gzip > ${mysql::server::backup_dir}/mysqldump.sql.gz && chmod 600 ${mysql::server::backup_dir}/mysqldump.sql.gz", command => $backup_command,
user => 'root', user => 'root',
minute => 0, minute => 0,
hour => 1, hour => 1,

View file

@ -0,0 +1,6 @@
# install mysqltuner package
class mysql::server::tuner {
package{'mysqltuner':
ensure => present,
}
}