Cacti 0.8.8b 成功監控mssql 2005

類別:原創 服務器

本文參考


第一:說明

目的:本機前提是已安裝好了cacti 0.8.8b 並正常工作,本文檔主要配置cacti插件並啓用郵件短信告警

其它說明: cacti 0.8.8b的安裝請參考我的其它博客文章《Cacti 0.8.8b 安裝配置(含snmp配置) http://jedy82.blog.51cto.com/425872/1569689

本文在此基礎上配置

Cacti服務器ip:192.168.10.112,mssql服務器ip:192.168.1.4

cacti 使用yum方式安裝,默認路徑爲/usr/share/cacti


第二:本例操作環境     

[root@i-tcz0hdhc ~]# yum update -y

[root@i-tcz0hdhc ~]# uname -a

Linux i-tcz0hdhc 2.6.32-431.29.2.el6.x86_64 #1 SMP Tue Sep 9 21:36:05 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux

[root@i-tcz0hdhc ~]# more /etc/redhat-release 

CentOS release 6.6 (Final)

[root@i-tcz0hdhc ~]# 


第三:必須組件的安裝

1、 說明

由於windows sql server 2005 本身不支持snmp。所以要想使用cacti 監控mssql,我們只能通過php連接mssql 2005,獲取sql 2005的性能計數器的值。

php連接mssql最常用的方法是使用freetds工具。cacti 服務器上必須安裝php-mssql 驅動。

 

2、 安裝freetds和php-mssql

[root@i-tcz0hdhc ~]# yum install freetds  php-mssql -y

Loaded plugins: fastestmirror

Setting up Install Process

Loading mirror speeds from cached hostfile

 * base: mirrors.yun-idc.com

 * epel: mirrors.yun-idc.com

 * extras: mirrors.yun-idc.com

 * rpmfusion-free-updates: mirror.bjtu.edu.cn

 * rpmfusion-nonfree-updates: mirror.bjtu.edu.cn

 * updates: mirrors.yun-idc.com

Package freetds-0.91-2.el6.x86_64 already installed and latest version

Package php-mssql-5.3.3-3.el6.x86_64 already installed and latest version

Nothing to do

[root@i-tcz0hdhc ~]# 

freetds安裝完成後 不需要配置,重啓httpd服務後能在phpinfo頁面看到php支持mssql了

wps893.tmp

3、 測試mssql的連接


注意防火牆的設置


[root@i-tcz0hdhc ~]# vi test_mssql_connect.php


[root@i-tcz0hdhc ~]# more test_mssql_connect.php   

<?php 

if(mssql_connect('192.168.1.4','sa','test')){ 

echo   "success\n"; 


else   { 

echo   "fail"; 


?>

[root@i-tcz0hdhc ~]# php -q test_mssql_connect.php 

success

[root@i-tcz0hdhc ~]# 

[root@i-tcz0hdhc ~]#

 

監控腳本配置

Cacti官方模板下載地址:http://docs.cacti.net/templates

Sql server 模板官方安裝文檔:http://docs.cacti.net/usertemplate:host:microsoft:sqlserver

將http://docs.cacti.net/_media/usertemplate:host:microsoft:cacti087e-mssql-host_template.tgz 下載到本地。解壓後得到4個文件夾。


 1、 sql server 上新增監控用戶 


將解壓後的sql scripts\sql_server_2005-2008.sql中的內容導入到sql server2005 中。其中的cactistats和CHANGEME分別是新增用戶的用戶名和密碼。可以自行修改。如果此處修改了,下面幾行也要做相應修改。之後的ss_win_mssql.php文件中的相應位置也要修改。


wps894.tmp

成功執行後在會在sql server 上增加一個名爲:cactistats密碼爲:CHANGEME的用戶。


wps8A4.tmp

 

2、 測試監控用戶連接 

新建測試文件

[root@i-tcz0hdhc ~]# vi test_dm_os_performance_counters.php 

[root@i-tcz0hdhc ~]# more test_dm_os_performance_counters.php 

<?php 

try { 

$hostname='192.168.1.4';       \\ 數據庫ip地址

$port=1433;                    \\ 數據庫端口(默認)

$dbname="master";              \\ 數據庫名(默認)

$username="cactistats";        \\ 數據庫用戶名(必須和前面導入的sql文件中的一致)

$pw="CHANGEME";                \\ 數據庫用戶密碼(必須和前面導入的sql文件中的一致)

$dbh= new PDO("dblib:host=$hostname:$port;dbname=$dbname","$username","$pw"); 

} catch (PDOException $e) { 

echo"Failed to get DB handle: ".$e->getMessage() ."n"; 

exit; 

echo 'connent MSSQL succeed'; 

 

#$stmt=$dbh->prepare("SELECT * FROM sys.dm_os_performance_counters"); 

$stmt=$dbh->prepare("SELECT COUNT (*) FROM sys.dm_os_performance_counters"); 

$stmt->execute(); 

while ($row=$stmt->fetch()) { 

print_r($row); 

unset($dbh); unset($stmt); 

?>

[root@i-tcz0hdhc ~]# php test_dm_os_performance_counters.php 

connent MSSQL succeedArray

(

    [computed] => 644

    [0] => 644

)

[root@i-tcz0hdhc ~]# 

 

3、 添加監控腳本 

將解壓後的scripts\ss_win_mssql.php上傳到cacti服務器的cacti目錄下的scripts/下,並賦予權限

[root@i-tcz0hdhc ~]# 

[root@i-tcz0hdhc ~]# cd /usr/share/cacti/scripts/

[root@i-tcz0hdhc scripts]# chmod 755 ss_win_mssql.php 

[root@i-tcz0hdhc scripts]# 

官方文檔中有如下的一段話:“I use MemCached to speed up the polling process so the code is setup to use it. If you choose not to, comment out (or delete) lines 24-29 and 72-73

You'll need to install the MemCached service as well as the PHP libraries which should be available through PECL”。大致意思就是說,ss_win_mssql.php中默認使用的是memcached來取mssql的數據,如果沒有安裝或是不使用memcached的話。需要將memcached有關的行註釋掉。否則無法取到mssql的數據。

我這裏沒有安裝memcached。所以這相關內容註釋。

 

[root@i-tcz0hdhc ~]# cd /usr/share/cacti/scripts/

[root@i-tcz0hdhc scripts]# vi ss_win_mssql.php 

[root@i-tcz0hdhc scripts]# more ss_win_mssql.php 

<?php

/* do NOT run this script through a web browser */

if (!isset($_SERVER["argv"][0]) || isset($_SERVER['REQUEST_METHOD'])  || isset($_SERVER['REMOTE_ADDR'])) {

   die("<br><strong>This script is only meant to run at the command line.</strong>");

}

 

/* display No errors */

error_reporting(0);

 

if (!isset($called_by_script_server)) {

        array_shift($_SERVER["argv"]);

 

        print call_user_func_array("ss_win_mssql", $_SERVER["argv"])."\n";

}

 

function ss_win_mssql ($hostname, $cmd, $username = NULL, $password = NULL) {

        list($host, $port) = explode(':', $hostname);

        $port = ($port == '' ? '1433' : $port);

        $username = ($username == NULL ? 'cactistats' : $username);

        $password = ($password == NULL ? 'CHANGEME' : $password);

 

        $ret = '';

 

//        $MCache_Host = 'localhost';                          \\ 註釋掉memcached相關內容

//        $MCache_Port = '11211';                              \\ 註釋掉memcached相關內容

//        $cachekey = 'ss_win_mssql:'.$host.'-'.$port;         \\ 註釋掉memcached相關內容

//        $MemCache = new Memcache;                            \\ 註釋掉memcached相關內容

//        $MemCache->connect($MCache_Host, $MCache_Port);      \\ 註釋掉memcached相關內容

//        if (! $vals = $MemCache->get($cachekey)){            \\ 註釋掉memcached相關內容

 

                if (! $link = mssql_connect($host.':'.$port, $username, $password) )

                        return;


                list($server_version) = mssql_fetch_row(mssql_query("SELECT SERVERPROPERTY('productversion')"));

 

                $perf_counter_table = (substr($server_version, 0, 1) == "8" ? 'sysperfinfo' : 'sys.dm_os_performance_counters');

 

                $sql = "SELECT [counter_name], [cntr_value] FROM ".$perf_counter_table." ".

                        "WHERE ([instance_name] = '' OR [instance_name] = '_Total') AND (".

                        "([object_name] LIKE ('%Plan Cache%') AND [counter_name] IN ".

                          "('Cache Hit Ratio', 'Cache Hit Ratio Base')) OR ".

                        "([object_name] LIKE ('%Buffer Manager%') AND [counter_name] IN ".

                          "('Buffer Cache Hit Ratio', 'Buffer Cache Hit Ratio Base', 'Page reads/sec', 'Page writes/sec')) OR ".

                        "([object_name] LIKE ('%General Statistics%') AND [counter_name] IN ".

                          "('Active Temp Tables', 'User Connections')) OR ".

                        "([object_name] LIKE ('%Databases%') AND [counter_name] IN ".

                          "('Transactions/sec', 'Log Cache Hit Ratio', 'Log Cache Hit Ratio Base', 'Log Flushes/sec', ".

                            "'Log Bytes Flushed/sec', 'Backup/Restore Throughput/sec')) OR ".

                        "([object_name] LIKE ('%Access Methods%') AND [counter_name] IN ".

                          "('Full Scans/sec', 'Range Scans/sec', 'Probe Scans/sec', 'Index Searches/sec', 'Page Splits/sec')) OR ".

                        "([object_name] LIKE ('%Memory Manager%') AND [counter_name] IN ".

                          "('Target Server Memory (KB)', 'Target Server Memory(KB)', 'Total Server Memory (KB)')) OR".

                        "([object_name] LIKE ('%SQL Statistics%') AND [counter_name] IN ".

                          "('SQL Compilations/sec', 'SQL Re-Compilations/sec'))".

                        ")";

 

                $res = mssql_query($sql, $link);

 

                $search = array(' ', '/sec', '(KB)', '/', '-');

 

                while ($row = mssql_fetch_row($res)){

                        $vals[strtolower(str_replace($search, '', $row[0]))] = (empty($row[1]) ? '0' : $row[1]);

                }

 

                $vals['buffercachehitratio'] = $vals['buffercachehitratio'] / $vals['buffercachehitratiobase'] * 100;

                $vals['logcachehitratio'] = $vals['logcachehitratio'] / $vals['logcachehitratiobase'] * 100;

                $vals['proccachehitratio'] = $vals['cachehitratio'] / $vals['cachehitratiobase'] * 100;

                $vals['memoryhitratio'] = $vals['totalservermemory'] / $vals['targetservermemory'] * 100;

 

                unset($vals['buffercachehitratiobase'], $vals['logcachehitratiobase'], $vals['cachehitratiobase'], $vals['cachehitratio']);

 

//                $MemCache->set($cachekey, $vals, FALSE, 15);       \\ 註釋掉memcached相關內容

//        }                                                          \\ 註釋掉memcached相關內容

 

        switch ($cmd){

        case "bckrsttroughput":

                $ret .= 'bckrsttroughput:'.$vals['backuprestorethroughput'].' ';

        break;

        case "buffercache":

                $ret .= 'buffercachehitratio:'.$vals['buffercachehitratio'].' ';

        break;

        case "compilations":

                $ret .= 'compliations:'.$vals['sqlcompilations'].' ';

                $ret .= 'recompliations:'.$vals['sqlrecompilations'].' ';

        break;

        case "connections":

                $ret .= 'userconnections:'.$vals['userconnections'].' ';

        break;

        case "logcache":

                $ret .= 'logcachehitratio:'.$vals['logcachehitratio'].' ';

        break;

        case "logflushes":

                $ret .= 'logflushes:'.$vals['logflushes'].' ';

        break;

        case "logflushtraffic":

                $ret .= 'bytesflushed:'.$vals['logbytesflushed'].' ';

        break;

        case "memory":

                $ret .= 'memoryhitratio:'.$vals['memoryhitratio'].' ';

                $ret .= 'totalservermemory:'.$vals['totalservermemory'].' ';

                $ret .= 'targetservermemory:'.$vals['targetservermemory'].' ';

        break;

        case "pageio":

                $ret .= 'pagereads:'.$vals['pagereads'].' ';

                $ret .= 'pagewrites:'.$vals['pagewrites'].' ';

        break;

        case "pagesplits":

                $ret .= 'pagesplits:'.$vals['pagesplits'].' ';

        break;

        case "proccache":

                $ret .= 'proccachehitratio:'.$vals['proccachehitratio'].' ';

        break;

        case "scans":

                $ret .= 'fullscans:'.$vals['fullscans'].' ';

                $ret .= 'rangescans:'.$vals['rangescans'].' ';

                $ret .= 'probescans:'.$vals['probescans'].' ';

                $ret .= 'indexsearches:'.$vals['indexsearches'].' ';

        break;

        case "temptables":

                $ret .= 'activetemptables:'.$vals['activetemptables'].' ';

        break;

        case "transactions":

                $ret .= 'transactions:'.$vals['transactions'].' ';

        break;

#       case "":

#               $ret .= ':'.$vals[''].' ';

#       break;

        }

 

        return trim($ret);

}

?>

[root@i-tcz0hdhc scripts]# 

 

4、 測試監控腳本 

[root@i-tcz0hdhc scripts]#

[root@i-tcz0hdhc scripts]# /usr/bin/php -q /usr/share/cacti/scripts/ss_win_mssql.php 192.168.1.4 scans cactistats CHANGEME

fullscans:4167 rangescans:611197 probescans:130196372 indexsearches:3420215

[root@i-tcz0hdhc scripts]# /usr/bin/php -q /usr/share/cacti/scripts/ss_win_mssql.php 192.168.1.4 connections 

userconnections:5

[root@i-tcz0hdhc scripts]#

 

 

cacti配置

1、 導入模板

將解壓後的template\cacti_host_template_windows_-_sql_server.xml導入到cacti中 

Console → Import/Export → Import Templates  → 選擇文件 → Import 

導入後的Host Templates名爲 Windows - SQL Server

導入後graph templates包含:

    Windows - SQL Server - Backup/Restore I/O

    Windows - SQL Server - Buffer Cache

    Windows - SQL Server - Connections

    Windows - SQL Server - Log Cache

    Windows - SQL Server - Log Flush I/O

    Windows - SQL Server - Log Flushes

    Windows - SQL Server - Memory

    Windows - SQL Server - Page I/O

    Windows - SQL Server - Page Splits

    Windows - SQL Server - Procedure Cache

    Windows - SQL Server - Processes Blocked

    Windows - SQL Server - SQL Compilations

    Windows - SQL Server - Table Scans

    Windows - SQL Server - Temp Tables

    Windows - SQL Server - Transactions

 

2、 新建一個Devices

“Console → Management → Devices → Add”中新建一個Devices。注意“Host Template” 中選擇“Windows - SQL Server” 點“Save”後在頁面上方點 Create Graphs for this Host。 

在“Graph Templates”中選擇要監控的項,點“Create”後出現“Create Graphs from Data Query ”中要求填寫sql server的端口號、用戶名、密碼。此處如果不填寫,將直接使用前面在ss_win_mssql.php中填寫的端口號、用戶名、密碼。

 

3、 將新建的Devices加入到Graph Trees中(過程略)5分鐘後,我們能在graphs中看到mssql的監控圖。

wps8B5.tmp

這裏要注意一下,雖然mssql 2005 不支持snmp,監控也是使用的php腳本,但是rrdtool畫圖是必須是要snmp的哦,所以在被監控的mssql 2005上的snmp必須要允許cacti服務器,否則就會有數據不出圖哦


 

至此 cacti成功監控mssql 2005



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章