諸行無常

IT色々お勉強中のブログ

Capistranoでstage環境のプロセスを起動停止する方法

ステージング環境に直接入ってコマンド打っても起動せぇへん

bundle exec unicorn -c /var/www/hogehoge/current/config/unicorn/stage.rb -E deployment -D

停止はできるっぽい

kill -QUIT `cat /var/www/hogehoge/current/tmp/pids/unicorn.pid`

入らんでも外からできるんちゃう?exitしてから

bundle exec cap stage unicorn:start

でけた、停止は

bundle exec cap stage unicorn:stop

sidekiqの場合はこれでおk

bundle exec cap stage sidekiq:start

CloudWatchでEC2を監視

標準だけだと足り無いのでカスタム用メトリックスを作成

[hoge@ip-2342-234 cloudwatch]$ ls
credential  custom_metrics.sh  http_status_check.sh
#!/bin/bash

export JAVA_HOME=/usr/lib/jvm/jre
export AWS_CLOUDWATCH_HOME=/opt/aws/apitools/mon
export EC2_REGION=ap-northeast-1
export AWS_CREDENTIAL_FILE=/home/deployer/cloudwatch/credential
instanceid=i-6786876768 # EC-2メニューの「Instances」から該当サーバのInstanceIDを取得して記述

# http status check
status=`/home/deployer/cloudwatch/http_status_check.sh https://hogehoge.work` # 監視したいurlを記述
if [ $status -eq 200 ]; then
Fail=0
else
Fail=1
fi
/opt/aws/bin/mon-put-data --metric-name "Http Status fail" --namespace "Custom Metrix" --dimensions "InstanceId=$instanceid" --value "$Fail" --unit "Count"

# memory check
memtotal=`free -m | grep 'Mem' | tr -s ' ' | cut -d ' ' -f 2`
memfree=`free -m | grep 'buffers/cache' | tr -s ' ' | cut -d ' ' -f 4`
let "memused=100-memfree*100/memtotal"
/opt/aws/bin/mon-put-data --metric-name "FreeMemoryMBytes" --namespace "Custom Metrix" --dimensions "InstanceId=$instanceid" --value "$memfree" --unit "Megabytes"
/opt/aws/bin/mon-put-data --metric-name "UsedMemoryPercent" --namespace "Custom Metrix" --dimensions "InstanceId=$instanceid" --value "$memused" --unit "Percent"

# sidekiq check
sidekiq=`ps aux | grep sidekiq | grep -v grep | wc -l`

if [ "$sidekiq" -gt "0" ]; then
 SidekiqProcesses=1
else
 SidekiqProcesses=0
fi
/opt/aws/bin/mon-put-data --metric-name "Sidekiq Processes" --namespace "Custom Metrix" --dimensions "InstanceId=$instanceid" --value "$SidekiqProcesses" --unit "Count"

# redis check
redis=`ps cax | grep redis | wc -l`
if [ "$redis" -gt "0" ]; then
 RedisProcesses=1
else
 RedisProcesses=0
fi
/opt/aws/bin/mon-put-data --metric-name "Redis Processes" --namespace "Custom Metrix" --dimensions "InstanceId=$instanceid" --value "$RedisProcesses" --unit "Count"

# nginx check
nginx=`ps cax | grep nginx | wc -l`

if [ "$nginx" -gt "0" ]; then
 NginxProcesses=1
else
 NginxProcesses=0
fi
/opt/aws/bin/mon-put-data --metric-name "Nginx Processes" --namespace "Custom Metrix" --dimensions "InstanceId=$instanceid" --value "$NginxProcesses" --unit "Count"

# unicorn check
unicorn=`ps -ef | grep unicorn | grep -v grep | wc -l`

if [ "$unicorn" -gt "0" ]; then
 UnicornProcesses=1
else
 UnicornProcesses=0
fi
/opt/aws/bin/mon-put-data --metric-name "Unicorn Processes" --namespace "Custom Metrix" --dimensions "InstanceId=$instanceid" --value "$UnicornProcesses" --unit "Count"

# cron check
cron=`ps cax | grep cron | wc -l`

if [ "$cron" -gt "0" ]; then
 CronProcesses=1
else
 CronProcesses=0
fi
/opt/aws/bin/mon-put-data --metric-name "Cron Processes" --namespace "Custom Metrix" --dimensions "InstanceId=$instanceid" --value "$CronProcesses" --unit "Count"

# diskspace check
path='/'
freespace=`df --local --block-size=1M $path | grep $path | tr -s ' ' | cut -d ' ' -f 4`
usedpercent=`df --local $path | grep $path | tr -s ' ' | cut -d ' ' -f 5 | grep -o "[0-9]*"`

mon-put-data --metric-name "FreeSpaceMBytes" --namespace "Custom Metrix" --dimensions "InstanceId=$instanceid,Path=$path" --value "$freespace" --unit "Megabytes"
mon-put-data --metric-name "UsedSpacePercent" --namespace "Custom Metrix" --dimensions "InstanceId=$instanceid,Path=$path" --value "$usedpercent" --unit "Percent"

crontab -eでクーロンの設定

MAILTO=dev@creww.me
*/5 * * * * /home/deployer/cloudwatch/custom_metrics.sh

cap stage deployを実行するとPermission denied (publickey)というエラー

cap stage deployを実行するとエラーになる

  [git][* hoge-hoge-hoge]:~/projects/hoge/ bundle exec cap stage deploy
  00:00 git:wrapper
        01 mkdir -p /tmp/hoge/
      ✔ 01 deployer@hoge.poge.me 0.226s
        Uploading /tmp/hoge/git-ssh.sh 100.0%
        02 chmod +rx /tmp/hoge/git-ssh.sh
      ✔ 02 deployer@hoge.poge.me 0.025s
  00:00 git:check
        01 git ls-remote --heads git@github.com:poge/hoge.git
        01 Permission denied (publickey).
        01 fatal: Could not read from remote repository.
        01
        01 Please make sure you have the correct access rights
        01 and the repository exists.
  (Backtrace restricted to imported tasks)
  cap aborted!
  SSHKit::Runner::ExecuteError: Exception while executing as deployer@hoge.poge.me: git exit status: 128
  git stdout: Nothing written
  git stderr: Permission denied (publickey).
  fatal: Could not read from remote repository.

  Please make sure you have the correct access rights
  and the repository exists.

  SSHKit::Command::Failed: git exit status: 128
  git stdout: Nothing written
  git stderr: Permission denied (publickey).
  fatal: Could not read from remote repository.

  Please make sure you have the correct access rights
  and the repository exists.

  Tasks: TOP => git:check
  (See full trace by running task with --trace)
  The deploy has failed with an error: Exception while executing as deployer@hoge.poge.me: git exit status: 128
  git stdout: Nothing written
  git stderr: Permission denied (publickey).
  fatal: Could not read from remote repository.

  Please make sure you have the correct access rights
  and the repository exists.

  ** DEPLOY FAILED
  ** Refer to log/capistrano.log for details. Here are the last 20 lines:

  Please make sure you have the correct access rights
  and the repository exists.
    INFO ---------------------------------------------------------------------------
    INFO START 2016-08-24 19:39:34 +0900 cap stage deploy
    INFO ---------------------------------------------------------------------------
    INFO [90de94b6] Running /usr/bin/env mkdir -p /tmp/hoge/ as deployer@hoge.poge.me
   DEBUG [90de94b6] Command: /usr/bin/env mkdir -p /tmp/hoge/
    INFO [90de94b6] Finished in 0.226 seconds with exit status 0 (successful).
   DEBUG Uploading /tmp/hoge/git-ssh.sh 0.0%
    INFO Uploading /tmp/hoge/git-ssh.sh 100.0%
    INFO [6247b79d] Running /usr/bin/env chmod +rx /tmp/hoge/git-ssh.sh as deployer@hoge.poge.me
   DEBUG [6247b79d] Command: /usr/bin/env chmod +rx /tmp/hoge/git-ssh.sh
    INFO [6247b79d] Finished in 0.025 seconds with exit status 0 (successful).
    INFO [a7f4afba] Running /usr/bin/env git ls-remote --heads git@github.com:poge/hoge.git as deployer@hoge.poge.me
   DEBUG [a7f4afba] Command: ( export GIT_ASKPASS="/bin/echo" GIT_SSH="/tmp/hoge/git-ssh.sh" ; /usr/bin/env git ls-remote --heads git@github.com:poge/hoge.git )
   DEBUG [a7f4afba]     Permission denied (publickey).
   DEBUG [a7f4afba]     fatal: Could not read from remote repository.

  Please make sure you have the correct access rights
  and the repository exists.

エラー解消方法 公開鍵をssh-addする

ssh-add -l
The agent has no identities.
ssh-add ~/.ssh/id_rsa
Identity added: /Users/hoge/.ssh/id_rsa (/Users/hoge/.ssh/id_rsa)
ssh-add -l
2048 23i4u2oi:5c:21:da:23423498:be:00:58:629387:cd:12:18:18:7c:14 /Users/hoge/.ssh/id_rsa (RSA)

#永続的にaddする方法
ssh-add -K ~/.ssh/id_git_rsa

rails sidekiqでのエラーハンドリング

sidekiqでのエラーハンドリング config/initializers/sidekiq.rb

Sidekiq.configure_server do |config|
  config.redis = { url: 'redis://127.0.0.1:3333' }
end

config.redisの下に以下を追加

  config.error_handlers << Proc.new { |ex, ctx_hash| ExceptionNotifier.notify_exception(ex) }

rails enumの表示を共通化

viewでそれぞれ書くのがめんどくさかったんでmodelに定義 human_hoge

  ['hoge', 'hoge2', 'hoge3'].each do |method|
    define_method "human_#{method}" do
      I18n.t("activerecord.attributes.applicant.#{method.pluralize}").fetch(send(method).to_sym)
    end
  end

クラスメソッドバージョン

  ['hoge', 'hoge2', 'hoge3'].each do |method|
    define_singleton_method "collection_#{method}" do
      send(method.pluralize).map{|k,v| [I18n.t("activerecord.attributes.applicant.#{method.pluralize}.#{k}"),k]}.to_h
    end
  end

git でhttpsからgit接続に変更

公開鍵作成

cd ~/.ssh/
ssh-keygen -t rsa

クリップボードにコピー

pbcopy < ~/.ssh/id_rsa.pub

github側で登録 https://github.com/settings/ssh

app/.git/configを書き換え

[remote "origin"]
  url = git@github.com:hoge/hoge.git

毎回パスワード聞かれないように

ssh-add ~/.ssh/id_rsa