2015-04-09 20:01:23 +00:00
|
|
|
# encoding: utf-8
|
|
|
|
# copyright: 2015, Dominik Richter
|
|
|
|
# license: All rights reserved
|
|
|
|
|
2015-06-22 16:21:09 +00:00
|
|
|
$__SCOPE = self
|
2015-06-22 15:57:07 +00:00
|
|
|
|
2015-06-22 14:18:40 +00:00
|
|
|
class MysqlSession < Vulcano::Resource
|
2015-04-09 20:01:23 +00:00
|
|
|
def initialize user, pass
|
|
|
|
@user = user
|
|
|
|
@pass = pass
|
2015-06-22 13:24:35 +00:00
|
|
|
@runner = Specinfra::Runner
|
|
|
|
initialize_fallback if user.nil? or pass.nil?
|
2015-06-22 14:18:40 +00:00
|
|
|
skip_resource("Can't run MySQL SQL checks without authentication") if @user.nil? or @pass.nil?
|
2015-04-09 20:01:23 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def describe(query, db = "", &block)
|
|
|
|
# TODO: simple escape, must be handled by a library
|
|
|
|
# that does this securely
|
|
|
|
escaped_query = query.gsub(/\\/, '\\\\').gsub(/"/,'\\"').gsub(/\$/,'\\$')
|
|
|
|
# run the query
|
|
|
|
cmd = Serverspec::Type::Command.new("mysql -u#{@user} -p#{@pass} #{db} -s -e \"#{escaped_query}\"")
|
|
|
|
out = cmd.stdout + "\n" + cmd.stderr
|
|
|
|
if out =~ /Can't connect to .* MySQL server/ or
|
|
|
|
out.downcase =~ /^error/
|
|
|
|
# skip this test if the server can't run the query
|
2015-06-22 14:33:22 +00:00
|
|
|
skip_resource("Can't connect to MySQL instance for SQL checks.")
|
2015-04-09 20:01:23 +00:00
|
|
|
else
|
2015-06-22 15:57:07 +00:00
|
|
|
$__SCOPE.describe(cmd, &block)
|
2015-04-09 20:01:23 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2015-06-22 13:24:35 +00:00
|
|
|
private
|
|
|
|
|
|
|
|
def initialize_fallback
|
|
|
|
# support debian mysql administration login
|
|
|
|
debian = @runner.run_command("test -f /etc/mysql/debian.cnf && cat /etc/mysql/debian.cnf").stdout
|
|
|
|
unless debian.empty?
|
|
|
|
user = debian.match(/^\s*user\s*=\s*([^ ]*)\s*$/)
|
|
|
|
pass = debian.match(/^\s*password\s*=\s*([^ ]*)\s*$/)
|
|
|
|
return if user.nil? or pass.nil?
|
|
|
|
@user = user[1]
|
|
|
|
@pass = pass[1]
|
|
|
|
return
|
|
|
|
end
|
|
|
|
end
|
2015-04-09 20:01:23 +00:00
|
|
|
end
|
|
|
|
|
2015-06-22 13:24:35 +00:00
|
|
|
def start_mysql_session( user=nil, password=nil )
|
2015-04-09 20:01:23 +00:00
|
|
|
MysqlSession.new(user, password)
|
|
|
|
end
|