# Zabbix: Instalando o servidor

## 1. Introdução

<span style="font-weight: 400;">Zabbix é uma solução de código aberto para monitoramento de dispositivos e aplicações, sendo capaz de monitorar parâmetros utilizando agentes em diversas plataformas de sistemas operacionais, além de protocolos como SNMP, IPMI, JMX, entre outros.</span>

<span style="font-weight: 400;">É uma plataforma bastante difundida e não está limitada a ativos de TIC, apenas. Pode ser utilizado em diversas áreas, pois o seu método de coleta é flexível e permitindo personalizá-lo de acordo com necessidades de monitoramento do ambiente.</span>

## <span style="font-weight: 400;">2. Ferramentas utilizadas</span>

<span style="font-weight: 400;">Os softwares utilizados na produção deste tutorial é apresentado a seguir:</span>

- <span style="font-weight: 400;">CentOS 7</span>
- <span style="font-weight: 400;">Zabbix 3.4.1</span>
- <span style="font-weight: 400;">MariaDB 10.3.9-1.el7.centos</span>

<span style="font-weight: 400;">O ambiente utilizado é apresentado a seguir:</span>

- <span style="font-weight: 400;">Uma MV, com o sistema operacional CentOS 7, destinada ao banco de dados</span>
- <span style="font-weight: 400;">Uma MV, com o sistema operacional CentOS 7, destinada ao servidor e interface Web do Zabbix</span>

<span style="font-weight: 400;">A instalação do CentOS 7 utilizada para validar esse tutorial foi a Minimal-1611. A ISO dessa versão pode ser baixada através deste [link](http://mirror.ufscar.br/centos/7/isos/x86_64/).</span>

## <span style="font-weight: 400;">3. Configurando o serviço</span>

<span style="font-weight: 400;">Todos os comandos executados nesse tutorial foram executados com o usuário **root**.</span>

### <span style="font-weight: 400;">3.1. Instalando o servidor de banco de dados</span>

#### <span style="font-weight: 400;">Passos preparatórios</span>

<span style="font-weight: 400;">3.1.1. </span><span style="font-weight: 400;">Após a instalação do CentOS, execute o comando abaixo para atualizar os pacotes presentes no sistema:</span>

```
yum update
```

<span style="font-weight: 400;">3.1.2. Habilite o modo permissivo do SELinux, com os comandos abaixo:</span>

```shell
sed s/SELINUX=enforcing/SELINUX=permissive/g -i /etc/selinux/config
setenforce 0
```

<span style="font-weight: 400;">3.1.3. Adicione os repositórios do Zabbix e MariaDB:</span>

```shell
URL='https://repo.zabbix.com/zabbix/3.4/rhel/7/x86_64/zabbix-release-3.4-2.el7.noarch.rpm'
rpm -ivh "$URL" # Adiciona o repositório do zabbix
printf '[mariadb]\nname = MariaDB\nbaseurl = http://yum.mariadb.org/10.3/centos7-amd64\ngpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB\ngpgcheck=1\n' > /etc/yum.repos.d/MariaDB.repo
```

<span style="font-weight: 400;">3.1.4. Instalar o agente do Zabbix </span>

```shell
yum install zabbix-agent zabbix-get # Instala o agente do zabbix
systemctl enable zabbix-agent # Configura o systemd para iniciar o agente do zabbix após o boot
```

<p class="callout warning"><span style="font-weight: 400;">Caso o local do armazenamento dos arquivos seja numa partição separada, insira a linha correta no fstab, definindo como ponto de montagem o diretório do mysql e monte-a digitando o comando ***mount -a***</span></p>

<span style="font-weight: 400;">3.1.5. Instalar o MariaDB </span>

```shell
yum install mariadb-server mariadb-libs mariadb -y # Instala o servidor
chown -R mysql:mysql /var/lib/mysql # Configura as permissões no diretório usado pelo mariadb
systemctl enable mariadb # Configura o systemd para iniciar o mariadb após o boot
systemctl start mariadb # Iniciar o serviço do mariadb imediatamente
```

<span style="font-weight: 400;">3.1.6. Permita os serviços no Firewall</span>

```shell
firewall-cmd --permanent --add-port=3306/tcp # configura o firewalld para permitir conexões ao mariadb
firewall-cmd --permanent --add-port=10050/tcp # configura o firewalld para permitir conexões ao agente do zabbix
firewall-cmd --reload
```

#### Configure o servidor de banco de dados

<span style="font-weight: 400;">3.1.7. Complete a instalação do MariaDB:</span>

```shell
mysql_secure_installation
```

<span style="font-weight: 400;">Com o comando acima iremos configurar a senha do usuário </span>**root**<span style="font-weight: 400;"> para acessar o MySQL.</span>

```shell
# Enter current password for root (enter for none): <ENTER>
# Change the root password? [Y/n] <Y>
# New password: <DIGITE UMA SENHA SEGURA>
# Re-enter new password: <DIGITE A SENHA NOVAMENTE>
# Remove anonymous users? [Y/n] <Y>
# Disallow root login remotely? [Y/n] <Y>
# Remove test database and access to it? [Y/n] <Y>
# Reload privilege tables now? [Y/n] <Y>
```

<p class="callout warning"><span style="font-weight: 400;">Para manter a segurança num nível aceitável, crie uma senha segura, com no mínimo 8 dígitos, contendo letras maiúsculas e minúsculas e caracteres especiais. </span></p>

<p class="callout info"><span style="font-weight: 400;">Observe também que esta senha deve ser guardada em local seguro para possíveis acesso e manutenções.</span></p>

<span style="font-weight: 400;">3.1.8. Crie a base de dados para o Zabbix</span>

<span style="font-weight: 400;">Acesse o mariadb como </span>**root**<span style="font-weight: 400;">:</span>

```shell
mysql -uroot -p
```

<span style="font-weight: 400;">Digite a senha cadastrada no passo anterior. Deverá aparecer o prompt da console do MySQL. Iremos criar a base de dados que será utilizada pelo Zabbix:</span>

<table id="bkmrk-mysql%3E-mysql%3E-mysql%3E" style="width: 812px; background-color: #f8f8f8;"><tbody><tr><td style="width: 65px;">mysql&gt;

mysql&gt;

mysql&gt;

</td><td style="width: 743.017px;"><span style="font-weight: 400;">create database </span>**BASE\_ZABBIX**<span style="font-weight: 400;">;</span>

<span style="font-weight: 400;">grant all privileges on **BASE\_ZABBIX**.\* to '**USUARIO\_ZABBIX**'@'%' identified by '**SENHA\_ZABBIX**';</span>

<span style="font-weight: 400;">quit;</span>

</td></tr></tbody></table>

 <span style="font-weight: 400;">O comando</span><span style="font-weight: 400;"> ‘</span><span style="font-weight: 400;">create database</span><span style="font-weight: 400;">’ </span><span style="font-weight: 400;">cria a base de dados para o </span>**zabbix**<span style="font-weight: 400;">. Observe que o termo “</span><span style="font-weight: 400;">**base\_z**</span>**abbix**<span style="font-weight: 400;">” deve ser substituído pelo nome escolhido. </span>

<span style="font-weight: 400;">O comando iniciando com</span><span style="font-weight: 400;"> ‘</span><span style="font-weight: 400;">grant all privileges</span><span style="font-weight: 400;">‘ concede</span><span style="font-weight: 400;"> permissão para o usuário do </span>**zabbix**<span style="font-weight: 400;"> com a senha a ser digitada no lugar de</span> "**senha\_zabbix**"<span style="font-weight: 400;">. </span><span style="font-weight: 400;">Observe que o termo “</span><span style="font-weight: 400;">**usuario\_z**</span>**abbix**<span style="font-weight: 400;">” deve ser substituído pelo nome do usuário que o servidor irá utilizar ao se conectar à base de dados. </span>

<p class="callout warning"><span style="font-weight: 400;">Para manter a segurança num nível aceitável, crie uma senha segura, com no mínimo 8 dígitos, contendo letras maiúsculas e minúsculas e caracteres especiais. </span></p>

<p class="callout info"><span style="font-weight: 400;">Observe também que esta senha deve ser guardada em local seguro para possíveis acesso e manutenções.</span></p>

<span style="font-weight: 400;">Essas informações serão utilizadas para o acesso a base de dados no arquivo de configuração do servidor Zabbix.</span>

### <span style="font-weight: 400;">3.2. Instalando o servidor do Zabbix  
</span>

#### <span style="font-weight: 400;">Passos preparatórios</span>

<span style="font-weight: 400;">3.2.1. Após a instalação do CentOS no servidor, execute o comando abaixo para atualizar os pacotes presentes no sistema:</span>

```
yum update
```

<span style="font-weight: 400;">3.2.2. Habilite o modo permissivo do SELinux, com os comandos abaixo:</span>

```shell
sed s/SELINUX=enforcing/SELINUX=permissive/g -i /etc/selinux/config
setenforce 0
```

<span style="font-weight: 400;">3.2.3. Ad</span><span style="font-weight: 400;">icione os repositórios do Zabbix e MariaDB:</span>

```shell
URL='https://repo.zabbix.com/zabbix/3.4/rhel/7/x86_64/zabbix-release-3.4-2.el7.noarch.rpm'
rpm -ivh "$URL" # Adiciona o repositório do zabbix
printf '[mariadb]\nname = MariaDB\nbaseurl = http://yum.mariadb.org/10.3/centos7-amd64\ngpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB\ngpgcheck=1\n' > /etc/yum.repos.d/MariaDB.repo
```

<span style="font-weight: 400;">3.2.4. In</span><span style="font-weight: 400;">stale os pacotes necessários </span>

```shell
yum install wget unzip net-snmp net-snmp-utils -y # Instala dependências do SNMP
yum install zabbix-agent zabbix-get -y # Instala o agente do zabbix
yum install zabbix-server-mysql mariadb -y # Instala as bibliotecas do mariadb e o servidor zabbix
yum install zabbix-web-mysql -y # Instala a interface web do servidor zabbix
```

<span style="font-weight: 400;">3.2.5. Permita os serviços no Firewall</span>

```shell
firewall-cmd --permanent --add-port=10050/tcp # configura o firewalld para permitir conexões ao agente do zabbix
firewall-cmd --permanent --add-port=10051/tcp # configura o firewalld para permitir conexões ao servidor do zabbix
firewall-cmd --permanent --add-service=snmp   # configura o firewalld para permitir conexões snmp
firewall-cmd --permanent --add-service=snmptrap # configura o firewalld para permitir conexões snmp
firewall-cmd --reload
```

<span style="font-weight: 400;">3.2.6. Configure as MIBs do SNMP  
</span>

```shell
cd /usr/share/snmp/mibs/
wget -c -m ftp://ftp.cisco.com/pub/mibs/v2/
mv ftp.cisco.com/pub/mibs/v2/* .
rm -fr ftp.cisco.com/
for line in $(ls *.my); do base=$(echo $line|cut -d'.' -f1); mv $line $base; done
```

```
cd /usr/share/snmp/mibs/
wget -c https://github.com/librenms/librenms-mibs/archive/master.zip -O Cisco-SB-MIB.zip
unzip -jo Cisco-SB-MIB.zip
rm -fr Cisco-SB-MIB.zip
for line in $(ls *.mi2); do base=$(echo $line|cut -d'.' -f1); mv -n $line $base; done
```

#### Configure a base de dados

<span style="font-weight: 400;">3.2.7. </span> I<span style="font-weight: 400;">mportar os schemas:</span>

```shell
cd /usr/share/doc/zabbix-server-mysql-3.*
zcat create.sql.gz | mysql -h IP_SERVIDOR_BANCO -u USUARIO_ZABBIX -p BASE_ZABBIX  
```

<span style="text-decoration: underline;"><span style="font-weight: 400;">A senha solicitada, assim como os itens "USUARIO\_ZABBIX" e "BASE\_ZABBIX" devem ser os mesmos configurados no passo "Crie a base de dados para o Zabbix".</span></span>

<p class="callout info"><span style="font-weight: 400;">Substitua o “IP\_SERVIDOR\_BANCO” pelo IP do servidor do banco de dados configurado anteriormente.</span></p>

#### <span style="font-weight: 400;">Configure o servidor zabbix  
</span>

<span style="font-weight: 400;">3.2.8. Será necessário alterar alguns parâmetros do banco de dados no arquivo de configuração `/etc/zabbix/zabbix_server.conf`: </span>

```shell
cd /etc/zabbix             # Entra no diretório do zabbix
mkdir -p original          # Cria diretório para backup, se não existir
cp zabbix*.conf original/  # Copia os arquivos de configuração originais para pasta criada
sed s/'LogFileSize=0'/'LogFileSize=128'/g -i zabbix_server.conf # Define o tamanho máximo de cada arquivo de log
sed s/'Timeout=4'/'Timeout=20'/g -i zabbix_server.conf          # Define o timeout da conexão ao cliente
sed s/'# StartSNMPTrapper=0'/'StartSNMPTrapper=1'/g -i zabbix_server.conf   # Define se o SNMP trapper será ativado
sed s/'# SenderFrequency=30'/'SenderFrequency=60'/g -i zabbix_server.conf   # Frequencia submetida aos senders
sed s/'# StartDBSyncers=4'/'StartDBSyncers=8'/g -i zabbix_server.conf       # Define a quantidade de sicronizadores entre a aplicação e o bd
sed s/'# StartPollers=5'/'StartPollers=35'/g -i zabbix_server.conf          # Quantidade de pollers multipropósito (para java, ipmi e etc)  
sed s/'# HistoryCacheSize=16M'/'HistoryCacheSize=128M'/g -i zabbix_server.conf         # Tamanho do cache para histórico de alterações  
sed s/'# HistoryIndexCacheSize=4M'/'HistoryIndexCacheSize=64M'/g -i zabbix_server.conf # Tamanho do cache para o indice do histórico
sed s/'# TrendCacheSize=4M'/'TrendCacheSize=64M'/g -i zabbix_server.conf # Tamanho do cache usado para armazenar tendências
sed s/'# ValueCacheSize=8M'/'ValueCacheSize=64M'/g -i zabbix_server.conf # Tamanho do cache de valores
sed s/'# CacheSize=8M'/'CacheSize=512M'/g -i zabbix_server.conf          # Tammanho máximo que todos os caches, somados, podem alcançar 
sed s/'# StartVMwareCollectors=0'/'StartVMwareCollectors=16'/g -i zabbix_server.conf # Quantidade de coletores de dados do vmware
sed s/'# VMwareCacheSize=8M'/'VMwareCacheSize=16M'/g -i zabbix_server.conf       # Cache para os dados de vmware coletados
sed s/'# VMwareTimeout=10'/'VMwareTimeout=30'/g -i zabbix_server.conf            # Define timeout para conexão ao agente do vmware
sed s/'# DBHost=localhost'/'DBHost=IP_SERVIDOR_BANCO'/g -i zabbix_server.conf # Servidor onde está a BD do zabbix. Substitua IP_SERVIDOR_BD pelo IP correto 
sed s/'DBName=zabbix'/'DBName=BASE_ZABBIX'/g -i zabbix_server.conf         # BD a ser utilizada pelo zabbix. Substitua pelo nome correto 
sed s/'# DBPassword='/'DBPassword=SENHA_ZABBIX'/g -i zabbix_server.conf    # Senha para conexão a BD. Substitua pela senha correta 
sed s/'DBUser=zabbix'/'DBUser=USUARIO_ZABBIX'/g -i zabbix_server.conf      # Usuário para conexão a BD. Substitua pelo nome correto
```

<span style="text-decoration: underline;"><span style="font-weight: 400;">A senha solicitada, assim como os itens "USUARIO\_ZABBIX" e "BASE\_ZABBIX" devem ser os mesmos configurados no passo "Crie a base de dados para o Zabbix".</span></span>

<p class="callout info"><span style="font-weight: 400;">Substitua o “IP\_SERVIDOR\_BANCO” pelo IP do servidor do banco de dados configurado anteriormente.</span></p>

<span style="font-weight: 400;">3.2.9. Configure o serviço do servidor e agente:</span>

```shell
systemctl enable zabbix-agent zabbix-server-mysql # Configura o systemd para iniciar os serviços do zabbix após o boot
systemctl start zabbix-server zabbix-agent        # Inicia os serviços imediatamente
```

<span style="font-weight: 400;">Realizada a instalação da base de dados e do servidor Zabbix, o próximo passo é configurar e instalar a interface web.</span>

### <span style="font-weight: 400;">3.3. Instalando a interface web servidor do Zabbix</span>

<p class="callout warning"><span style="font-weight: 400;">*A interface web e o servidor podem ser instalados na mesma máquina. No entanto, esse procedimento não é recomendado em ambientes de alta disponibilidade.*</span></p>

#### <span style="font-weight: 400;">Passos preparatórios</span>

<span style="font-weight: 400;">3.3.1. Após a instalação do CentOS no servidor, execute o comando abaixo para atualizar os pacotes presentes no sistema:</span>

```
yum update
```

<span style="font-weight: 400;">3.3.2. Habilite o modo permissivo do SELinux, com os comandos abaixo:</span>

```shell
sed s/SELINUX=enforcing/SELINUX=permissive/g -i /etc/selinux/config
setenforce 0
```

<span style="font-weight: 400;">3.3.3. Ad</span><span style="font-weight: 400;">icione os repositórios do Zabbix e MariaDB:</span>

```shell
URL='https://repo.zabbix.com/zabbix/3.4/rhel/7/x86_64/zabbix-release-3.4-2.el7.noarch.rpm'
rpm -ivh "$URL" # Adiciona o repositório do zabbix
printf '[mariadb]\nname = MariaDB\nbaseurl = http://yum.mariadb.org/10.3/centos7-amd64\ngpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB\ngpgcheck=1\n' > /etc/yum.repos.d/MariaDB.repo
```

<span style="font-weight: 400;">3.3.4. In</span><span style="font-weight: 400;">stale os pacotes necessários </span>

```shell
yum install zabbix-agent zabbix-get -y # Instala o agente do zabbix
yum install mariadb zabbix-web-mysql -y # Instala as bibliotecas do mariadb e a aplicação web do zabbix
```

<span style="font-weight: 400;">3.3.5. Permita o serviço no Firewall</span>

```shell
firewall-cmd --permanent --add-service=http   # configura o firewalld para permitir conexões http
firewall-cmd --permanent --add-service=https # configura o firewalld para permitir conexões https
firewall-cmd --reload
```

#### <span style="font-weight: 400;">Configure a aplicação web do Zabbix</span>

<span style="font-weight: 400;">3.3.6. Edite o arquivo contendo as definições do site do zabbix  
</span>

```shell
cd /etc/httpd/conf.d/                            # Diretório de configuração dos sites do apache
sed s/'# php_value'/'php_value'/g -i zabbix.conf # Ativa as definições do PHP dentro do arquivo
sed s/'timezone.*'/'timezone America\/Recife'/g -i zabbix.conf # Define o timezone correto
sed s/'Alias'/'# Alias'/g -i zabbix.conf           # Retira o alias "/zabbix/"
sed '6i Alias / /usr/share/zabbix/' -i zabbix.conf # Adiciona o alias "/", redirecionando o indice no referido diretório
```

<span style="font-weight: 400;">3.3.7. Crie o arquivo de configuração da aplicação web do zabbix</span>

`<span style="font-weight: 400;">vi /etc/zabbix/web/zabbix.conf.php</span>`

<span style="font-weight: 400;">A</span><span style="font-weight: 400;">s configurações deverão ficar conforme o exemplo abaixo:</span>

```
<?php
// Zabbix GUI configuration file.
global $DB;
$DB['TYPE']     = 'MYSQL';
$DB['SERVER']   = 'IP_SERVIDOR_BANCO';
$DB['PORT']     = '0';
$DB['DATABASE'] = 'BASE_ZABBIX';
$DB['USER']     = 'USUARIO_ZABBIX';
$DB['PASSWORD'] = 'SENHA_ZABBIX';
 
// Schema name. Used for IBM DB2 and PostgreSQL.
$DB['SCHEMA'] = '';
 
$ZBX_SERVER      = 'localhost';
$ZBX_SERVER_PORT = '10051';
$ZBX_SERVER_NAME = 'zabbix.int.example.com';
 
$IMAGE_FORMAT_DEFAULT = IMAGE_FORMAT_PNG;
```

<span style="text-decoration: underline;"><span style="font-weight: 400;">Os itens "USUARIO\_ZABBIX" , "SENHA\_ZABBIX" e "BASE\_ZABBIX" devem ser os mesmos configurados no passo "***Crie a base de dados para o Zabbix***".</span></span>

<span style="text-decoration: underline;"><span style="font-weight: 400;">Em **$ZBX\_SERVER**, substitua "localhost" pelo IP ou FQDN da máquina onde o servidor Zabbix está instalado.</span></span>

<span style="text-decoration: underline;"><span style="font-weight: 400;">Em **$ZBX\_SERVER\_NAME**, substitua "zabbix.int.example.com" pelo nome a ser dado ao servidor.</span></span>

<p class="callout info"><span style="font-weight: 400;">Substitua o “IP\_SERVIDOR\_BANCO” pelo IP do servidor do banco de dados configurado anteriormente.</span></p>

<span style="font-weight: 400;">3.3.8. Configure o serviço utilizado pela interface gráfica:</span>

```shell
systemctl enable httpd # Configura o systemd para iniciar o apachea pós o boot
systemctl start httpd  # Inicia osserviço imediatamente
```

### <span style="font-weight: 400;">3.4. Configurações adicionais</span>

#### <span style="font-weight: 400;">Passos preparatórios</span>

<span style="font-weight: 400;">3.4.1. Neste momento, abra o seu navegador favorito e insira o endereço do teu servidor, conforme o exemplo abaixo:</span>

<span style="font-weight: 400;">https://IP-DO-SERVIDOR/</span>

<span style="font-weight: 400;">Será mostrada uma tela solicitando credenciais. </span><span style="font-weight: 400;">Faça login no sistema com o usuário </span>**Admin**<span style="font-weight: 400;"> e a senha </span>**zabbix**<span style="font-weight: 400;">.</span>

#### <span style="font-weight: 400;">Configure o inventário e monitoramento do servidor</span>

<span style="font-weight: 400;">3.4.2. Primeiro, vamos habilitar a capacidade do Zabbix de fazer inventário de alguns itens sobre os dispositivos monitorados:</span>

<span style="font-weight: 400;">Clique em </span>**Administration &gt; General**<span style="font-weight: 400;">. No dropbox à direita, clique em </span>**Others.**

<span style="font-weight: 400;">3.4.3. Feito isso, vamos habilitar o monitoramento do próprio servidor: </span>

<span style="font-weight: 400;">Clique em </span>**Configuration &gt; Hosts**<span style="font-weight: 400;">, </span>**marque** o checkbox ao lado de **“Zabbix Server”**<span style="font-weight: 400;"> e clique no botão “</span>**Enable**<span style="font-weight: 400;">”.</span>

<span style="font-weight: 400;"> </span>