Zabbix安裝和使用配置小結

前言

Zabbix是目前最為主流的開源監(jiān)控方案之一贞岭,部署本身并不困難,難的是深入理解唉工。根據在生產環(huán)境的實踐從新版Zabbix 4.0 LTS開始全部使用Docker部署,我相信未來越來越多的開源組件都會以容器化的形式呈現在我們面前犬庇。

學習使用Zabbix

更新歷史

2018年11月01日 - 更新官方LAMP部署過程
2018年10月16日 - 更新Docker部署Zabbix 4.0
2018年08月06日 - 初稿

閱讀原文 - https://wsgzao.github.io/post/zabbix/

擴展閱讀

Zabbix - https://www.zabbix.com/


官方文檔

https://www.zabbix.com/download
https://www.zabbix.com/documentation

zabbix-server

基于官方的LAMP架構纽帖,按照最簡單的原生方式來部署雕崩,不做任何多余優(yōu)化

# 安裝必要依賴包
yum install -y httpd mariadb-server mariadb php php-mysql php-gd libjpeg* php-ldap php-odbc php-pear php-xml php-xmlrpc php-mhash

# 修改apache配置
vi /etc/httpd/conf/httpd.conf
ServerName 192.168.56.103
DirectoryIndex index.html index.php

# 修改php時區(qū)
vi /etc/php.ini
date.timezone = Asia/Singapore

# 啟動 httpd 服務
systemctl start httpd.service
# 啟動 mariadb 服務
systemctl start mariadb.service

# 初始化 mysql 數據庫,并配置 root 用戶密碼
mysql_secure_installation

# 萬一新版本忘記隨機密碼可以通過日志獲取
grep 'temporary password' /var/log/mysqld.log

# 創(chuàng)建一個測試頁,測試 LAMP 是否搭建成功
cat > /var/www/html/index.php << EOF
<?php
phpinfo();
?>
EOF

# 創(chuàng)建zabbix數據庫
mysql -uroot -p

mysql> create database zabbix character set utf8 collate utf8_bin;
mysql> grant all privileges on zabbix.* to zabbix@localhost identified by 'zabbix';
mysql> quit;

# 部署zabbix
rpm -i https://repo.zabbix.com/zabbix/3.4/rhel/7/x86_64/zabbix-release-3.4-2.el7.noarch.rpm
yum install -y zabbix-server-mysql zabbix-web-mysql zabbix-agent
zcat /usr/share/doc/zabbix-server-mysql*/create.sql.gz | mysql -uzabbix -p zabbix

# 配置數據庫用戶及密碼
vim /etc/zabbix/zabbix_server.conf
DBPassword=zabbix

# 修改時區(qū)
vim /etc/httpd/conf.d/zabbix.conf
php_value date.timezone Asia/Singapore

# 啟動zabbix并設置自啟動服務
systemctl restart zabbix-server zabbix-agent httpd
systemctl enable zabbix-server zabbix-agent httpd mariadb

以下是基于LNMP手動編譯安裝Zabbix的過程沐祷,僅供參考


# hostname
hostnamectl set-hostname <host-name>

# firewall
systemctl stop firewalld
systemctl disable firewalld

# selinux
getenforce
setenforce 0
sed -i "s/SELINUX=enforcing/SELINUX=disabled/g" /etc/selinux/config

# epel
yum install epel-release

# nginx
yum install nginx
systemctl enable nginx
systemctl start nginx
systemctl status nginx
nginx -s reload

# mysql | mariadb
yum -y install mariadb mariadb-server
systemctl enable mariadb.service
systemctl start mariadb.service
mysql_secure_installation

# php
wget http://cn2.php.net/distributions/php-7.2.8.tar.gz
tar xf php-7.2.8.tar.gz 
cd ./php-7.2.8/
yum install -y libxml2 libxml2-devel openssl openssl-devel bzip2 bzip2-devel libcurl libcurl-devel libjpeg libjpeg-devel libpng libpng-devel freetype freetype-devel gmp gmp-devel libmcrypt libmcrypt-devel readline readline-devel libxslt libxslt-devel 
yum install -y libmcrypt libmcrypt-devel gcc
./configure --prefix=/usr/local/php --with-config-file-path=/etc --enable-fpm --with-fpm-user=nginx  --with-fpm-group=nginx --enable-inline-optimization --disable-debug --disable-rpath --enable-shared  --enable-soap --with-libxml-dir --with-xmlrpc --with-openssl --with-mcrypt --with-mhash --with-pcre-regex --with-sqlite3 --with-zlib --enable-bcmath  --with-iconv --with-bz2 --enable-calendar --with-curl --with-cdb --enable-dom --enable-exif --enable-fileinfo --enable-filter --with-pcre-dir --enable-ftp --with-gd --with-openssl-dir  --with-jpeg-dir --with-png-dir --with-zlib-dir --with-freetype-dir --enable-gd-native-ttf --enable-gd-jis-conv --with-gettext --with-gmp --with-mhash --enable-json --enable-mbstring --enable-mbregex --enable-mbregex-backtrack --with-libmbfl --with-onig --enable-pdo --with-mysqli=mysqlnd --with-pdo-mysql=mysqlnd --with-zlib-dir --with-pdo-sqlite --with-readline --enable-session --enable-shmop --enable-simplexml --enable-sockets  --enable-sysvmsg --enable-sysvsem --enable-sysvshm --enable-wddx --with-libxml-dir --with-xsl --enable-zip --enable-mysqlnd-compression-support --with-pear --enable-opcache
make && make install

vi /etc/profile

PATH=$PATH:/usr/local/php/bin
export PATH

source /etc/profile
echo $PATH
php -v

# php-fpm 
cp ./php.ini-production /etc/php.ini
cp /usr/local/php/etc/php-fpm.conf.default /usr/local/php/etc/php-fpm.conf
cp /usr/local/php/etc/php-fpm.d/www.conf.default /usr/local/php/etc/php-fpm.d/www.conf
cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm
chmod +x /etc/init.d/php-fpm

vi /etc/php.ini

max_execution_time = 300
max_input_time = 300
memory_limit = 128M
post_max_size = 16M
date.timezone = Asia/Singapore

/etc/init.d/php-fpm start

# nginx
vi /etc/nginx/conf.d/default.conf

server{
    listen 80;
    server_name localhost;
    root /data/www;
    location / {
        index  index.php index.html index.htm;
        if (!-e $request_filename)
        {
            rewrite ^/(.*)$ /index.php/$1;
            #rewrite ^/subdir/(.*)$ /subdir/index.php/$1;
        }
    }
    #proxy the php scripts to php-fpm
    location ~ \.php {
        include fastcgi_params;
        set $path_info "";
        set $real_script_name $fastcgi_script_name;
        if ($fastcgi_script_name ~ "^(.+?\.php)(/.+)$") {
            set $real_script_name $1;
            set $path_info $2;
        }
        fastcgi_param SCRIPT_FILENAME $document_root$real_script_name;
        fastcgi_param SCRIPT_NAME $real_script_name;
        fastcgi_param PATH_INFO $path_info;
        fastcgi_intercept_errors on;
        fastcgi_pass   127.0.0.1:9000;
    }
}

nginx -s reload

vi /data/www/info.php

<?php
    phpinfo();
?>

http://127.0.0.1/info.php 

# zabbix-server
rpm -ivh http://repo.zabbix.com/zabbix/3.4/rhel/7/x86_64/zabbix-release-3.4-2.el7.noarch.rpm
yum -y install zabbix-server-mysql zabbix-agent

# create zabbix in db
mysql -u root -p
create database zabbix character set utf8 collate utf8_bin;
grant all privileges on zabbix.* to 'zabbix'@'%' identified by 'zabbix';
flush privileges;


cd /usr/share/doc/zabbix-server-mysql-3.4.11/
zcat create.sql.gz | mysql -u root -p zabbix

vi /etc/zabbix/zabbix_server.conf

DBHost=localhost
DBName=zabbix
DBUser=zabbix
DBPassword=zabbix

chown -R zabbix:zabbix /etc/zabbix
chown -R zabbix:zabbix /usr/lib/zabbix
systemctl enable zabbix-server
systemctl start zabbix-server

# zabbix-web
wget -O zabbix-3.4.11.tar.gz https://excellmedia.dl.sourceforge.net/project/zabbix/ZABBIX%20Latest%20Stable/3.4.11/zabbix-3.4.11.tar.gz
tar zxvf zabbix-3.4.11.tar.gz
cp -rf ./zabbix-3.4.11/frontends/php/ /data/www/zabbix
mv /data/www/zabbix/conf/zabbix.conf.php.example /data/www/zabbix/conf/zabbix.conf.php 
vi /data/www/zabbix/conf/zabbix.conf.php

<?php
// Zabbix GUI configuration file.
global $DB, $HISTORY;

$DB['TYPE']                             = 'MYSQL';
$DB['SERVER']                   = '127.0.0.1';
$DB['PORT']                             = '0';
$DB['DATABASE']                 = 'zabbix';
$DB['USER']                             = 'zabbix';
$DB['PASSWORD']                 = 'zabbix';
// Schema name. Used for IBM DB2 and PostgreSQL.
$DB['SCHEMA']                   = '';

$ZBX_SERVER                             = 'localhost';
$ZBX_SERVER_PORT                = '10051';
$ZBX_SERVER_NAME                = '';

$IMAGE_FORMAT_DEFAULT   = IMAGE_FORMAT_PNG;

// Elasticsearch url (can be string if same url is used for all types).
$HISTORY['url']   = [
                'uint' => 'http://127.0.0.1:9200',
                'text' => 'http://127.0.0.1:9200'
];
// Value types stored in Elasticsearch.
$HISTORY['types'] = ['uint', 'text'];


http://127.0.0.1/zabbix

## zabbix-agent
rpm -ivh http://repo.zabbix.com/zabbix/3.4/rhel/7/x86_64/zabbix-release-3.4-2.el7.noarch.rpm
yum -y install zabbix-agent
vi /etc/zabbix/zabbix_agentd.conf

Server=127.0.0.1
ServerActive=127.0.0.1
Hostname=Zabbix server

systemctl enable zabbix-agent
systemctl start zabbix-agent

Zabbix表分區(qū)優(yōu)化

https://www.zabbix.org/wiki/Docs/howto/mysql_partition
https://cloud.tencent.com/developer/article/1006301

Zabbix數據庫優(yōu)化
目的: 快速清理歷史數據髓绽,并減少數據存儲容量
方法: 歷史表使用分區(qū)表(刪除分區(qū)表速度快),使用Tokudb引擎(適合大量insert少量update和select等日志表)
Zabbix版本: 3.4
涉及表項:
存儲不同類型item的歷史數據株茶,最終1小時或者1天等段時間的繪圖數據從其中獲取
history启盛、history_log棍厂、history_str航攒、history_text、history_uint
存儲不同類型item的歷史趨勢數據断盛,每隔一小時從歷史數據中統計一次,并計算統計區(qū)間的平均值嘉裤,最大值郑临,最小值trends栖博、trends_uint

zabbix的db有做分表 根據這個來的
https://www.zabbix.org/wiki/Docs/howto/mysql_partition
cronjob里的腳本包括了建新表和刪除舊表,用mysql的procedure控制,刪除舊表可以釋放空間
想要修改短一點屑宠,需要修改procedure partition_maintenance_all里規(guī)定的時間
我的做法是Drop舊procedure再創(chuàng)建新的

存儲過程執(zhí)行后將可以使用命令對想要分區(qū)的表進行表分區(qū)了,其中的參數我這里解釋一下仇让。

CALL partition_maintenance('<zabbix_db_name>', '<table_name>', <days_to_keep_data>, <hourly_interval>, <num_future_intervals_to_create>)

這是舉例:

CALL partition_maintenance(zabbix, 'history_uint', 31, 24, 14);

zabbix_db_name:庫名
table_name:表名
days_to_keep_data:保存多少天的數據
hourly_interval:每隔多久生成一個分區(qū)
num_future_intervals_to_create:本次一共生成多少個分區(qū)

這個例子就是 history_uint 表最多保存 31 天的數據典奉,每隔 24 小時生成一個分區(qū),這次一共生成 14 個分區(qū)

這里可以將上面四個存儲過程保存為一個文件丧叽,導入到數據庫中卫玖,文件我稍后將會放在附件中,這里使用的命令是

mysql -uzabbix -pzabbix zabbix<partition_call.sql

然后可以將 CALL 統一調用也做成一個文件

關閉zabbix的housekeeper功能

  1. login mysql zabbix
  2. DROP PROCEDURE IF EXISTS partition_maintenance_all
  3. 根據需要修改括號內第三列的時間踊淳,估計得改成45或者30了假瞬。每列的定義請參照最上面給的鏈接
  4. 再手動跑下cronjob內的那個指令就好
[root@sg-gop-10-65-200-90 mysql]# grep -Ev '^$|#' /etc/zabbix/zabbix_server.conf
LogFile=/var/log/zabbix/zabbix_server.log
LogFileSize=0
PidFile=/var/run/zabbix/zabbix_server.pid
SocketDir=/var/run/zabbix
DBName=zabbix
DBUser=zabbix
DBPassword=zabbix
StartPollers=500
StartPingers=50
SNMPTrapperFile=/var/log/snmptrap/snmptrap.log
CacheSize=8G
TrendCacheSize=1G
Timeout=15
AlertScriptsPath=/usr/lib/zabbix/alertscripts
ExternalScripts=/usr/lib/zabbix/externalscripts
LogSlowQueries=3000

[root@sg-gop-10-65-200-90 percona-server.conf.d]# grep -Ev '^$|#' /etc/percona-server.conf.d/mysqld.cnf
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
symbolic-links=0
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
max_connections=1000
# login mysql
mysql -uroot -p
zabbix

mysql> use zabbix;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show variables like '%dir%';
+-----------------------------------------+-------------------------------------+
| Variable_name                           | Value                               |
+-----------------------------------------+-------------------------------------+
| basedir                                 | /usr/                               |
| binlog_direct_non_transactional_updates | OFF                                 |
| character_sets_dir                      | /usr/share/percona-server/charsets/ |
| datadir                                 | /var/lib/mysql/                     |
| ignore_db_dirs                          |                                     |
| innodb_data_home_dir                    |                                     |
| innodb_log_group_home_dir               | ./                                  |
| innodb_max_dirty_pages_pct              | 75.000000                           |
| innodb_max_dirty_pages_pct_lwm          | 0.000000                            |
| innodb_tmpdir                           |                                     |
| innodb_undo_directory                   | ./                                  |
| lc_messages_dir                         | /usr/share/percona-server/          |
| plugin_dir                              | /usr/lib64/mysql/plugin/            |
| slave_load_tmpdir                       | /tmp                                |
| tmpdir                                  | /tmp                                |
+-----------------------------------------+-------------------------------------+
15 rows in set (0.07 sec)

mysql>
SELECT table_name AS "Tables",
round(((data_length + index_length) / 1024 / 1024), 2) "Size in MB"
FROM information_schema.TABLES
WHERE table_schema = 'zabbix'
ORDER BY (data_length + index_length) DESC;

+----------------------------+------------+
| Tables                     | Size in MB |
+----------------------------+------------+
| history                    |  545043.75 |
| history_uint               |   44729.66 |
| trends                     |   13500.41 |
| trends_uint                |    1666.66 |
| history_text               |     650.31 |


# Zabbix > 3.2, history 30, Trends 300

#cat partition.sql
DELIMITER $$
CREATE PROCEDURE `partition_create`(SCHEMANAMEvarchar(64), TABLENAME varchar(64), PARTITIONNAME varchar(64), CLOCK int)
BEGIN
       /*
          SCHEMANAME = The DB schema in which to make changes
          TABLENAME = The table with partitions to potentially delete
          PARTITIONNAME = The name of the partition to create
       */
       /*
          Verify that the partition does not already exist
       */

       DECLARE RETROWS INT;
       SELECT COUNT(1) INTO RETROWS
       FROM information_schema.partitions
       WHERE table_schema = SCHEMANAME AND table_name = TABLENAME ANDpartition_description >= CLOCK;

       IF RETROWS = 0 THEN
               /*
                   1. Print a messageindicating that a partition was created.
                   2. Create the SQL to createthe partition.
                   3. Execute the SQL from #2.
               */
               SELECT CONCAT( "partition_create(", SCHEMANAME, ",",TABLENAME, ",", PARTITIONNAME, ",", CLOCK, ")" )AS msg;
               SET @sql = CONCAT( 'ALTER TABLE ', SCHEMANAME, '.', TABLENAME, ' ADDPARTITION (PARTITION ', PARTITIONNAME, ' VALUES LESS THAN (', CLOCK, '));' );
               PREPARE STMT FROM @sql;
               EXECUTE STMT;
               DEALLOCATE PREPARE STMT;
       END IF;
END$$
DELIMITER ;

DELIMITER $$
CREATE PROCEDURE `partition_drop`(SCHEMANAMEVARCHAR(64), TABLENAME VARCHAR(64), DELETE_BELOW_PARTITION_DATE BIGINT)
BEGIN
       /*
           SCHEMANAME = The DB schema in which tomake changes
          TABLENAME = The table with partitions to potentially delete
          DELETE_BELOW_PARTITION_DATE = Delete any partitions with names that aredates older than this one (yyyy-mm-dd)
        */
       DECLARE done INT DEFAULT FALSE;
       DECLARE drop_part_name VARCHAR(16);

       /*
          Get a list of all the partitions that are older than the date
          in DELETE_BELOW_PARTITION_DATE. All partitions are prefixed with
           a "p", so use SUBSTRING TOget rid of that character.
       */
       DECLARE myCursor CURSOR FOR
               SELECT partition_name
               FROM information_schema.partitions
               WHERE table_schema = SCHEMANAME AND table_name = TABLENAME ANDCAST(SUBSTRING(partition_name FROM 2) AS UNSIGNED) <DELETE_BELOW_PARTITION_DATE;
       DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

       /*
          Create the basics for when we need to drop the partition.  Also, create
          @drop_partitions to hold a comma-delimited list of all partitions that
          should be deleted.
       */
       SET @alter_header = CONCAT("ALTER TABLE ", SCHEMANAME,".", TABLENAME, " DROP PARTITION ");
       SET @drop_partitions = "";

       /*
          Start looping through all the partitions that are too old.
       */
       OPEN myCursor;
       read_loop: LOOP
               FETCH myCursor INTO drop_part_name;
               IF done THEN
                        LEAVE read_loop;
               END IF;
               SET @drop_partitions = IF(@drop_partitions = "",drop_part_name, CONCAT(@drop_partitions, ",", drop_part_name));
       END LOOP;
       IF @drop_partitions != "" THEN
                /*
                   1. Build the SQL to drop allthe necessary partitions.
                   2. Run the SQL to drop thepartitions.
                   3. Print out the tablepartitions that were deleted.
               */
               SET @full_sql = CONCAT(@alter_header, @drop_partitions, ";");
               PREPARE STMT FROM @full_sql;
               EXECUTE STMT;
               DEALLOCATE PREPARE STMT;

               SELECT CONCAT(SCHEMANAME, ".", TABLENAME) AS `table`,@drop_partitions AS `partitions_deleted`;
       ELSE
               /*
                   No partitions are beingdeleted, so print out "N/A" (Not applicable) to indicate
                   that no changes were made.
               */
               SELECT CONCAT(SCHEMANAME, ".", TABLENAME) AS `table`,"N/A" AS `partitions_deleted`;
       END IF;
END$$
DELIMITER ;


DELIMITER $$
CREATE PROCEDURE`partition_maintenance`(SCHEMA_NAME VARCHAR(32), TABLE_NAME VARCHAR(32),KEEP_DATA_DAYS INT, HOURLY_INTERVAL INT, CREATE_NEXT_INTERVALS INT)
BEGIN
       DECLARE OLDER_THAN_PARTITION_DATE VARCHAR(16);
       DECLARE PARTITION_NAME VARCHAR(16);
       DECLARE OLD_PARTITION_NAME VARCHAR(16);
       DECLARE LESS_THAN_TIMESTAMP INT;
       DECLARE CUR_TIME INT;

        CALL partition_verify(SCHEMA_NAME,TABLE_NAME, HOURLY_INTERVAL);
       SET CUR_TIME = UNIX_TIMESTAMP(DATE_FORMAT(NOW(), '%Y-%m-%d 00:00:00'));

       SET @__interval = 1;
       create_loop: LOOP
               IF @__interval > CREATE_NEXT_INTERVALS THEN
                        LEAVE create_loop;
               END IF;

               SET LESS_THAN_TIMESTAMP = CUR_TIME + (HOURLY_INTERVAL * @__interval *3600);
               SET PARTITION_NAME = FROM_UNIXTIME(CUR_TIME + HOURLY_INTERVAL *(@__interval - 1) * 3600, 'p%Y%m%d%H00');
               IF(PARTITION_NAME != OLD_PARTITION_NAME) THEN
                        CALLpartition_create(SCHEMA_NAME, TABLE_NAME, PARTITION_NAME, LESS_THAN_TIMESTAMP);
               END IF;
               SET @__interval=@__interval+1;
               SET OLD_PARTITION_NAME = PARTITION_NAME;
       END LOOP;

       SET OLDER_THAN_PARTITION_DATE=DATE_FORMAT(DATE_SUB(NOW(), INTERVALKEEP_DATA_DAYS DAY), '%Y%m%d0000');
       CALL partition_drop(SCHEMA_NAME, TABLE_NAME, OLDER_THAN_PARTITION_DATE);

END$$
DELIMITER ;

DELIMITER $$
CREATE PROCEDURE `partition_verify`(SCHEMANAMEVARCHAR(64), TABLENAME VARCHAR(64), HOURLYINTERVAL INT(11))
BEGIN
       DECLARE PARTITION_NAME VARCHAR(16);
       DECLARE RETROWS INT(11);
       DECLARE FUTURE_TIMESTAMP TIMESTAMP;

       /*
        * Check if any partitions exist for the given SCHEMANAME.TABLENAME.
        */
       SELECT COUNT(1) INTO RETROWS
       FROM information_schema.partitions
       WHERE table_schema = SCHEMANAME AND table_name = TABLENAME ANDpartition_name IS NULL;

       /*
        * If partitions do not exist, go ahead and partition the table
        */
        IFRETROWS = 1 THEN
               /*
                * Take the current date at 00:00:00 and add HOURLYINTERVAL to it.  This is the timestamp below which we willstore values.
                * We begin partitioning based on the beginning of a day.  This is because we don't want to generate arandom partition
                * that won't necessarily fall in line with the desired partition naming(ie: if the hour interval is 24 hours, we could
                * end up creating a partition now named "p201403270600" whenall other partitions will be like "p201403280000").
                */
               SET FUTURE_TIMESTAMP = TIMESTAMPADD(HOUR, HOURLYINTERVAL,CONCAT(CURDATE(), " ", '00:00:00'));
               SET PARTITION_NAME = DATE_FORMAT(CURDATE(), 'p%Y%m%d%H00');

               -- Create the partitioning query
               SET @__PARTITION_SQL = CONCAT("ALTER TABLE ", SCHEMANAME,".", TABLENAME, " PARTITION BY RANGE(`clock`)");
               SET @__PARTITION_SQL = CONCAT(@__PARTITION_SQL, "(PARTITION ",PARTITION_NAME, " VALUES LESS THAN (",UNIX_TIMESTAMP(FUTURE_TIMESTAMP), "));");

               -- Run the partitioning query
               PREPARE STMT FROM @__PARTITION_SQL;
               EXECUTE STMT;
               DEALLOCATE PREPARE STMT;
       END IF;
END$$
DELIMITER ;

DELIMITER $$
CREATE PROCEDURE`partition_maintenance_all`(SCHEMA_NAME VARCHAR(32))
BEGIN
               CALL partition_maintenance(SCHEMA_NAME, 'history', 30, 24, 14);
               CALL partition_maintenance(SCHEMA_NAME, 'history_log', 30, 24, 14);
               CALL partition_maintenance(SCHEMA_NAME, 'history_str', 30, 24, 14);
               CALL partition_maintenance(SCHEMA_NAME, 'history_text', 30, 24, 14);
                CALLpartition_maintenance(SCHEMA_NAME, 'history_uint', 30, 24, 14);
               CALL partition_maintenance(SCHEMA_NAME, 'trends', 120, 24, 14);
               CALL partition_maintenance(SCHEMA_NAME, 'trends_uint', 120, 24, 14);
END$$
DELIMITER ;

# import partition.sql
mysql -u'zabbix' -p'zabbix' zabbix  < partition.sql
# run
nohup mysql -u'zabbix' -p'zabbix' 'zabbix' -e "CALL partition_maintenance_all('zabbix')" &> /root/partition.log&
tail -f /root/partition.log

# 查看過程邏輯
show create procedure partition_maintenance_all \G;
# 刪除存儲過程
drop procedure if exists partition_maintenance_all; 
# 查看存儲過程
show procedure status like 'partition_maintenance%' \G;
# 查看
show create table history

# crontab
[root@sg-gop-10-65-200-90 wangao]# cat /etc/crontab
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root

# For details see man 4 crontabs

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name  command to be executed

15 3 * * * root bash /opt/sa_scripts/zabbix_partitioning.sh
[root@sg-gop-10-65-200-90 wangao]# cat /opt/sa_scripts/zabbix_partitioning.sh
#!/bin/bash

user='zabbix'
password='zabbix'
database='zabbix'

mysql -u${user} -p$password $database -e "CALL partition_maintenance_all('zabbix');"

docker

https://www.zabbix.com/documentation/3.4/zh/manual/installation/containers

# install docker-ce
sudo yum install -y yum-utils device-mapper-persistent-data lvm2
sudo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
sudo yum install -y docker-ce
sudo systemctl start docker

# docker: Error response from daemon: Get https://registry-1.docker.io/v2/: x509: certificate has expired or is not yet valid.
ntpdate 0.pool.ntp.org

# Install mysql, zabbix, nginx in docker 
docker run --name mysql-server -t \
-e MYSQL_DATABASE="zabbix" \
-e MYSQL_USER="zabbix" \
-e MYSQL_PASSWORD="zabbix" \
-e MYSQL_ROOT_PASSWORD="zabbix" \
-p 127.0.0.1:3306:3306 \
-d mysql:5.7 \
--character-set-server=utf8 --collation-server=utf8_bin

docker run --name zabbix-server-mysql -t \
--link mysql-server:mysql \
-e DB_SERVER_HOST="mysql-server" \
-e MYSQL_DATABASE="zabbix" \
-e MYSQL_USER="zabbix" \
-e MYSQL_PASSWORD="zabbix" \
-e MYSQL_ROOT_PASSWORD="zabbix" \
-p 10051:10051 \
-d \
zabbix/zabbix-server-mysql:centos-4.0-latest

docker run --name zabbix-web-nginx-mysql -t \
--link mysql-server:mysql \
--link zabbix-server-mysql:zabbix-server \
-e DB_SERVER_HOST="mysql-server" \
-e MYSQL_DATABASE="zabbix" \
-e MYSQL_USER="zabbix" \
-e MYSQL_PASSWORD="zabbix" \
-e MYSQL_ROOT_PASSWORD="zabbix" \
-e PHP_TZ="Asia/Singapore" \
-p 80:80 \
-d \
zabbix/zabbix-web-nginx-mysql:centos-4.0-latest


[root@zabbix_server ~]# docker ps
CONTAINER ID        IMAGE                                  COMMAND                  CREATED              STATUS              PORTS                           NAMES
98cbe8d8a6bd        zabbix/zabbix-web-nginx-mysql:latest   "docker-entrypoint.sh"   6 seconds ago        Up 5 seconds        443/tcp, 0.0.0.0:8080->80/tcp   zabbix-web-nginx-mysql
de040d43d60f        zabbix/zabbix-server-mysql:latest      "docker-entrypoint.sh"   59 seconds ago       Up 59 seconds       0.0.0.0:10051->10051/tcp        zabbix-server-mysql
3276f18def8d        mysql:5.7                              "docker-entrypoint.s…"   About a minute ago   Up About a minute   3306/tcp                        mysql-server

[root@zabbix_server ~]# docker images
REPOSITORY                      TAG                 IMAGE ID            CREATED             SIZE
zabbix/zabbix-web-nginx-mysql   latest              4db891b4393a        10 hours ago        177MB
zabbix/zabbix-server-mysql      latest              f5e58dafe9ac        10 hours ago        62.2MB
mysql                           5.7                 f0f3956a9dd8        7 days ago          409MB

http://127.0.0.1:8080

Admin/zabbix



Zabbix自定義監(jiān)控

以監(jiān)控文件系統目錄的權限為例

Zabbix用戶自定義參數
https://www.zabbix.com/documentation/3.4/zh/manual/config/items/userparameters

# 新建自定義監(jiān)控配置文件userparameter
cd /etc/zabbix/zabbix_agentd.d
vi userparameter_tmp.conf
UserParameter=check.tmp[*],stat -c %a /tmp
# 重啟zabbix agent
service zabbix-agent restart

# 在Zabbix Server服務端驗證
zabbix_get -s 10.65.200.90 -k check.tmp
1777
zabbix_get -s 10.65.200.90 -k agent.version
3.0.9

# 在WebUI中創(chuàng)建新的Template或者使用已有新增Items
Items: Key為check.tmp
Triggers: 定義Serverity,Expression如下所示
{Template Sea Ops WangAo:check.tmp.last()}<>1777

# 點擊Monitoring Latest data查看Item最新數據
Moniroting -> Latest data -> Hosts -> check /tmp permission

如果需要配置Actions可以查看Zabbix使用企業(yè)微信告警配置小結
https://wsgzao.github.io/post/zabbix-alert-wechat/

Zabbix備份恢復

mysql數據庫備份通常使用mysqldump或者xtrabackup

因為一般歷史數據較大迂尝,如果需要保留所有數據可以考慮主從同步脱茉,如果不需要保留數據直接過濾歷史數據備份相關的告警配置即可

# 查看當前版本Zabbix的數據庫表結構
mysql -uzabbix -pzabbix zabbix -e "show tables"|egrep -v "(Tables_in_zabbix)"
mysql -uzabbix -pzabbix zabbix -e "show tables"|egrep -v "(Tables_in_zabbix|history*|trends*|acknowledges|alerts|auditlog|events|service_alarms)"

# 以下表中標記+號為需要過濾的表
+acknowledges
actions
+alerts
application_discovery
application_prototype
application_template
applications
+auditlog
+auditlog_details
autoreg_host
conditions
config
corr_condition
corr_condition_group
corr_condition_tag
corr_condition_tagpair
corr_condition_tagvalue
corr_operation
correlation
dashboard
dashboard_user
dashboard_usrgrp
dbversion
dchecks
dhosts
drules
dservices
escalations
event_recovery
event_tag
+events
expressions
functions
globalmacro
globalvars
graph_discovery
graph_theme
graphs
graphs_items
group_discovery
group_prototype
groups
+history
+history_log
+history_str
+history_text
+history_uint
host_discovery
host_inventory
hostmacro
hosts
hosts_groups
hosts_templates
housekeeper
httpstep
httpstep_field
httpstepitem
httptest
httptest_field
httptestitem
icon_map
icon_mapping
ids
images
interface
interface_discovery
item_application_prototype
item_condition
item_discovery
item_preproc
items
items_applications
maintenances
maintenances_groups
maintenances_hosts
maintenances_windows
mappings
media
media_type
opcommand
opcommand_grp
opcommand_hst
opconditions
operations
opgroup
opinventory
opmessage
opmessage_grp
opmessage_usr
optemplate
problem
problem_tag
profiles
proxy_autoreg_host
+proxy_dhistory
+proxy_history
regexps
rights
screen_user
screen_usrgrp
screens
screens_items
scripts
+service_alarms
services
services_links
services_times
sessions
slides
slideshow_user
slideshow_usrgrp
slideshows
sysmap_element_trigger
sysmap_element_url
sysmap_shape
sysmap_url
sysmap_user
sysmap_usrgrp
sysmaps
sysmaps_elements
sysmaps_link_triggers
sysmaps_links
task
task_acknowledge
task_close_problem
task_remote_command
task_remote_command_result
timeperiods
+trends
+trends_uint
trigger_depends
trigger_discovery
trigger_tag
triggers
users
users_groups
usrgrp
valuemaps
widget
widget_field

# 我們直接提取需要過濾的表
acknowledges
alerts
auditlog
auditlog_details
events
history
history_log
history_str
history_text
history_uint
proxy_dhistory
proxy_history
service_alarms
trends
trends_uint

# 使用--ignore-table跳過不需要備份的表

# 過濾最簡單的表只需要history*和trends*
mysqldump -uzabbix -pzabbix --databases zabbix \
--ignore-table=zabbix.history \
--ignore-table=zabbix.history_log \
--ignore-table=zabbix.history_str \
--ignore-table=zabbix.history_text \
--ignore-table=zabbix.history_uint \
--ignore-table=zabbix.trends \
--ignore-table=zabbix.trends_uint > /tmp/zabbix_config.sql

# 如果需要做更細化的過濾,可以參考下面的過濾表
mysqldump -uzabbix -pzabbix --databases zabbix \
--ignore-table=zabbix.acknowledges \
--ignore-table=zabbix.alerts \
--ignore-table=zabbix.auditlog \
--ignore-table=zabbix.auditlog_details \
--ignore-table=zabbix.events \
--ignore-table=zabbix.history \
--ignore-table=zabbix.history_log \
--ignore-table=zabbix.history_str \
--ignore-table=zabbix.history_text \
--ignore-table=zabbix.history_uint \
--ignore-table=zabbix.proxy_dhistory \
--ignore-table=zabbix.proxy_history \
--ignore-table=zabbix.service_alarms \
--ignore-table=zabbix.services_times \
--ignore-table=zabbix.trends \
--ignore-table=zabbix.trends_uint > /tmp/zabbix_config.sql

# 如果數據量交大垄开,可以考慮使用gzip壓縮
--ignore-table=zabbix.trends_uint | gzip > zabbix_`date +'%Y%m%d%H%M%S'`.sql.gz

# 上傳至新的數據庫執(zhí)行導入
mysql -uzabbix -pzabbix zabbix < zabbix_config.sql

itnihao的書中分享了一部分代碼琴许,可以做些許參考吧
https://github.com/itnihao/zabbix-book/tree/master/03-chapter

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市溉躲,隨后出現的幾起案子榜田,更是在濱河造成了極大的恐慌益兄,老刑警劉巖,帶你破解...
    沈念sama閱讀 211,042評論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件箭券,死亡現場離奇詭異净捅,居然都是意外死亡,警方通過查閱死者的電腦和手機邦鲫,發(fā)現死者居然都...
    沈念sama閱讀 89,996評論 2 384
  • 文/潘曉璐 我一進店門灸叼,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人庆捺,你說我怎么就攤上這事古今。” “怎么了滔以?”我有些...
    開封第一講書人閱讀 156,674評論 0 345
  • 文/不壞的土叔 我叫張陵捉腥,是天一觀的道長。 經常有香客問我你画,道長抵碟,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,340評論 1 283
  • 正文 為了忘掉前任坏匪,我火速辦了婚禮拟逮,結果婚禮上,老公的妹妹穿的比我還像新娘适滓。我一直安慰自己敦迄,他們只是感情好,可當我...
    茶點故事閱讀 65,404評論 5 384
  • 文/花漫 我一把揭開白布凭迹。 她就那樣靜靜地躺著罚屋,像睡著了一般。 火紅的嫁衣襯著肌膚如雪嗅绸。 梳的紋絲不亂的頭發(fā)上脾猛,一...
    開封第一講書人閱讀 49,749評論 1 289
  • 那天,我揣著相機與錄音鱼鸠,去河邊找鬼猛拴。 笑死,一個胖子當著我的面吹牛蚀狰,可吹牛的內容都是我干的愉昆。 我是一名探鬼主播,決...
    沈念sama閱讀 38,902評論 3 405
  • 文/蒼蘭香墨 我猛地睜開眼造锅,長吁一口氣:“原來是場噩夢啊……” “哼撼唾!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 37,662評論 0 266
  • 序言:老撾萬榮一對情侶失蹤倒谷,失蹤者是張志新(化名)和其女友劉穎蛛蒙,沒想到半個月后,有當地人在樹林里發(fā)現了一具尸體渤愁,經...
    沈念sama閱讀 44,110評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡牵祟,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 36,451評論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現自己被綠了抖格。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片诺苹。...
    茶點故事閱讀 38,577評論 1 340
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖雹拄,靈堂內的尸體忽然破棺而出收奔,到底是詐尸還是另有隱情,我是刑警寧澤滓玖,帶...
    沈念sama閱讀 34,258評論 4 328
  • 正文 年R本政府宣布坪哄,位于F島的核電站,受9級特大地震影響势篡,放射性物質發(fā)生泄漏翩肌。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 39,848評論 3 312
  • 文/蒙蒙 一禁悠、第九天 我趴在偏房一處隱蔽的房頂上張望念祭。 院中可真熱鬧,春花似錦碍侦、人聲如沸粱坤。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,726評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽比规。三九已至若厚,卻和暖如春拦英,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背测秸。 一陣腳步聲響...
    開封第一講書人閱讀 31,952評論 1 264
  • 我被黑心中介騙來泰國打工疤估, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人霎冯。 一個月前我還...
    沈念sama閱讀 46,271評論 2 360
  • 正文 我出身青樓铃拇,卻偏偏與公主長得像,于是被迫代替她去往敵國和親沈撞。 傳聞我的和親對象是個殘疾皇子慷荔,可洞房花燭夜當晚...
    茶點故事閱讀 43,452評論 2 348

推薦閱讀更多精彩內容

  • 先通過lnmp一鍵安裝包吧nginx和數據庫、php搞起來缠俺!然后:實現:1. 獲取zabbix centos:獲取...
    老夫劉某閱讀 2,237評論 0 3
  • 關于Mongodb的全面總結 MongoDB的內部構造《MongoDB The Definitive Guide》...
    中v中閱讀 31,905評論 2 89
  • Zabbix簡介 Zabbix官方網站Zabbix中文文檔 本文系統環(huán)境是CentOS7x86_64, Zabbi...
    Zhang21閱讀 7,968評論 0 37
  • 1. 最近幾天刷了一部電視劇,叫《上海女子圖鑒》磷雇。 不同于前段時間的《北京女子圖鑒》是這里基本都是一些新面孔偿警,可是...
    阿里與阿卡閱讀 239評論 0 1
  • 111
    30d0c573ea88閱讀 149評論 0 0