# @note Inspired by Puma capistrano handlers # @see https://github.com/seuros/capistrano-puma/blob/master/lib/capistrano/tasks/puma.rake namespace :load do task :defaults do set :karafka_role, :app set :karafka_default_hooks, -> { true } set :karafka_env, -> { fetch(:karafka_env, fetch(:environment)) } set :karafka_pid, -> { File.join(shared_path, 'tmp', 'pids', 'karafka.pid') } end end namespace :deploy do before :starting, :check_karafka_hooks do invoke 'karafka:add_default_hooks' if fetch(:karafka_default_hooks) end end namespace :karafka do desc 'Stop Karafka' task :stop do on roles(fetch(:karafka_role)) do |host| within shared_path do # If there's no pidfile it means that Karafka is not running next unless test "cat #{fetch(:karafka_pid)}" # Send a kill signal to a given process execute "kill -INT `cat #{fetch(:karafka_pid)}`" # And wait until it finishes. We wait because we don't want to start next process until # the previous one is stopped. That way we won't have problems with Kafka registering and # deregistering processes from topics (although nothing bad would happen. It would just # take more time to rebalance) while true break unless test "cat #{fetch(:karafka_pid)}" info 'Waiting for Karafka to stop' sleep 5 end end end end desc 'Start Karafka' task :start do on roles(fetch(:karafka_role)) do |host| within current_path do # We use all 3 because when combined with Sinatra/Rails it will use their parts as well # so we want to set proper env for any of them with( KARAFKA_ENV: fetch(:karafka_env), RAILS_ENV: fetch(:rails_env), RACK_ENV: fetch(:rack_env) )do execute :bundle, "exec karafka server -d -p #{fetch(:karafka_pid)}" end end end end desc 'Restart Karafka' task :restart do invoke 'karafka:stop' invoke 'karafka:start' end desc 'Status Karafka' task :status do on roles(fetch(:karafka_role)) do |host| if test "cat #{fetch(:karafka_pid)}" pid = capture "cat #{fetch(:karafka_pid)}" if test "ps -p #{pid} > /dev/null" info "Karafka is started: #{pid}" else error "Karafka is not started but pidfile exists" end else info "Karafka is not started" end end end task :add_default_hooks do after 'deploy:finished', 'karafka:restart' end end