ecsにおけるunicronのgraceful shutdown

コンテナのライフサイクル

タスクが停止すると、各コンテナのエントリプロセス (通常は PID 1) に SIGTERM シグナルを送信します。
タイムアウトが経過すると、今度は SIGKILL シグナルをプロセスに送信します。
デフォルトでは、SIGTERM シグナルの送信後 30 秒のタイムアウトで SIGKILL シグナルを送信します。

ECS のアプリケーションを正常にシャットダウンする方法 | Amazon Web Services ブログ

SIGKILLされるまでの時間はデフォルトで30秒でMAXで120秒のようだ。
そんな重い処理はないので今回は考える必要はないがSidekiqやResqueなどでそれなりに重い非同期処理をしたい場合は何か必要。
バッチ化するとかキューを積み直すとか???

 

unicornの挙動

unicornにSIGTERMを送った場合は即シャットダウンでgraceful shutdownしたい場合はSIGQUITを送る必要がありそう

Signal handling

 

unicornでSIGTERMを受け取ったらSIGQUITする処理を実装する

unicorn.config

before_fork do |server, worker|
  Signal.trap 'TERM' do
    puts 'Unicorn master intercepting TERM and sending myself QUIT instead'
    Process.kill 'QUIT', Process.pid
  end
end

after_fork do |server, worker|
  Signal.trap 'TERM' do
    puts 'Unicorn worker intercepting TERM and doing nothing.'
  end
end

 

実際にgraceful shutdownするか確認

1. sleepを入れたapiを作成する

class TestController < ActionController::API
  def test
    sleep(10)
    render text: 'OK'
  end
end

2. apiをコールしてsleep中にunicornにsigtermを送る

root@06b4da6d0c07:/app# ps aux | grep unicorn
root         1  0.4  1.2  90216 24964 pts/0    Ss+  11:03   0:00 unicorn master -p 3100 -c /app/config/unicorn/development.rb
root         8  2.0  5.3 661524 109292 pts/0   Sl+  11:03   0:02 unicorn worker[0] -p 3100 -c /app/config/unicorn/development.rb
root         9  2.0  5.3 661524 109168 pts/0   Sl+  11:03   0:02 unicorn worker[1] -p 3100 -c /app/config/unicorn/development.rb
root        10  2.0  5.3 661536 109280 pts/0   Sl+  11:03   0:02 unicorn worker[2] -p 3100 -c /app/config/unicorn/development.rb
root        11  2.0  5.3 661520 109176 pts/0   Sl+  11:03   0:02 unicorn worker[3] -p 3100 -c /app/config/unicorn/development.rb
root        12  2.0  5.3 661540 109188 pts/0   Sl+  11:03   0:02 unicorn worker[4] -p 3100 -c /app/config/unicorn/development.rb
root        13  2.0  5.3 661528 109280 pts/0   Sl+  11:03   0:02 unicorn worker[5] -p 3100 -c /app/config/unicorn/development.rb
root        14  2.0  5.3 661548 109200 pts/0   Sl+  11:03   0:02 unicorn worker[6] -p 3100 -c /app/config/unicorn/development.rb
root        15  2.0  5.3 661544 109188 pts/0   Sl+  11:03   0:02 unicorn worker[7] -p 3100 -c /app/config/unicorn/development.rb
root       128  0.0  0.0   4840   856 pts/1    S+   11:05   0:00 grep unicorn
root@06b4da6d0c07:/app# kill -TERM 1

3. OKレスポンスが返ってくることとlogが出ていることを確認する

unicorn.stdout.log

Unicorn worker intercepting TERM and doing nothing.
Unicorn master intercepting TERM and sending myself QUIT instead