Last active
May 8, 2016 23:57
-
-
Save brianmed/c4531e9abc70d1bc7647105f037630f1 to your computer and use it in GitHub Desktop.
Mojolicious command for backing up a postgres database
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package Mojolicious::Command::backup_db; | |
use Mojo::Base 'Mojolicious::Command'; | |
use POSIX qw(strftime); | |
use autodie; | |
has description => 'Backup DB'; | |
has usage => "Usage: APPLICATION backup_db\n"; | |
sub run { | |
my ($self, @args) = @_; | |
my $app = $self->app; | |
my $dir = $app->home->rel_dir("../sql/backup"); | |
foreach my $db (@{ $app->config->{pg_dbs} }) { | |
chdir("$dir/$db"); | |
$self->backup($db)->trim($db); | |
} | |
} | |
sub backup { | |
my $self = shift; | |
my $db = shift; | |
my $file = strftime("$db.txt.%FT%T", localtime(time)); | |
system("sudo", "-u", "postgres", "/usr/pgsql-9.5/bin/pg_dump", $db, "-f", $file); | |
system("gzip", $file); | |
return $self; | |
} | |
sub trim { | |
my $self = shift; | |
my $db = shift; | |
my @backup_files = (); | |
opendir (my $dh, "."); | |
while (readdir $dh) { | |
if ($_ =~ m/^$db.txt.\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.gz$/) { | |
push (@backup_files, $_); | |
} | |
} | |
closedir ($dh); | |
@backup_files = sort({ $a cmp $b } @backup_files); | |
my $three_days_worth = 72; | |
my @old_backups = (); | |
if ($three_days_worth < scalar(@backup_files)) { | |
@old_backups = splice(@backup_files, 0, scalar(@backup_files) - $three_days_worth); | |
} | |
unlink(@old_backups); | |
return $self; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment