quinta-feira, setembro 23, 2010

Simples Programa de Backup de MySQL

#!/bin/bash
#
# ===========================
# Programa de Backup de MySQL
# ===========================
#
#
#
# Objetivos
# =========
#
#  Executar um backup de todas as tabelas de cada servidor MySQL em produção da UFCSPA
#
#
# Responsáveis 
# ============
#
#  - Klaus Engelmann (programação)
#  - Anderson Domingues (validação de dados)
#
# Histórico
# =========
#
#  - (Klaus Engelmann - 21/09/2010)
#      - Início do desenvolvimento. 
#        - Habilitar programa para o moodle.ufcspa.edu.br e anubis.ufcspa.edu.br.
#        - Desenvolver parte "1" do algoritmo.
#        - Desenvolver parte "2" do algoritmo.
#        - Execução de Testes de Mesa.
#        - A variável hostname do mysqldump deve ser declarada durante a execução do laço.
#        - Mudar o formato da data para contabilizar minutos e segundos.
#        - A variável DATA deve ser declarada durante a execução do laço.
#        - Configuração da CRON para executar o programa.
#
# - (Klaus Engelmann - 22/09/2010)
#        - Correção de erro de redirecionamento por causa do formato da data. 
#        - Teste da Cron
#
# - (Klaus Engelmann - 23/09/2010)
#        - Desenvolvimento da Etapa 3 do algoritmo.
#        - Formatação da mensagem do relatório.
#        - Configuração do sistema de email da dracula.ufcspa.lan
#        - Teste e Validação do relatório.
#              
#
# Funcionamento do Programa de Backups
# ====================================
#
# Será realizado um Full Backup toda madrugada às 04:00 hs.
# Cada execução da rotina de backup verificará o seguinte algoritmo:
#
# 1- Criação do arquivo de backup.
# 2- Exclusão dos arquivos que são 5 dias mais antigos.
# 3- Envio de relatório de arquivos por email
#
#
# Parâmetros do comando mysqldump
# ===============================
#
# O comando mysqldump realiza o dump dos bancos de dados e tabelas. Ele é o principal artífice do backup. 
# Os parâmetros utilizados estão comentados abaixo conforme o "man mysqldump".
#
#
#  --add-drop-table
#
#          Add a DROP TABLE statement before each CREATE TABLE statement.
#
#  --add-locks 
#
#          Surround each table dump with LOCK TABLES and UNLOCK TABLES statements. This results in faster inserts when the dump file is reloaded.
#
#  --comments, -i 
#
#          Write additional information in the dump file such as program version, server version, and host. This option is enabled by default. To
#          suppress this additional information, use --skip-comments.
#
#  --extended-insert, -e 
#
#          Use multiple-row INSERT syntax that include several VALUES lists. This results in a smaller dump file and speeds up inserts when the file is
#          reloaded.
#
#  --flush-privileges 
#
#          Emit a FLUSH PRIVILEGES statement after dumping the mysql database. This option should be used any time the dump contains the mysql database
#          and any other database that depends on the data in the mysql database for proper restoration. This option was added in MySQL 5.0.26.
#
#  --force, -f 
#
#          Continue even if an SQL error occurs during a table dump.
#
#          One use for this option is to cause mysqldump to continue executing even when it encounters a view that has become invalid because the
#          definition refers to a table that has been dropped. Without --force, mysqldump exits with an error message. With --force, mysqldump prints
#          the error message, but it also writes an SQL comment containing the view definition to the dump output and continues executing.
#
#  --host=host_name, -h host_name 
#
#          Dump data from the MySQL server on the given host. The default host is localhost.
#
#  --lock-all-tables, -x 
#
#          Lock all tables across all databases. This is achieved by acquiring a global read lock for the duration of the whole dump. This option
#          automatically turns off --single-transaction and --lock-tables.
#
#  --log-error=file_name 
#
#          Append warnings and errors to the named file. This option was added in MySQL 5.0.42.
#
#  --password[=password], -p[password] 
#
#          The password to use when connecting to the server. If you use the short option form (-p), you cannot have a space between the option and the
#          password. If you omit the password value following the --password or -p option on the command line, you are prompted for one.
#
#          Specifying a password on the command line should be considered insecure. See Section 5.6, “Keeping Passwords Secure”.
#
#  --user=user_name, -u user_name 
#
#          The MySQL user name to use when connecting to the server.
#
#



# -------------------------------
# Variáveis Estáticas do Programa
# -------------------------------

# Lista de servidores MySQL para executar backup
declare -a HOSTS=( 'teste1.teste.com' 'teste2.teste.com' 'teste3.teste.com' ) 

# Senha do usuário backup
PASS="put-your-own"

# Configuração do comando mysqldump
MYSQLDUMP="/usr/bin/mysqldump --all-databases \
                              --add-drop-table \
                              --add-locks \
                              --log-error=/var/log/bkp-mysql-error.log \
                              --comments \
                              --extended-insert \
                              --flush-privileges \
                              --force \
                              --lock-all-tables \
                              -u backup \
                              -p$PASS"
                              


# ---------------------
# Execução do mysqldump
# ---------------------

# Criação dos DUMPS do mysql
for I in "${HOSTS[@]}"
do
   {
      # Formato de data: dia-mes-ano-hora-minuto-segundo
      DATA=$( /bin/date +%d-%m-%Y-%H-%M-%S )
      $MYSQLDUMP -h $I > /backup3/bkp-$I-$DATA.sql
   }
done


# -----------------------------------------
# Exclusão de Arquivos criados 5 dias atrás 
# -----------------------------------------

/usr/bin/find /backup3 -atime +5 -exec rm -f {} \;


# ----------------------------------------
# Geração e envio do relatório de execução
# ----------------------------------------

LISTAGEM=$(ls -lha /backup3/)
OCUPACAO=$(du -sh /backup3/)
DISCO=$(df -h) 

RELATORIO="\nResultado do Backup de Sevidores MYSQL\n\n\nOs arquivos armazenados são:\n$LISTAGEM\n\nTotal Uso:\n$OCUPACAO\n\nOcupação do Filesystem:\n$DISCO\n\n"

echo -e "$RELATORIO" | mail -s"Relatorio de Backup MySQL" root


exit 0