1. Home
  2. Docs
  3. ClusterControl
  4. Developer Guide
  5. ClusterControl Domain Specific Language (DSL)
  6. Examples

Examples

Executing SQL commands and queries

The following example demonstrates how to execute an SQL query on an arbitrary host of a cluster and receive the results in an array. The return value of the host.executeSqlQuery() holds the success/failed status of the query, the error message and also the results in a two dimensional array.

function getSqlVariable(host, variableName)
{
  var query = "SHOW GLOBAL STATUS LIKE '$1'";
  var retval;
  var value;
  if (host.typeName() != "CmonHost")
    return #ARGS!;
  query.replace("$1", variableName);
  retval = host.executeSqlQuery(query);
  if (!retval["success"])
  {
    print("ERROR:", retval["errorMessage"]);
    return #N/A;
  }
  value = retval["result"][0, 1];
  if (value.looksInteger())
    return value.toInt();
  else if (value.looksULongLong())
    return value.toULongLong();
  else if (value.looksDouble())
    return value.toDouble();
  return value;
}
function main()
{
  var hosts = cluster::hosts();
  var value = getSqlVariable(hosts[0], "COM_SELECT");
  print("*** value: ", value);
  return value.isInt();
}

Here is an example that shows how to execute an SQL query on the Cmon Database:

var retval = CmonDb::executeSqlQuery("select * from mysql_states;");
var passed = true;
if (!retval["success"])
{
  error("Executing SQL query failed: ", retval["errorMessage"]);
}

for (idx = 0; idx < retval["result"].rows(); ++idx)
{
  var string = retval["result"][idx, 2];
  print(retval["result"][idx, 2]);
  if (string.empty())
  {
    error("Value at idx = ", idx, " is empty.");
  }
}

Executing shell commands

function listFiles(host)
{
  var retval = host.system("ls -lha /home");
  if (!retval["success"])
    error("ERROR: ", retval["errorMessage"]);
  print("Host    : ", host.hostName());
  print("Result  : ", retval["result"]);
  print("Success : ", retval["success"]);
  return retval["success"];
}

Obtaining and processing statistical information

The following example shows how to obtain statistical data from a specific host about a specific time interval and how to process the data using low-level indexing operators. For the most task there are more efficient high-level statistical functions that can be used without looping through the data, but low-level access can be also beneficial for custom calculations.

//
// Going through the memory statistics of the last 10 minutes and printing the
// size of the free memory with the time.
//
#include "cmon/io.h"
function toGigaBytes(value)
{
  return value / (1024 * 1024 * 1024);
}
function main()
{
  var host = cluster::hosts()[0];
  var endTime = CmonDateTime::currentDateTime();
  var startTime = endTime - 10 * 60;
  var stats = host.memoryStats(startTime, endTime);
  var retval = true;
  for (idx = 0; idx < stats.size(); ++idx)
  {
    map = stats[idx];
    created = CmonDateTime::fromUnixTime(map["created"]);
    ramfree = toGigaBytes(map["ramfree"]);
    print(
      created.toString(LongTimeFormat),
      " ", ramfree.toString(TwoDecimalNumber), "GBytes");
  }
  return retval;
}

The next example shows a sophisticated recipe to process some of the statistical data using high-level statistical functions. It first gets the data calling the host.memoryStats() function, then it filters all the memory utilization information into an array. This array then can be processed by statistical functions like min(), max() or percentile().

//
// Printing the min, the ninth percentile and the max of the memory utilization
// in the last ten minutes for every host. Prints something like this:
//
// MEMORY UTILIZATION
// HOST MIN NINTH MAX
// 127.0.0.1 42.00% - 42.58% - 42.64%
//
#include "cmon/io.h"
function printUtil(host, startTime, endTime)
{
  var list = host.memoryStats(startTime, endTime);
  var array = list.toArray("memoryutilization");
  var min = min(array);
  var max = max(array);
  var ninth = percentile(array, 0.9);
  print(host.hostName(),
    " ",
    min.toString(TwoDecimalPercent), " - ",
    ninth.toString(TwoDecimalPercent), " - ",
    max.toString(TwoDecimalPercent));

  return true;
}
function main()
{
  var endTime = CmonDateTime::currentDateTime();
  var startTime = endTime - 10 * 60;
  var hosts = cluster::hosts();

  print(" MEMORY UTILIZATION ");
  print("HOST MIN NINTH MAX");
  for (idx = 0; idx < hosts.size(); ++idx)
    printUtil(hosts[idx], startTime, endTime);
  return true;
}

Alarms

#include "cmon/alarms.h"
var hosts   = cluster::hosts();
var host    = hosts[0];
var alarms;
var found   = false;
//
// Raising an alarm
//
host.raiseAlarm(MySqlAdvisor, Critical, "Some message.");
//
// Reading the active alarms and searching for the same alarm.
//
alarms = host.alarms();
for (idx = 0; idx < alarms.size(); ++idx)
{
  if (alarms[idx]["title"] == "MySQL advisor alarm")
  {
    found = true;
    break;
  }
}
The following example demonstrates how to create a custom alarm type and raise an alarm with the custom alarm.

//
// Demonstrating custom alarms.
//
#include "cmon/alarms.h"
//
// This function returns an alarm type for a custom alarm with some
// properties encoded into the function.
//
function myAlarm()
{
  return Alarm::alarmId(
        Node, true,
        "Computer is on fire",
        "The computer is on fire, it is on flames.",
        "Pour some water on it.");
}
var myAlarmId = myAlarm();
var hosts     = cluster::hosts();
var host      = hosts[0];
var sentMessage;
sentMessage = host.raiseAlarm(myAlarmId, Critical);
//
// An alarm is raised and sentMessage should be:
// Server 127.0.0.1 reports: The computer is on fire, it is on flames.
//

Configuration files

function getConfiguredClientPort(host)
{
  var config      = host.config();
  var variable    = config.variable("port");
  for (idx = 0; idx < variable.size(); ++idx)
  {
    print("*** section  : ", variable[idx]["section"]);
    print("*** value    : ", variable[idx]["value"]);
    print("*** location : ",
          variable[idx]["filepath"], ":", variable[idx]["linenumber"]);
    if (variable[idx]["section"] == "client")
        return variable[idx]["value"].toInt();
  }
  return #N/A;
}

Creating graphs

The following example shows how to create a graph, set up with statistical data and return to the UI to be shown as an image.

//
// This is a test program that prints a graph on the sql statistics.
//
#include "cmon/graph.h"
var hosts     = cluster::hosts();
var host      = hosts[0];
var endTime   = CmonDateTime::currentDateTime();
var startTime = endTime - 10 * 60;
var stats     = host.sqlStats(startTime, endTime);
var array     = stats.toArray(
  "created,interval,COM_SELECT,COM_INSERT");
//
// Calculating some values from the statistics
//
for (idx = 0; idx < array.columns(); idx++)
{
  array[5, idx] = 1000 * array[2, idx] / array[1, idx];
  array[6, idx] = 1000 * array[3, idx] / array[1, idx];
}
var graph     = new CmonGraph;
graph.setXDataIsTime();
graph.setTitle("SQL Statistics " + host.toString());
graph.setSize(800, 600);
// This graph contains two plots, we set the various properties for them here
// here. The plot index will be 1 and 2.
graph.setPlotLegend(1, "Select (1/s)");
graph.setPlotColumn(1, 0, 5);
graph.setPlotStyle(1, Impulses);
graph.setPlotLegend(2, "Insert (1/s)");
graph.setPlotColumn(2, 0, 6);
graph.setPlotStyle(2, Impulses);
graph.setData(array);
exit(graph);

The following example shows how to interact with Mongo:

// Mongo JS example
function main()
{
    var hosts   = cluster::mongoNodes();
    for (i = 0; i < hosts.size(); i++)
    {
        host        = hosts[i];
        print(host.hostName());
        var config      = host.config();
        var variable    = config.variable("port");
        for (idx = 0; idx < variable.size(); ++idx)
        {
            print("*** section  : ", variable[idx]["section"]);
            print("*** value    : ", variable[idx]["value"]);
            print("*** location : ",
                    variable[idx]["filepath"], ":", variable[idx]["linenumber"]);
            if (variable[idx]["section"] == "client")
                return variable[idx]["value"].toInt();
        }
 
 
        var res= host.executeMongoQuery("{ serverStatus : 1 }");
        print(res["result"]["host"]);
        print(res["result"]["storageEngine"]["name"]);
 
        var endTime = CmonDateTime::currentDateTime();
        var startTime = endTime - 10 * 60;
        var stats     = host.mongoStats(startTime, endTime);
        var array     = stats.toArray("created,interval,opcounters.command");
        for (idx = 0; idx < array.columns(); idx++)
        {
            var x= 1000 * array[2, idx] / array[1, idx];
            //print(x);
        }
        break;
    }
}
Was this article helpful to you? Yes No