How-to add new device to cacti by script

Adding many devices to cacti is a tedious work. For NoSQL DB, they always have lots of hosts in a cluster. So I wrote a script to add them easily.

<?php

#This script auto_add_device.php is to add new device automatically
#
#Table auto_add_list is source of new hosts
#create table auto_add_list (
#id mediumint(8) unsigned NOT NULL auto_increment,
#hostname varchar(100) not null,
#tree varchar(100) not null,
#type varchar(100) not null,
#status varchar(100) not null default 'new',
#create_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
#last_update_date datetime,
#PRIMARY KEY (id),
#CONSTRAINT uc_hostname_type UNIQUE (hostname,type)
#);
#
#type: Linux, MongoDB, Cassandra, MySQLInnodb, MySQLMemory, pushVM
#tree: MongoDB-szoommdb
#status: new, added, failed
#
#insert into auto_add_list(hostname,type,tree) values ('alexzeng.wordpress.com','MongoDB','MongoDB-alexzeng');

$CACTI_HOME = '/export/home/cacti';
$mysql_host = '';      #localhost by default
$mysql_user = 'cacti';
$mysql_pass = 'password';
$mysql_port = 3306;
$mysql_ssl  = FALSE;   # Whether to use SSL to connect to MySQL.

#Call main functions
connect_db();
add_device();

# ============================================================================
# This is the main function. 
# ============================================================================
function add_device() {
   #print("The start\n");
   $result = run_query("select id,hostname,tree,type from auto_add_list where status='new'");
   foreach ( $result as $row ) {  
     if ( $row && is_array($row) 
      && array_key_exists('hostname', $row) 
      && array_key_exists('type', $row) 
      )
     {
        $hostname  = $row['hostname'];  
        $type = strtoupper($row['type']);
        $id = $row['id'] ;            
        $tree = $row['tree'];    
        $status = 'new';
        if ( $type == 'LINUX' ) {
          print("Add Linux host $hostname \n");          
          #...
        } elseif ( $type == 'MONGODB' ) {
          print("Add MongoDB host $hostname \n");
          add_device_general($type, $hostname, $tree);
          $status = 'added';
        } elseif ( $type == 'CASSANDRA' ) {
          print("Add Cassandra host $hostname \n");         
          #...
        } elseif ( $type == 'MYSQLINNODB' ) {
          print("Add MySQLInnodb host $hostname \n");         
          #...
        } elseif ( $type == 'MYSQLMEMORY' ) {
          print("Add MySQLMemory host $hostname \n");         
          #...
        } elseif ( $type == 'PUSHVM' ) {
          print("Add pushVM host $hostname \n");         
          #...
        } else {
          print("unknown type: $type \n");
          $status = 'unknown type';
        }
        if ($id == 1) {
          print("id $id\n");
        }
        $result = run_query("update auto_add_list set status='$status', last_update_date=CURRENT_TIMESTAMP() where id=$id ");        
     }
   }
  #print("The end\n");
}

# ============================================================================
# Add general devices
# ============================================================================
function add_device_general($device_type, $hostname, $tree ) {
  global $CACTI_HOME;
  
  $result = explode('.', $hostname);
  $short_name = @$result[0];
  #print("$hostname $short_name\n");
  
  #Add device
  $host_template_id = get_host_template_id($device_type);
  print("host_template_id $host_template_id\n");
  `php -q $CACTI_HOME/cli/add_device.php --description=$short_name --ip=$hostname --avail=none --version='' --template=$host_template_id`;
  
  #Add graphs
  $host_id = get_host_id($hostname);
  $result = run_query("SELECT " .
                             "host_template_graph.graph_template_id AS id " .
                     "FROM host_template_graph " .
                     "LEFT JOIN graph_templates " .
                             "ON (host_template_graph.graph_template_id = graph_templates.id) " .
                     "WHERE host_template_id = $host_template_id");
  foreach( $result as $row ) {
    if ( $row && is_array($row) ) {
      $graph_template_id = $row['id'];
       print("graph_template_id $graph_template_id\n");
      `php -q $CACTI_HOME/cli/add_graphs.php --graph-type=cg --host-id=$host_id --graph-template-id=$graph_template_id`;
    }
  }
  
  #Add it to tree
  print("Add it to tree\n");
  list($parent_node, $subheader_name) = explode('-', $tree);
  print("parent_node $parent_node\n");
  $parent_id = get_tree_id($parent_node);
  if ( $subheader_name ) {
     print("subheader_name $subheader_name\n");
     $sub_header_id = get_subheader_id($subheader_name);
     if($sub_header_id == -1) {
        print("$subheader_name doesn't exist, add it\n");
       `php -q $CACTI_HOME/cli/add_tree.php --type=node --node-type=header --tree-id=$parent_id --name="$subheader_name"`;
       $sub_header_id = get_subheader_id($subheader_name);
     }
     print("sub_header_id $sub_header_id\n");
    `php -q $CACTI_HOME/cli/add_tree.php --type=node --node-type=host --tree-id=$parent_id --host-id=$host_id --parent-node=$sub_header_id`;
  } else {
    `php -q $CACTI_HOME/cli/add_tree.php --type=node --node-type=host --tree-id=$parent_id --host-id=$host_id`;
  }
}

function get_subheader_id($subheader_name) {
  $query = "select id from graph_tree_items WHERE graph_tree_id=4 and upper(title)=upper('$subheader_name')";
  $id = run_query_get_id($query);
  return $id;
}

function get_tree_id($treename) {
  $query = "select id from graph_tree where upper(name) like upper('%$treename%') ";
  $id = run_query_get_id($query);
  return $id;
}

function get_host_template_id($type) {
  $query = "select id from host_template where upper(name) like upper('%$type%')";
  $id = run_query_get_id($query);
  return $id;
}

function get_host_id($hostname) {
  $query = "select id from host where hostname='$hostname' ";
  $id = run_query_get_id($query);
  return $id;
}

#Run given query, and get the first row in it's result
function run_query_get_id ($query) {
  $result = run_query($query);
  $id = -1;
  #print_r($result);
  foreach ( $result as $row ) {
    if ( $row && is_array($row) ) {
      $id = $row[0];
      #print("id $id\n");
      break;
    }
  }
  return $id;
}

# ============================================================================
# Wrap mysql_query in error-handling, and instead of returning the result,
# return an array of arrays in the result.
# ============================================================================
function run_query($sql) {
   global $conn;
   #print("sql $sql\n");
   $result = @mysql_query($sql, $conn);
   $array = array();
   while ( $row = @mysql_fetch_array($result) ) {
      $array[] = $row;
      #print_r($row);
   }
   return $array;
}

function connect_db() {
   # Process connection options and connect to MySQL.
   global $mysql_host, $mysql_user, $mysql_pass, $mysql_port, $mysql_ssl, $conn;
   # Connect to MySQL.
   $user = $mysql_user;
   $pass = $mysql_pass;
   $port = $mysql_port;
   if ( !extension_loaded('mysql') ) {
      print("The MySQL extension is not loaded");
      die("The MySQL extension is not loaded");
   }
   if ( $mysql_ssl ) {
      $conn = mysql_connect($mysql_host, $user, $pass, true, MYSQL_CLIENT_SSL);
   }
   else {
      $conn = mysql_connect($mysql_host, $user, $pass);
   }
   if ( !$conn ) {
      die("MySQL: " . mysql_error());
   }
   $db_selected = mysql_select_db('cacti', $conn);
   if (!$db_selected) {
     die ('Can\'t use cacti : ' . mysql_error());
   }
}
?>

With this script, what you need to do is just add one row to the table as follows:

insert into auto_add_list(hostname,type,tree) values ('alexzeng.wordpress.com','MongoDB','MongoDB-alexzeng'); 

As usual, it’s not a perfect script but it’s a good start 🙂

Advertisements

About Alex Zeng
I would be very happy if this blog can help you. I appreciate every honest comments. Please forgive me if I'm too busy to reply your comments in time.

2 Responses to How-to add new device to cacti by script

  1. melik says:

    I want to add 200+ IP addresses as including name of the host. Such as;

    Description: xyz Server
    Hostname: 192.168.1.1
    Host Template: Cisco
    Thold Up/Down Email Notification: Global List
    Downed Device Detection: Ping
    Ping Method: ICMP Ping

    adding manually like this takes to much time. Give advise how to handle this issue with script, please !

    P.s: my cacti “version 0.8.8a”

    • Alex Zeng says:

      You can just change the script for your usage. I didn’t take much time to change it.
      Regards,
      Alex

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: