Minggu, Mei 28, 2017

Sistem Monitoring dengan Script PHP

Udah lama ga posting.
Lagi develop kecil2an sistem monitoring Linux dengan scrip PHP.
Saya kasih nama RMonit, dibawah lisensi GPL-v2.

Ada 4 file:
- BACADULU.txt
- rmonit_config.php
- rmonit_function.php
- rmonit_cek.php

Fungsi:
monitoring uptime (dg ping), disk, spu, dan ram usage.
Output:
SMS alert.

Silakan pakai, dan kembangkan. Jangan lupa mencantumkan sumber.
SMS gateway menggunakan zenziva.net.

BACADULU.txt

*********************************************************************
*                                                      *
*   RMonit v1.0.0.rc1 (Monitoring system with PHP)                *
*   Oleh   : Raka Yusuf                                      *
*   License: GNU GPL-v2                                      *
*                                                      *
*********************************************************************
RMonit  adalah  sistem monitoring  berbasis PHP-CLI,  bukan web-based
PHP. RMonit memonitor uptime host (dengan ping), penggunaan CPU, RAM,
dan disk,  baik lokal maupun remote, TAPI HANYA LINUX.  Ditambah lagi
dengan monitoring  replikasi Galera  Cluster (MariaDB).  Use it  with
your own risks!

Cara menggunakan RMonit:
1. Sediakan dulu DB di MySQL utk Log, nama DB bebas.  Nama tabel juga
   bebas. Di host mana bebas juga. Catat nama host, nama DB, nama ta-
   bel, user, dan pswd. Isikan di file konfig rmonit_config.php
2. Struktur tabel log pada poin (1) adalah sbb:
    CREATE TABLE nama_table (
  id INT auto_increment,
  tgl DATETIME,
  host VARCHAR(15),
  service VARCHAR(10),
  status INT default 1,
  count INT default 0,
  PRIMARY KEY (id)
    )
3. Pada file konfig,  sesuaikan mana  yang mau dimonitor.  Baca komen
   pada file konfig.
4. PHP harus diinstal dg modul cURL dan mysql. Misal:
   di debian,
       apt-get install php5 php5-mysql php5-curl
   WARNING: RMonit tidak jalan di PHP7.0!!
4. Ada  baiknya menginstal  modul php5-snmp  supaya tidak ada warning
   soal snmp (optional).
5. Tambahkan di crontab
       */2 * * * * /path-ke-rmonit/rmonit_cek.php
   bila diinginkan pengecekan tiap 2 menit.
6. Untuk pengecekan disk, CPU, dan RAM secara remote,  host yg dituju
   harus sudah dapat dihubungi dg ssh tanpa perlu login.  Gunakan pe-
   rintah:
      #ssh-keygen
      #ssh-copy-id -i ~/.ssh/id-rsa.pub [ip-host-tujuan]
   silakan googling untuk hal ini.
7. Selamat mencoba.

Change Log:
1.0.0rc1
- dapat  digunakan juga  untuk  pengecekan  remote host  untuk uptime
  (dengan ping), disk usage, CPU usage, dan RAM usage
- perubahan konfig ping menjadi {IP, NamaHost, PingCycle}
- perubahan konfig disk menjadi {IP, NamaHost, Limit}
- perubahan konfig CPU menjadi  {IP, NamaHost, Limit}
- perubahan konfig RAM menjadi  {IP, NamaHost, Limit}
- pengecekan disk, cpu, ram dilakukan bila host hidup (dicek dg ssh)

0.6.3
- Menambahkan berapa lama host down (service: ping)
- Menambahkan $pesanSMS dan membuang "Silakan periksa" dari SMS untuk

  host UP (service: ping)



rmonit_config.php

<?php
// RMonit v1.0.0.rc1 (Monitoring system with PHP)
// Oleh   : Raka Yusuf
// License: GNU GPL-v2
/********************************************************************
** Setting monitoring   **
********************************************************************/
// Data Center ID, untuk membedakan posisi RMonit bila ada
// lebih dari 1 DC
$rm_dc_id = "IDC";
// Daftarkan host yang akan dipantau di sini (disk, cpu, ram)
// Kosongkan array bila tidak ingin dicek. WARNING: Linux Only!!
// Format:
// ("ip1","nama1","limit%1","ip2","nama2","limit%2", ...)
// WARNING: harus sudah diset agar RMonit dpt mengakses SSH pd host2
// tsb TANPA LOGIN. Silakan googling bagaimana caranya.
$rm_disk_list = array("10.1.1.181", "bl01",  "80%",
       "10.1.1.182", "bl02",    "80%",
       "10.1.1.183", "bl03",    "80%",
       "10.1.1.187", "fuji",    "80%",
       "10.1.1.191", "pr01",    "80%",
       "10.1.1.192", "pr02",    "80%");
$rm_cpu_list =  array("10.1.1.181", "bl01",  "90%",
       "10.1.1.182", "bl02",    "90%",
       "10.1.1.183", "bl03",    "90%",
       "10.1.1.187", "fuji",    "90%",
       "10.1.1.191", "pr01",    "90%",
       "10.1.1.192", "pr02",    "90%");
$rm_ram_list =  array("10.1.1.181", "bl01",  "80%",
       "10.1.1.182", "bl02",    "80%",
         "10.1.1.183", "bl03",    "80%",
         "10.1.1.187", "fuji",    "80%",
         "10.1.1.191", "pr01",    "80%",
         "10.1.1.192", "pr02",    "80%");
// untuk ping, nilai ketiga ialah ping-count, yakni berapa kali ping
// dalam 1 sesi ping
$rm_ping_list = array("10.1.1.181", "bl01",  "1",
       "10.1.1.182", "bl02",    "1",
       "10.1.1.183", "bl03",    "1",
       "10.1.1.186", "bl06",    "1",
       "10.1.1.187", "fuji",    "2",
       "10.1.1.191", "pr01",    "2",
       "10.1.1.192", "pr02",    "2");
// Isi dg directory disk yang akan dimonitor
$rm_disk         = "/";
// Isi dg berapa cycle baru RMonit laporan, agar tidak sering2
// lapor. contoh: crontab tiap 2 mnt dg cycle=3 maka laporan
// paling cepat 6 mnt
$rm_ping_cycle = 3;
$rm_disk_cycle = 5;
$rm_ram_cycle  = 5;
$rm_cpu_cycle  = 9;
// Isi dg nomor HP tujuan alert, pisahkan dg koma
$telepon = "087787654321,085712345678";

/** Konfigurasi khusus Replikasi MariaDB Galera Cluster **/
// rmon_galera: isi dengan "yes" untuk memonitor replikasi
$rmon_galera   = "no";
$rmon_galera_cycle = 1;
// Konfigurasi mysql untuk monitor replikasi Galera
$galHost = "localhost";
$galUser = "moodle_user";
$galPswd = "admin1234";

/*************************************************
**              Konfigurasi RMonit              **
*************************************************/
// zenziva API key (www.zenzifa.com)
$userkey = "abcdef";
$passkey = "123456";
// konfigurasi mysql  untuk log monitoring
$rmHost  = "localhost";
$rmDB    = "rmonit";
$rmTable = "tb_log";
$rmUser  = "rmonit";
$rmPswd  = "rm@1234";
?>

rmonit_function.php

<?php
// RMonit v1.0.0rc1 (Monitoring system with PHP)
// Oleh   : Raka Yusuf
// License: GNU GPL-v2

require 'rmonit_config.php';

// function compare dg log utk menahan agar tdk banyak alert
function compareLog($dbConn,$rmTable, $host, $service, $userkey, $passkey) {
  $q = "SELECT * FROM $rmTable WHERE host='$host' AND service='$service' ";
  if ($rs=mysql_query($q, $dbConn)) {
    $row=mysql_fetch_array($rs);
    return (($row['status']==1) ? True : False);
    //echo "IF then\n";
  } else {
    // insert
    $tgl = date("Y-m-d h:i:s");
    $q = "INSERT INTO $rmTable(tgl, host, service) VALUES ('$tgl', '$host', '$service')";
    //echo "$q\n";
    if (mysql_query($q, $dbConn)) echo "INSERT OK\n"; else "INSERT gagal.\n";
    return True;
    //echo "IF else\n";
  }
}


// function utk kirim SMS via Zenziva API
function kirimSms($host, $namaHost, $service, $desc) {
  $dc_id  = $GLOBALS['rm_dc_id'];
  $userkey= $GLOBALS['userkey'];
  $passkey= $GLOBALS['passkey'];
  $stTelp = $GLOBALS['telepon'];
  $tgl = Date("Y-m-d H:i:s");
  $arTel = explode(",", $stTelp);
  $pesan = "$tgl\nHost: $host ($namaHost), Service: $service, Status: $desc\n \nSent from:\nRMonit on " . gethostname() . " [DC: $dc_id]";
  for($i=0;$i<count($arTel);$i++) {
    $url ="https://alpha.zenziva.net/apps/smsapi.php";
    $curlHandle = curl_init();
    curl_setopt($curlHandle, CURLOPT_URL, $url);
    curl_setopt($curlHandle, CURLOPT_POSTFIELDS, "userkey=" . $userkey . "&passkey=" . $passkey . "&nohp=" . $arTel[$i] . "&pesan=" . urlencode($pesan));
    curl_setopt($curlHandle, CURLOPT_HEADER, 0);
    curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curlHandle, CURLOPT_SSL_VERIFYHOST, 2);
    curl_setopt($curlHandle, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($curlHandle, CURLOPT_TIMEOUT,30);
    curl_setopt($curlHandle, CURLOPT_POST, 1);
    $results = curl_exec($curlHandle);
    curl_close($curlHandle);
    syslog(LOG_INFO, "[RMonit] SMS to " . $arTel[$i] . ": $pesan");
  }
}

// cek ping
function pingFail($host, $count=1) {
  $ping=shell_exec("ping $host -c $count");
  if (stripos($ping,"ttl=")>0) return False; else return True;
}

// cek disk usage
function diskOverLimit($host, $path, $batasAtas) {
  $cmd = "ssh root@$host \"df $path\" ";
  $df = shell_exec($cmd);
  while (stripos($df,"  ")>0) $df=str_replace("  "," ",$df);
  $ar = explode(" ",$df);
  $usage= $ar[10];
  //echo "$host disk $path usage $usage\n";
  return (floatval($usage)>=floatval($batasAtas));
}

// cek penggunaan RAM
function ramOverLimit($host, $batasAtas){
    $free = shell_exec("ssh root@$host 'free' ");
    $free = (string)trim($free);
    $free_arr = explode("\n", $free);
    $mem1 = explode(" ", $free_arr[1]);
    $mem1 = array_filter($mem1);
    $mem1 = array_merge($mem1);
    $mem2 = explode(" ", $free_arr[2]);
    $mem2 = array_filter($mem2);
    $mem2 = array_merge($mem2);
    $usage = $mem1[2]/$mem1[1]*100;
    if ($usage>=floatval($batasAtas)) $usage = $mem2[2]/$mem1[1]*100;
    //echo "$host mem usage $usage/" . floatval($batasAtas) . "\n";
    return ($usage>=floatval($batasAtas));
}

// cek penggunaan CPU
function cpuOverLimit($host, $batasAtas){
  $cmd = "ssh root@$host 'top -bn2 | grep \"Cpu(s)\" ' ";
  $data= shell_exec($cmd);
  while (stripos($data,"  ")>0) $data=str_replace("  "," ",$data);
  $ar = explode(" ",$data);
  $used  = $ar[17]+$ar[19]+$ar[27]+$ar[24]+$ar[28]; // us, sy, hi, wa, si
  $idle  = $ar[23]; // id
  $total = $used + $idle;
  $total = ($total < 1) ? 100 : $total;
  $load  = floor(100*($used / $total * 100))/100;
  $load .= "%";
  //echo "$host used=$used; idle=$idle; total=$total; load=$load\n";
  return (floatval($load)>=floatval($batasAtas));
}

// function utk cek replikasi galera cluster
function replikasiFailed($host, $user, $pswd) {
  mysql_connect($host,$user,$pswd) or die("ga konek!");
  $q="show status like 'wsrep_%'";
  $h=mysql_query($q);
  $syarat=0;
  $target=3;
  while($row = mysql_fetch_array($h)) {  // MYSQL_ASSOC
      if ($row[0]=="wsrep_ready" and $row[1]=="ON") $syarat++;
      if ($row[0]=="wsrep_connected" and $row[1]=="ON") $syarat++;
      if ($row[0]=="wsrep_local_state_comment" and $row[1]=="Synced") $syarat++;
  }
  //mysql_close();
  if ($syarat>=$target) return False; else return True;
}

?>

rmonit_cek.php

#!/usr/bin/php5
<?php
// RMonit v1.0.0rc1 (Monitoring system with PHP)
// Oleh   : Raka Yusuf
// License: GNU GPL-v2

require 'rmonit_config.php';
require 'rmonit_function.php';

// open db connection
if (!($con1=mysql_connect($rmHost, $rmUser, $rmPswd))) die("Ga konek!");
mysql_select_db($rmDB, $con1) or die("DB Error!");

// cek ping (local dan remote)
// service: ping
$service = "ping";
if (count($rm_ping_list)>1) {
  // bila ada daftar yang akan dicek disk-nya
  $tgl=date("Y-m-d H:i:s");
  $jumHost = floor(count($rm_ping_list)/3);
  for($i=0;$i<$jumHost;$i++) {
    $targetHost=$rm_ping_list[3*$i];
    $namaHost  =$rm_ping_list[3*$i+1];
    $pingCount =$rm_ping_list[3*$i+2];
    // cek di DB Log
    $q="SELECT * FROM $rmTable WHERE host='$targetHost' AND service='$service' ";
    $rs=mysql_query($q, $con1);
    if ($rs and (mysql_num_rows($rs)>0)) {
      // bila query berhasil dan ada datanya
      $row=mysql_fetch_array($rs);
      $status=$row['status'];
      $count=$row['count'];
      $tglDown=$row['tgl'];
      // utk ping tdk cek dulu apakah konek
      //if (shell_exec("ssh root@$targetHost \"ls /\" ")) {
        // cek limit
        if (pingFail($targetHost, $pingCount)) {
          // kalau ping failed, cek sudah berapa kali
          if ($count>=$rm_ping_cycle) {
            // bila sdh mencapai batas cycle, cek status
            $updateTgl = "";
            if ($status==1) {
              // bila status masih 1, kirim SMS dan update tgl pada Log
              $pesanSMS = "Host DOWN (gagal di-ping). Silakan periksa.";
              kirimSMS($targetHost, $namaHost, $service, $pesanSMS);
              $updateTgl = "tgl=Now(),";
            }
            // bila status tdk 1, tgl tdk diupdate
            $q="UPDATE $rmTable SET $updateTgl status=0, count=0 WHERE host='$targetHost' AND service='$service' ";
            mysql_query($q, $con1) or syslog(LOG_ERR,"[RMonit] UPDATE $targetHost/$service OVER Failed.\n");
          } else {
            // bila belum mencapai batas cycle, update count naik
            $count++;
            $q="UPDATE $rmTable SET count=$count WHERE host='$targetHost' AND service='$service'";
            mysql_query($q, $con1) or syslog(LOG_ERR,"[RMonit] UPDATE $targetHost/$service COUNT Failed.\n");
          } // end-if ($count>=$rm_ping_cycle)
        } else {
          // bila bisa di-ping
          if ($status==0) {
            // bila status terakhir 0, hitung selisih DOWN time
            $sec = strtotime(date("Y-m-d H:i:s"))-strtotime($tglDown);
            $sec += 60*$rm_disk_cycle;
            $jam = floor($sec/3600);
            $mnt = floor(($sec-3600*$jam)/60);
            $dtk = $sec-3600*$jam-60*$mnt;
            $jam = ($jam<10) ? "0".$jam : $jam;
            $mnt = ($mnt<10) ? "0".$mnt : $mnt;
            $dtk = ($dtk<10) ? "0".$dtk : $dtk;
            $wkt = "$jam:$mnt:$dtk";
            $pesanSMS="Host sudah UP lagi (down selama $wkt).";
            kirimSMS($targetHost, $namaHost, $service, $pesanSMS);
            $q="UPDATE $rmTable SET status=1, count=0 WHERE host='$targetHost' AND service='$service' ";
            mysql_query($q, $con1) or syslog(LOG_ERR, "[RMonit] UPDATE $targetHost/$service UNDER Failed.\n");
          } else {
            // kalau tdk over limit dan status=1, count harus dibuat 0
            $q="UPDATE $rmTable SET count=0 WHERE host='$targetHost' AND service='$service' ";
            mysql_query($q, $con1) or syslog(LOG_ERR, "[RMonit] UPDATE $targetHost/$service count=0 Failed.\n");
          } // end-if ($status==0)
        } // end-if (diskOverLimit())
      //} else {
        // bila no route to host
      //  syslog(LOG_ERR, "[RMonit] SSH $service: no route to host $targetHost.");
      //} // end-if check shell_exec
    } else {
      // targetHost dan service belum ada di Log
      $q="INSERT INTO $rmTable(tgl, host, service, count) VALUES('$tgl', '$targetHost', '$service', 0)";
      mysql_query($q, $con1) or syslog(LOG_ERR,"[RMonit] INSERT $targetHost/$service Failed.\n");
    } // end-if ($rs and (mysql_num_rows($rs)>0))
  } // end-for
} // end-if (count($rm_ping_list)>1)

// cek disk (local dan remote)
// service: disk
$service = "disk";
if (count($rm_disk_list)>1) {
  // bila ada daftar yang akan dicek disk-nya
  $tgl=date("Y-m-d H:i:s");
  $jumHost = floor(count($rm_disk_list)/3);
  for($i=0;$i<$jumHost;$i++) {
    $targetHost=$rm_disk_list[3*$i];
    $namaHost  =$rm_disk_list[3*$i+1];
    $limitHost =$rm_disk_list[3*$i+2];
    // cek di DB Log
    $q="SELECT * FROM $rmTable WHERE host='$targetHost' AND service='$service' ";
    $rs=mysql_query($q, $con1);
    if ($rs and (mysql_num_rows($rs)>0)) {
      // bila query berhasil dan ada datanya
      $row=mysql_fetch_array($rs);
      $status=$row['status'];
      $count=$row['count'];
      $tglDown=$row['tgl'];
      // cek dulu apakah konek
      if (shell_exec("ssh root@$targetHost \"ls /\" ")) {
        // cek limit
        if (diskOverLimit($targetHost, $rm_disk, $limitHost)) {
          // kalau disk sudah over limit, cek sudah berapa kali
          if ($count>=$rm_disk_cycle) {
            // bila sdh mencapai batas cycle, cek status
            $updateTgl = "";
            if ($status==1) {
              // bila status masih 1, kirim SMS dan update tgl pada Log
              $pesanSMS = "Disk OVER LIMIT (lebih dari $limitHost). Silakan periksa.";
              kirimSMS($targetHost, $namaHost, $service, $pesanSMS);
              $updateTgl = "tgl=Now(),";
            }
            // bila status tdk 1, tgl tdk diupdate
            $q="UPDATE $rmTable SET $updateTgl status=0, count=0 WHERE host='$targetHost' AND service='$service' ";
            mysql_query($q, $con1) or syslog(LOG_ERR,"[RMonit] UPDATE $targetHost/$service OVER Failed.\n");
          } else {
            // bila belum mencapai batas cycle, update count naik
            $count++;
            $q="UPDATE $rmTable SET count=$count WHERE host='$targetHost' AND service='$service'";
            mysql_query($q, $con1) or syslog(LOG_ERR,"[RMonit] UPDATE $targetHost/$service COUNT Failed.\n");
          } // end-if ($count>=$rm_disk_cycle)
        } else {
          // bila tidak over limit
          if ($status==0) {
            // bila status terakhir 0, hitung selisih DOWN time
            $sec = strtotime(date("Y-m-d H:i:s"))-strtotime($tglDown);
            $sec += 60*$rm_disk_cycle;
            $jam = floor($sec/3600);
            $mnt = floor(($sec-3600*$jam)/60);
            $dtk = $sec-3600*$jam-60*$mnt;
            $jam = ($jam<10) ? "0".$jam : $jam;
            $mnt = ($mnt<10) ? "0".$mnt : $mnt;
            $dtk = ($dtk<10) ? "0".$dtk : $dtk;
            $wkt = "$jam:$mnt:$dtk";
            $pesanSMS="Disk sudah di bawah limit $limitHost (over selama $wkt).";
            kirimSMS($targetHost, $namaHost, $service, $pesanSMS);
            $q="UPDATE $rmTable SET status=1, count=0 WHERE host='$targetHost' AND service='$service' ";
            mysql_query($q, $con1) or syslog(LOG_ERR, "[RMonit] UPDATE $targetHost/$service UNDER Failed.\n");
          } else {
            // kalau tdk over limit dan status=1, count harus dibuat 0
            $q="UPDATE $rmTable SET count=0 WHERE host='$targetHost' AND service='$service' ";
            mysql_query($q, $con1) or syslog(LOG_ERR, "[RMonit] UPDATE $targetHost/$service count=0 Failed.\n");
          } // end-if ($status==0)
        } // end-if (diskOverLimit())
      } else {
        // bila no route to host
        syslog(LOG_ERR, "[RMonit] SSH $service: no route to host $targetHost.");
      } // end-if check shell_exec
    } else {
      // targetHost dan service belum ada di Log
      $q="INSERT INTO $rmTable(tgl, host, service, count) VALUES('$tgl', '$targetHost', '$service', 0)";
      mysql_query($q, $con1) or syslog(LOG_ERR,"[RMonit] INSERT $targetHost/$service Failed.\n");
    } // end-if ($rs and (mysql_num_rows($rs)>0))
  } // end-for
} // end-if (count($rm_disk_list)>1)

// cek cpu (local dan remote)
// service: cpu
$service = "cpu";
if (count($rm_cpu_list)>1) {
  // bila ada daftar yang akan dicek cpu-nya
  $tgl=date("Y-m-d H:i:s");
  $jumHost = floor(count($rm_cpu_list)/3);
  for($i=0;$i<$jumHost;$i++) {
    $targetHost=$rm_cpu_list[3*$i];
    $namaHost  =$rm_cpu_list[3*$i+1];
    $limitHost =$rm_cpu_list[3*$i+2];
    // cek di DB Log
    $q="SELECT * FROM $rmTable WHERE host='$targetHost' AND service='$service' ";
    $rs=mysql_query($q, $con1);
    if ($rs and (mysql_num_rows($rs)>0)) {
      // bila query berhasil dan ada datanya
      $row=mysql_fetch_array($rs);
      $status=$row['status'];
      $count=$row['count'];
      $tglDown=$row['tgl'];
      // cek dulu apakah konek
      if (shell_exec("ssh root@$targetHost \"ls /\" ")) {
        // cek limit
        if (cpuOverLimit($targetHost, $limitHost)) {
          // kalau cpu sudah over limit, cek sudah berapa kali
          if ($count>=$rm_cpu_cycle) {
            // bila sdh mencapai batas cycle, cek status
            $updateTgl = "";
            if ($status==1) {
              // bila status masih 1, kirim SMS dan update tgl pada Log
              $pesanSMS = "CPU OVER LIMIT (lebih dari $limitHost). Silakan periksa.";
              kirimSMS($targetHost, $namaHost, $service, $pesanSMS);
              $updateTgl = "tgl=Now(),";
            }
            // bila status tdk 1, tgl tdk diupdate
            $q="UPDATE $rmTable SET $updateTgl status=0, count=0 WHERE host='$targetHost' AND service='$service' ";
            mysql_query($q, $con1) or syslog(LOG_ERR,"[RMonit] UPDATE $targetHost/$service OVER Failed.\n");
          } else {
            // bila belum mencapai batas cycle, update count naik
            $count++;
            $q="UPDATE $rmTable SET count=$count WHERE host='$targetHost' AND service='$service'";
            mysql_query($q, $con1) or syslog(LOG_ERR,"[RMonit] UPDATE $targetHost/$service COUNT Failed.\n");
          } // end-if ($count>=$rm_cpu_cycle)
        } else {
          // bila tidak over limit
          if ($status==0) {
            // bila status terakhir 0, hitung selisih DOWN time
            $sec = strtotime(date("Y-m-d H:i:s"))-strtotime($tglDown);
            $sec += 60*$rm_cpu_cycle;
            $jam = floor($sec/3600);
            $mnt = floor(($sec-3600*$jam)/60);
            $dtk = $sec-3600*$jam-60*$mnt;
            $jam = ($jam<10) ? "0".$jam : $jam;
            $mnt = ($mnt<10) ? "0".$mnt : $mnt;
            $dtk = ($dtk<10) ? "0".$dtk : $dtk;
            $wkt = "$jam:$mnt:$dtk";
            $pesanSMS="Cpu sudah di bawah limit $limitHost (over selama $wkt).";
            kirimSMS($targetHost, $namaHost, $service, $pesanSMS);
            $q="UPDATE $rmTable SET status=1, count=0 WHERE host='$targetHost' AND service='$service' ";
            mysql_query($q, $con1) or syslog(LOG_ERR, "[RMonit] UPDATE $targetHost/$service UNDER Failed.\n");
          } else {
            // kalau tdk over limit dan status=1, count harus dibuat 0
            $q="UPDATE $rmTable SET count=0 WHERE host='$targetHost' AND service='$service' ";
            mysql_query($q, $con1) or syslog(LOG_ERR, "[RMonit] UPDATE $targetHost/$service count=0 Failed.\n");
          } // end-if ($status==0)
        } // end-if (diskOverLimit())
      } else {
        // bila no route to host
        syslog(LOG_ERR, "[RMonit] SSH $service: no route to host $targetHost.");
      } // end-if check shell_exec
    } else {
      // targetHost dan service belum ada di Log
      $q="INSERT INTO $rmTable(tgl, host, service, count) VALUES('$tgl', '$targetHost', '$service', 0)";
      mysql_query($q, $con1) or syslog(LOG_ERR,"[RMonit] INSERT $targetHost/$service Failed.\n");
    } // end-if ($rs and (mysql_num_rows($rs)>0))
  } // end-for
} // end-if (count($rm_cpu_list)>1)

// cek ram (local dan remote)
// service: ram
$service = "ram";
if (count($rm_ram_list)>1) {
  // bila ada daftar yang akan dicek ram-nya
  $tgl=date("Y-m-d H:i:s");
  $jumHost = floor(count($rm_ram_list)/3);
  for($i=0;$i<$jumHost;$i++) {
    $targetHost=$rm_ram_list[3*$i];
    $namaHost  =$rm_ram_list[3*$i+1];
    $limitHost =$rm_ram_list[3*$i+2];
    // cek di DB Log
    $q="SELECT * FROM $rmTable WHERE host='$targetHost' AND service='$service' ";
    $rs=mysql_query($q, $con1);
    if ($rs and (mysql_num_rows($rs)>0)) {
      // bila query berhasil dan ada datanya
      $row=mysql_fetch_array($rs);
      $status=$row['status'];
      $count=$row['count'];
      $tglDown=$row['tgl'];
      // cek dulu apakah konek
      if (shell_exec("ssh root@$targetHost \"ls /\" ")) {
        // cek limit
        if (ramOverLimit($targetHost, $limitHost)) {
          // kalau ram sudah over limit, cek sudah berapa kali
          if ($count>=$rm_ram_cycle) {
            // bila sdh mencapai batas cycle, cek status
            $updateTgl = "";
            if ($status==1) {
              // bila status masih 1, kirim SMS dan update tgl pada Log
              $pesanSMS = "RAM OVER LIMIT (lebih dari $limitHost). Silakan periksa.";
              kirimSMS($targetHost, $namaHost, $service, $pesanSMS);
              $updateTgl = "tgl=Now(),";
            }
            // bila status tdk 1, tgl tdk diupdate
            $q="UPDATE $rmTable SET $updateTgl status=0, count=0 WHERE host='$targetHost' AND service='$service' ";
            mysql_query($q, $con1) or syslog(LOG_ERR,"[RMonit] UPDATE $targetHost/$service OVER Failed.\n");
          } else {
            // bila belum mencapai batas cycle, update count naik
            $count++;
            $q="UPDATE $rmTable SET count=$count WHERE host='$targetHost' AND service='$service'";
            mysql_query($q, $con1) or syslog(LOG_ERR,"[RMonit] UPDATE $targetHost/$service COUNT Failed.\n");
          } // end-if ($count>=$rm_cpu_cycle)
        } else {
          // bila tidak over limit
          if ($status==0) {
            // bila status terakhir 0, hitung selisih DOWN time
            $sec = strtotime(date("Y-m-d H:i:s"))-strtotime($tglDown);
            $sec += 60*$rm_cpu_cycle;
            $jam = floor($sec/3600);
            $mnt = floor(($sec-3600*$jam)/60);
            $dtk = $sec-3600*$jam-60*$mnt;
            $jam = ($jam<10) ? "0".$jam : $jam;
            $mnt = ($mnt<10) ? "0".$mnt : $mnt;
            $dtk = ($dtk<10) ? "0".$dtk : $dtk;
            $wkt = "$jam:$mnt:$dtk";
            $pesanSMS="RAM sudah di bawah limit $limitHost (over selama $wkt).";
            kirimSMS($targetHost, $namaHost, $service, $pesanSMS);
            $q="UPDATE $rmTable SET status=1, count=0 WHERE host='$targetHost' AND service='$service' ";
            mysql_query($q, $con1) or syslog(LOG_ERR, "[RMonit] UPDATE $targetHost/$service UNDER Failed.\n");
          } else {
            // kalau tdk over limit dan status=1, count harus dibuat 0
            $q="UPDATE $rmTable SET count=0 WHERE host='$targetHost' AND service='$service' ";
            mysql_query($q, $con1) or syslog(LOG_ERR, "[RMonit] UPDATE $targetHost/$service count=0 Failed.\n");
          } // end-if ($status==0)
        } // end-if (diskOverLimit())
      } else {
        // bila no route to host
        syslog(LOG_ERR, "[RMonit] SSH $service: no route to host $targetHost.");
      } // end-if check shell_exec
    } else {
      // targetHost dan service belum ada di Log
      $q="INSERT INTO $rmTable(tgl, host, service, count) VALUES('$tgl', '$targetHost', '$service', 0)";
      mysql_query($q, $con1) or syslog(LOG_ERR,"[RMonit] INSERT $targetHost/$service Failed.\n");
    } // end-if ($rs and (mysql_num_rows($rs)>0))
  } // end-for
} // end-if (count($rm_ram_list)>1)

/* tutup dulu

// cek replikasi
// service: replikasi
$service = "replikasi";
$tgl=date("Y-m-d H:i:s");
if ($rmon_galera=="yes") {
    $targetHost=gethostbyname(gethostname());  // localhost IP
    $q="SELECT * FROM $rmTable WHERE host='$targetHost' AND service='$service' ";
    $rs=mysql_query($q, $con1);
    if ($rs and (mysql_num_rows($rs)>0)) {
      $row=mysql_fetch_array($rs);
      $status=$row['status'];
      $count=$row['count'];
      if (replikasiFailed($galHost, $galUser, $galPswd)) {
        if ($count>=$rmon_galera_cycle) {
 echo "count > $rmon_galera_cycle, status = $status \n";
          if ($status==1) kirimSMS($rmon_dc_id, $userkey, $passkey, $telepon, $targetHost, $service, "$service PUTUS pada Galera");
          $q="UPDATE $rmTable SET status=0, count=0 WHERE host='$targetHost' AND service='$service' ";
          mysql_query($q, $con1) or die("UPDATE $targetHost/$service PUTUS Failed.\n");
        } else {
          $count++;
          $q="UPDATE $rmTable SET count=$count WHERE host='$targetHost' AND service='$service' ";
          mysql_query($q, $con1) or die("UPDATE $targetHost/$service COUNT Failed.\n");
        }
      } else {
        if ($status==0) {
          kirimSMS($rmon_dc_id, $userkey, $passkey, $telepon, $targetHost, $service, "$service Galera sudah AKTIF kembali");
          $q="UPDATE $rmTable SET status=1, count=0 WHERE host='$targetHost' AND service='$service' ";
          mysql_query($q, $con1) or die("UPDATE $targetHost/$service AKTIF Failed.\n");
        }
      }
    } else {
      $q="INSERT INTO $rmTable(tgl, host, service, count) VALUES('$tgl', '$targetHost', '$service', 0)";
      mysql_query($q, $con1) or die("INSERT $targetHost/$service Failed.\n");
    }
} // if  limit>0
// Tutup dulu */

syslog(LOG_INFO, "[RMonit] Pengecekan SELESAI pada $tgl.\n");

?>

Baca dulu file BACADULU.TXT.

Terima kasih. Silakan komen bila dirasa bermanfaat.

Tidak ada komentar:

Posting Komentar