This is a follow-up on my previous blog post about using Lua enabled sysbench. Today I will dive into how to write Lua scripts for sysbench. Look at this simple example:

There are 3 functions prepare(), cleanup() and help(). Those are executed when sysbench is asked to perform the respective action (i.e. sysbench … help).

If you do sysbench ... run then things are different. First sysbench starts the requested number of threads and executes the thread_init() function for each. Prior to that each thread connects to the database server (using the sbtest database). Hence you need not (actually: must not) call db_connect() from thread_init(). The parameter thread_id runs from 1 to the requested number of threads.

After that sysbench pauses for a moment to give all threads the chance to finish initialization. Then each thread executes the event() function in a loop until either the limit on the number of requests (–max-requests) or the execution time limit (–max-time) has been reached.

Finally each thread executes the thread_done() function. Note: db_disconnect() is not automatically called when a sysbench thread exits. If sysbench connects directly to a MySQL server, this is no issue because when sysbench exits, all sockets are closed and MySQL terminates the related sessions. If you connect through some proxy, you might need to explicitly close the connection, just as I have done above.

If any of the mentioned Lua functions is empty, you can omit it from the Lua script. Above I added the thread_init() function only for sake of completeness.

Here is an example session using the Lua code from above:

If you know Lua, you might have noticed that demo.lua uses some nonstandard Lua functions. Sysbench adds several new functions to the Lua interpreter. The most important are probably db_query() and sb_rand(). There are many more. See the C function sb_lua_new_state() in script_lua.c from the sysbench source for a complete list.

You should also have a look at the delivered Lua code on how to use the functions.

Coming up next: extending oltp.lua …

Comments are closed.