Class: MysqlIsolatedServer

Inherits:
Object
  • Object
show all
Defined in:
lib/mysql_isolated_server.rb,
lib/mysql_isolated_server/version.rb

Constant Summary collapse

MYSQL_BASE_DIR =
"/usr"
VERSION =
"0.2.2"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ MysqlIsolatedServer



10
11
12
13
14
15
16
17
18
19
# File 'lib/mysql_isolated_server.rb', line 10

def initialize(options = {})
  @base = Dir.mktmpdir("mysql_isolated", "/tmp")
  @mysql_data_dir="#{@base}/mysqld"
  @mysql_socket="#{@mysql_data_dir}/mysqld.sock"
  @params = options[:params]
  @load_data_path = options[:data_path]
  @port = options[:port]
  @allow_output = options[:allow_output]
  @server_id = rand(2**31)
end

Instance Attribute Details

#baseObject (readonly)

Returns the value of attribute base.



6
7
8
# File 'lib/mysql_isolated_server.rb', line 6

def base
  @base
end

#paramsObject

Returns the value of attribute params.



7
8
9
# File 'lib/mysql_isolated_server.rb', line 7

def params
  @params
end

#pidObject (readonly)

Returns the value of attribute pid.



6
7
8
# File 'lib/mysql_isolated_server.rb', line 6

def pid
  @pid
end

#portObject (readonly)

Returns the value of attribute port.



6
7
8
# File 'lib/mysql_isolated_server.rb', line 6

def port
  @port
end

Instance Method Details

#boot!Object



73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/mysql_isolated_server.rb', line 73

def boot!
  @port ||= grab_free_port
  system("rm -Rf #{@mysql_data_dir}")
  system("mkdir #{@mysql_data_dir}")
  if @load_data_path
    system("cp -a #{@load_data_path}/* #{@mysql_data_dir}")
    system("rm -f #{@mysql_data_dir}/relay-log.info")
  else
    mysql_install_db = locate_executable("mysql_install_db")

    idb_path = File.dirname(mysql_install_db)
    system("(cd #{idb_path}/..; mysql_install_db --datadir=#{@mysql_data_dir} --user=`whoami`) >/dev/null 2>&1")
    system("cp #{File.expand_path(File.dirname(__FILE__))}/tables/user.* #{@mysql_data_dir}/mysql")
  end

  up!

  tzinfo_to_sql = locate_executable("mysql_tzinfo_to_sql5", "mysql_tzinfo_to_sql")
  raise "could not find mysql_tzinfo_to_sql" unless tzinfo_to_sql
  system("#{tzinfo_to_sql} /usr/share/zoneinfo 2>/dev/null | mysql -h127.0.0.1 --database=mysql --port=#{@port} -u root mysql ")
  connection.query("SET GLOBAL time_zone='UTC'")
  connection.query("SET GLOBAL server_id=#{@server_id}")
end

#cleanup!Object



162
163
164
# File 'lib/mysql_isolated_server.rb', line 162

def cleanup!
  system("rm -Rf #{base}")
end

#connectionObject



35
36
37
# File 'lib/mysql_isolated_server.rb', line 35

def connection
  @cx ||= Mysql2::Client.new(:host => "127.0.0.1", :port => @port, :username => "root", :password => "", :database => "mysql")
end

#down!Object



65
66
67
68
69
70
71
# File 'lib/mysql_isolated_server.rb', line 65

def down!
  Process.kill("TERM", @pid)
  while (Process.kill 0, @pid rescue false)
    sleep 1
  end
  @cx = nil
end

#exec_server(cmd) ⇒ Object



113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/mysql_isolated_server.rb', line 113

def exec_server(cmd)
  cmd.strip!
  cmd.gsub!(/\\\n/, ' ')
  devnull = File.open("/dev/null", "w")
  system("mkdir -p #{base}/tmp")
  system("chmod 0777 #{base}/tmp")

  original_pid = $$
  mysql_pid = nil

  middle_pid = fork do
    mysql_pid = fork do
      ENV["TMPDIR"] = "#{base}/tmp"
      if !@allow_output
        STDOUT.reopen(devnull)
        STDERR.reopen(devnull)
      end

      exec(cmd)
    end

    # begin waiting for the parent (or mysql) to die; at_exit is hard to control when interacting with test/unit
    # we can also be killed by our parent with down! and up!
    #
    trap("TERM") do
      Process.kill("KILL", mysql_pid) rescue nil
      cleanup!
      exit!
    end

    while true
      begin
        Process.kill(0, original_pid)
        Process.kill(0, mysql_pid)
      rescue Exception => e
        Process.kill("KILL", mysql_pid) rescue nil
        cleanup!
        exit!
      end

      sleep 1
    end

    at
  end

  @pid = middle_pid
end

#grab_free_portObject



97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/mysql_isolated_server.rb', line 97

def grab_free_port
  while true
    candidate=9000 + rand(50_000)

    begin
      socket = Socket.new(:INET, :STREAM, 0)
      socket.bind(Addrinfo.tcp("127.0.0.1", candidate))
      socket.close
      return candidate
    rescue Exception => e
      puts e
    end
  end
end

#kill!Object



166
167
168
169
# File 'lib/mysql_isolated_server.rb', line 166

def kill!
  return unless @pid
  system("kill -KILL #{@pid}")
end

#locate_executable(*candidates) ⇒ Object



45
46
47
48
49
# File 'lib/mysql_isolated_server.rb', line 45

def locate_executable(*candidates)
  output = `which #{candidates.join(' ')}`
  raise "I couldn't find any of these: #{candidates.join(',')} in $PATH" if output.chomp.empty?
  output.split("\n").first
end

#make_slave_of(master) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/mysql_isolated_server.rb', line 21

def make_slave_of(master)
  master_binlog_info = master.connection.query("show master status").first
  connection.query("    change master to master_host='127.0.0.1',\n                     master_port=\#{master.port},\n                     master_user='root', master_password='',\n                     master_log_file='\#{master_binlog_info['File']}',\n                     master_log_pos=\#{master_binlog_info['Position']}\n    EOL\n  )\n  connection.query(\"SLAVE START\")\n  connection.query(\"SET GLOBAL READ_ONLY=1\")\nend\n"

#set_rw(rw) ⇒ Object



39
40
41
42
# File 'lib/mysql_isolated_server.rb', line 39

def set_rw(rw)
  ro = rw ? 0 : 1
  connection.query("SET GLOBAL READ_ONLY=#{ro}")
end

#up!Object



51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/mysql_isolated_server.rb', line 51

def up!
  mysqld = locate_executable("mysqld")

  exec_server "      \#{mysqld} --no-defaults --default-storage-engine=innodb \\\n              --datadir=\#{@mysql_data_dir} --pid-file=\#{@base}/mysqld.pid --port=\#{@port} \\\n              \#{@params} --socket=\#{@mysql_data_dir}/mysql.sock --log-bin --log-slave-updates\n  EOL\n\n  while !system(\"mysql -h127.0.0.1 --port=\#{@port} --database=mysql -u root -e 'select 1' >/dev/null 2>&1\")\n    sleep(0.1)\n  end\nend\n"