Skip to content

Instantly share code, notes, and snippets.

@gokhangirgin
Created March 18, 2017 13:41
Show Gist options
  • Save gokhangirgin/2d88587847ff58d4e1246338b786d05e to your computer and use it in GitHub Desktop.
Save gokhangirgin/2d88587847ff58d4e1246338b786d05e to your computer and use it in GitHub Desktop.
GenServer pg_dump
defmodule MyApp.PgDump do
use GenServer
require Logger
@backup_config Application.get_env(:myapp, :db_backup_config)
def start_link do
GenServer.start_link(__MODULE__, [], name: :pg_dump)
end
defp schedule_database_backup() do
Process.send_after(self(), :database_backup, 1000 * 60 * @backup_config[:interval]) #6 hours
end
def init(state) do
schedule_database_backup()
{:ok, state}
end
def handle_info(:database_backup, state) do
db_config = Application.get_env(:myapp, MyApp.Repo)
file_name = "#{@backup_config[:path]}/#{db_config[:database]}_#{Timex.now |> Timex.to_unix}"
command = "pg_dump -d #{db_config[:database]} | gzip -9 > #{file_name}.sql.gz" |> String.to_charlist
:os.cmd(command)
{:ok, files} = File.ls(@backup_config[:path])
file_length = length(files)
if file_length > @backup_config[:max_storage] do
files
|> Enum.slice(0, file_length - @backup_config[:max_storage])
|> Enum.each(fn(file) ->
File.rm!("#{@backup_config[:path]}/#{file}")
end)
end
schedule_database_backup()
{:noreply, state}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment