segunda-feira, 24 de setembro de 2012

PostgreSQL - Política de retenção para o PGBarman

Segue abaixo um agente que fiz para criar uma política de retenção dos backups do PGBarman, enquanto não existe uma oficial:

IMPORTANTE:

Ajustar a variável $opt_path para onde ficam os backups dos seus servidores, ou seja o seu 'barman_home = /backup/vtl-backups' no 'barman.conf'.

---

#!/usr/bin/perl -w

# Rotate barman agent
# Author: Gabriel Prestes(LM2)
# Date: 21/09/2012

use File::stat;
use Time::Local;

($opt_db, $opt_ret, $opt_type) = @ARGV;

if($#ARGV<2){ print "Need args!\n"; exit(1);}

$opt_path="/backup/vtl-backups/$opt_db/$opt_type";
$opt_retinsec=($opt_ret*3600)*24;
print "|RETENTION POLICY - $opt_db - $opt_ret days - $opt_type |\n";

my @ls=`\$\(which ls\) -td $opt_path/*`;

foreach(@ls){

        chomp($_);

        if(($opt_type =~ "wals") and ($_ !~ "xlog.db")){

                $mtime=stat($_)->mtime;
                $timenow = timelocal(localtime());
                $tempo=$timenow-$mtime;
                $mtimereal=localtime($mtime);

                if($tempo>=$opt_retinsec){

                        $rm=`\$\(which rm\) -rf $_`;
                        print "WALS REMOVED : $_ - $mtimereal\n";

                } else{

                        print "WALS PRESERVED : $_ - $mtimereal\n";

                }

        }

        if($opt_type =~ "base"){

                $mtime=stat($_)->mtime;
                $timenow = timelocal(localtime());
                $tempo=$timenow-$mtime;
                $mtimereal=localtime($mtime);

                if($tempo>=$opt_retinsec){

                        $rm=`\$\(which rm\) -rf $_`;
                        print "BACKUP REMOVED : $_ - $mtimereal\n";

                } else{

                        print "BACKUP PRESERVED : $_ - $mtimereal\n";

                }

        }

}

exit(0);


---

Coloque depois no /etc/cron.d/barman o seguinte conteúdo: 

# m h     dom mon dow   user     command
  0 */4    *   *   *   barman   [ -x /usr/bin/barman ] && /usr/bin/barman -q cron
  0 */4    *   *   *   barman   [ -x /usr/bin/barman ] && /usr/bin/barman backup meu_pgsql
  1 0      *   *   *   barman   /backup/resources/bin/barman-retention.pl meu_pgsql 15 wals >> /backup/log/barman.log
  1 0      *   *   *   barman   /backup/resources/bin/barman-retention.pl meu_pgsql 15 base >> /backup/log/barman.log

Onde: 

/backup/resources/bin/barman-retention.pl - é o path do agente
meu_pgsql - é o nome que configurou na entrada do barman.conf
15 - 15 dias de retenção, pode ser menos ou mais, como queira
base - tipo de limpeza, esse argumento fará limpeza de todo backup sem archives com mais de 15 dias, por exemplo.
wals - tipo de limpeza, esse argumento fará limpeza de todos os wals com mais de 15 dias, por exemplo. 

Apenas um detalhe, PG-RMan dá de laço no Barman, pois Barman não tem incremental(versão 1.0.0).