Want to compile a MySQL Cluster MGM API application?

Here is a quick way to compile a simple MGM API application. The example will get the state of all nodes in MySQL Cluster and print whether they are connected or not.

All this without a Makefile, we just want to have some simple example on Linux to see how it works. It’s basic, maybe, but sometimes useful to just have a peek.

Requirements

We assume that:

  1. you installed MySQL Cluster 6.3 or higher, preferably under /usr/local/mysql,
  2. your cluster is up and shiny,
  3. and ndb_mgmd runs on the same machine you are compiling the MGM API test application on.

The code

Save it in a file called mgmapi_test.cc (from the MySQL manual):

#include <stdlib.h>
#include <mgmapi/mgmapi.h>

int main()
{
  NdbMgmHandle handle = ndb_mgm_create_handle();
  ndb_mgm_set_connectstring(handle,"localhost");
  ndb_mgm_connect(handle,0,0,0);
  struct ndb_mgm_cluster_state *state = ndb_mgm_get_status(handle);
  for(int i=0; i < state->no_of_nodes; i++)
  {
    struct ndb_mgm_node_state *node_state= &state->node_states[i];
    printf("node with ID=%d ", node_state->node_id);

    if(node_state->version != 0)
      printf("connected\n");
    else
      printf("not connected\n");
  }
  free((void*)state);
  ndb_mgm_destroy_handle(&handle);
}

Compile & Run

Note that it goes all on one line, but you could also paste the following lines in a shell script:

(
 MYBASE="/usr/local/mysql";
 PATH="$MYBASE/bin:$PATH";
 g++ `mysql_config --libs` `mysql_config --cflags` -lndbclient \
  -I$MYBASE/include/storage/ndb \
  -o mgmapi_test mgmapi_test.cc
)

No errors? Lets run it!

Setting LD_LIBRARY_PATH doesn’t hurt:

(
  export LD_LIBRARY_PATH="/usr/local/mysql/lib";
  ./mgmapi_test
)

Result

The result should be something like this:

node with ID=1 connected
node with ID=2 connected
node with ID=3 connected
node with ID=4 connected
node with ID=10 connected
node with ID=11 not connected
node with ID=12 not connected
node with ID=13 not connected
..

FAQ:

  • Wouldn’t it be better to have a Makefile? Absolutely.

  • Will there be problems doing it above? Sure, but the error message should help; start by checking if the locations are OK.