Zabbix安裝和使用配置小結

前言

Zabbix是目前最爲主流的開源監控方案之一,部署自己並不困難,難的是深刻理解。根據在生產環境的實踐重新版Zabbix 4.0 LTS開始所有使用Docker部署,我相信將來愈來愈多的開源組件都會以容器化的形式呈如今咱們面前。php

學習使用Zabbix

更新歷史

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

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

擴展閱讀linux

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


官方文檔

https://www.zabbix.com/download
https://www.zabbix.com/docume...git

zabbix-server

基於官方的LAMP架構,按照最簡單的原生方式來部署,不作任何多餘優化
# 安裝必要依賴包
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時區
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

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

# 建立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

# 修改時區
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表分區優化

https://www.zabbix.org/wiki/D...
https://cloud.tencent.com/dev...github

Zabbix數據庫優化
目的: 快速清理歷史數據,並減小數據存儲容量
方法: 歷史表使用分區表(刪除分區錶速度快),使用Tokudb引擎(適合大量insert少許update和select等日誌表)
Zabbix版本: 3.4
涉及表項:
存儲不一樣類型item的歷史數據,最終1小時或者1天等段時間的繪圖數據從其中獲取
history、history_log、history_str、history_text、history_uint
存儲不一樣類型item的歷史趨勢數據,每隔一小時從歷史數據中統計一次,並計算統計區間的平均值,最大值,最小值trends、trends_uintweb

zabbix的db有作分表 根據這個來的
https://www.zabbix.org/wiki/D...
cronjob裏的腳本包括了建新表和刪除舊錶,用mysql的procedure控制,刪除舊錶能夠釋放空間
想要修改短一點,須要修改procedure partition_maintenance_all裏規定的時間
個人作法是Drop舊procedure再建立新的sql

存儲過程執行後將可使用命令對想要分區的表進行表分區了,其中的參數我這裏解釋一下。docker

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:每隔多久生成一個分區
num_future_intervals_to_create:本次一共生成多少個分區

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

這裏能夠將上面四個存儲過程保存爲一個文件,導入到數據庫中,文件我稍後將會放在附件中,這裏使用的命令是

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/docume...

# 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自定義監控

以監控文件系統目錄的權限爲例

Zabbix用戶自定義參數
https://www.zabbix.com/docume...

# 新建自定義監控配置文件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中建立新的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使用企業微信告警配置小結
https://wsgzao.github.io/post...

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

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

itnihao的書中分享了一部分代碼,能夠作些許參考吧
https://github.com/itnihao/za...

相關文章
相關標籤/搜索