さくらVPSのRailsアプリをバージョンアップ

さくらの VPS で動かしている Rails アプリをバージョンアップした、その記録。
今回のバージョンアップでは、Rails のバージョンアップしないけど、データベースの変更をするので若干緊張しながらやった。

まずは、アプリを停止する。
で、万が一のためにデータベースのバックアップ。

[takatoh@tk2-254-36564 ~]$ mysqldump -u lathercraft -p lathercraft_production > lcp-20180502.sql

次に、アプリのディレクトリに移動して git fetchgit merge origin/master

[takatoh@tk2-254-36564 ~]$ cd /var/www/lathercraft
[takatoh@tk2-254-36564 lathercraft]$ sudo git fetch
Password: 
remote: Counting objects: 126, done.
remote: Compressing objects: 100% (126/126), done.
remote: Total 126 (delta 95), reused 0 (delta 0)
Receiving objects: 100% (126/126), 11.91 KiB | 6 KiB/s, done.
Resolving deltas: 100% (95/95), completed with 21 local objects.
From https://bitbucket.org/takatoh/lathercraft
   14f1281..7aecdc3  master     -> origin/master
 * [new branch]      support-release-datetime -> origin/support-release-datetime
 * [new tag]         v2.0.1     -> v2.0.1
From https://bitbucket.org/takatoh/lathercraft
 * [new tag]         v2.0.0     -> v2.0.0
[takatoh@tk2-254-36564 lathercraft]$ sudo git merge origin/master
Auto-merging .gitignore
Auto-merging db/schema.rb
CONFLICT (content): Merge conflict in db/schema.rb
Automatic merge failed; fix conflicts and then commit the result.

あれ、db/schema.rb がコンフリクトした?なんでだ?
中身を見てみると、文字列のカラムに limit:255 がついている。このファイルはデータベースをマイグレートすれば更新されるはずなので、元に戻しておく。

[takatoh@tk2-254-36564 lathercraft]$ sudo vim db/schema.rb

修正が済んだら commit

[takatoh@tk2-254-36564 lathercraft]$ sudo git add db/schema.rb
[takatoh@tk2-254-36564 lathercraft]$ sudo git commit -m "merge branch origin/master."

さて、いよいよデータベースのマイグレーション。

[takatoh@tk2-254-36564 lathercraft]$ sudo -s
[root@tk2-254-36564 lathercraft]# export SECRET_KEY_BASE=bundle exec rake secret
[root@tk2-254-36564 lathercraft]# bundle exec rake db:migrate RAILS_ENV=production
DEPRECATION WARNING: The configuration option `config.serve_static_assets` has been renamed to `config.serve_static_files` to clarify its role (it merely enables serving everything in the `public` folder and is unrelated to the asset pipeline). The `serve_static_assets` alias will be removed in Rails 5.0. Please migrate your configuration files accordingly. (called from block in  at /var/www/lathercraft/config/environments/production.rb:23)
== 20180430070208 AddReleaseDatetimeToItems: migrating ========================
-- add_column(:items, :release_datetime, :datetime)
   -> 1.5631s
== 20180430070208 AddReleaseDatetimeToItems: migrated (1.5635s) ===============

なんか警告が出てるけどまあいいや。次に進もう。

アプリを production 環境で立ち上げてみる。

[root@tk2-254-36564 lathercraft]# export SECRET_KEY_BASE=bundle exec rake secret
[root@tk2-254-36564 lathercraft]# bundle exec rake db:migrate RAILS_ENV=production

無事、立ち上がった。けど、あるページではエラーになってしまった。開発環境で修正して本番環境に反映すると、直った。多分これで大丈夫。

最後に本番用に立ち上げて完了。

[追記]

マイグレーションのところで出た警告だけど、ググってみたら config.serve_static_assets という設定項目が config.serve_static_files に名前変更されている、ということが分かった。なので、その通りに修正して完了。

SinatraアプリをCentOSで動かす(2)

前のエントリで、単純に動かすことには成功したので、今度はデーモンとして動かすことにチャレンジする。一部内容が重複するけど御勘弁。

まずは専用のユーザーを作る。

[takatoh@aybesea ~]$ sudo useradd sombrero
[sudo] takatoh のパスワード:
[takatoh@aybesea ~]$ sudo passwd sombrero
ユーザー sombrero のパスワードを変更。
新しいパスワード:
よくないパスワード: このパスワードには一部に何らかの形でユーザー名が含まれています。
新しいパスワードを再入力してください:
passwd: すべての認証トークンが正しく更新できました。
[takatoh@aybesea ~]$ sudo usermod -G wheel sombrero
[takatoh@aybesea ~]$ sudo usermod -aG staff sombrero

よくないパスワードと言われてるけど無視。
ここで新しいユーザーでログインし直す。

アプリの clone から セットアップまで。

[sombrero@aybesea ~]$ git clone https://github.com/takatoh/sombrero.git
[sombrero@aybesea ~]$ cd sombrero

と思ったら bundler のインストールでつまづいた。

[sombrero@aybesea sombrero]$ gem install bundler
ERROR:  While executing gem ... (Gem::FilePermissionError)
    You don't have write permissions for the /usr/local/rbenv/versions/2.4.3/lib/ruby/gems/2.4.0 directory.

指摘されているディレクトリのパーミッションを見てみると、bill のものになっている。

[sombrero@aybesea sombrero]$ ls -l /usr/local/rbenv/versions/2.4.3/lib/ruby/gems
合計 0
drwxr-xr-x. 8 bill bill 100  1月  2 10:11 2.4.0

これは bill で rbenv global したせいだろうけど、このパーミッション設定は良くないよな。
変えてしまえ。

[sombrero@aybesea sombrero]$ sudo chgrp -R staff /usr/local/rbenv/versions/2.4.3
[sombrero@aybesea sombrero]$ sudo chmod -R 775 /usr/local/rbenv/versions/2.4.3

これでどうか。

[sombrero@aybesea sombrero]$ gem install bundler
Fetching: bundler-1.16.1.gem (100%)
Successfully installed bundler-1.16.1
Parsing documentation for bundler-1.16.1
Installing ri documentation for bundler-1.16.1
Done installing documentation for bundler after 5 seconds
1 gem installed

OK。つづき。

[sombrero@aybesea sombrero]$ bundle install
[sombrero@aybesea sombrero]$ cp config.yaml.example config.yaml
[sombrero@aybesea sombrero]$ rake setup

ここでいったん起動してみる。

[sombrero@aybesea sombrero]$ bundle exec rackup config.ru

OK。

unicorn のインストール。

[sombrero@aybesea sombrero]$ bundle exec gem install unicorn

unicorn の設定ファイル unicorn.conf を書く。

listen "9000"
worker_processes 2
pid "./unicorn.pid"
stderr_path "./unicorn.log"
stdout_path "./unicorn.log"

もう一度、今度は unicorn で起動。

[sombrero@aybesea sombrero]$ bundle exec unicorn -c unicorn.conf
bundler: failed to load command: unicorn (/usr/local/rbenv/versions/2.4.3/bin/unicorn)
Gem::Exception: can't find executable unicorn for gem unicorn. unicorn is not currently included in the bundle, perhaps you meant to add it to your Gemfile?
  /usr/local/rbenv/versions/2.4.3/lib/ruby/gems/2.4.0/gems/bundler-1.16.1/lib/bundler/rubygems_integration.rb:458:in `block in replace_bin_path'
  /usr/local/rbenv/versions/2.4.3/lib/ruby/gems/2.4.0/gems/bundler-1.16.1/lib/bundler/rubygems_integration.rb:478:in `block in replace_bin_path'
  /usr/local/rbenv/versions/2.4.3/bin/unicorn:23:in `'

あれ?Gemfile に書き足さなきゃいけないのか。じゃ、そうしてからもう一度。

[sombrero@aybesea sombrero]$ bundle update
[sombrero@aybesea sombrero]$ bundle exec unicorn -c unicorn.conf

今度はOK。

UNIT ファイルを書く。

[sombrero@aybesea sombrero]$ sudo vim /etc/systemd/system/sombrero.service
[Unit]
Description=Sombrero service

[Service]
Type=forking
PIDFile=/home/sombrero/sombrero/unicorn.pid
ExecStart=/usr/local/rbenv/shims/bundle exec unicorn -c unicorn.conf -D
ExecReload=/bin/kill -HUP $MAINPID
ExecStop=/bin/kill -QUIT $MAINPID
WorkingDirectory=/home/sombrero/sombrero
User=sombrero
Group=sombrero

[Install]
WantedBy=multi-user.target

これでいってみよう。

[sombrero@aybesea sombrero]$ sudo systemctl start sombrero

ブラウザで確認……OK!!!!!
start したり stop したりしてもちゃんと動いていることが確認出来た。

最後は、自動起動するようにして、外部からもアクセスできるようにポートを開ければ完了。

[sombrero@aybesea sombrero]$ sudo systemctl enable sombrero
Created symlink from /etc/systemd/system/multi-user.target.wants/sombrero.service to /etc/systemd/system/sombrero.service.
[sombrero@aybesea sombrero]$ sudo firewall-cmd --add-port=9000/tcp --zone=public --permanent
success

これでマシンを再起動してみよう。

他のマシンから確認。ちゃんと動作していることが確認出来た。これで完了。

SinatraアプリをCentOSで動かす

ImageMagick を使うのでインストール。

[takatoh@aybesea ~]$ sudo yum install ImageMagick

GitHub から clone。

[takatoh@aybesea ~]$ cd w
[takatoh@aybesea w]$ git clone [email protected]:takatoh/sombrero.git

依存するライブラリをインストール。bundler はインストール済み。

[takatoh@aybesea w]$ cd sombrero
[takatoh@aybesea sombrero]$ bundle install

設定ファイルを作る。実験なのでデフォルトのまま。

[takatoh@aybesea sombrero]$ cp config.yaml.example config.yaml

アプリのセットアップ。データベースや必要なディレクトリなど。

[takatoh@aybesea sombrero]$ rake setup

これで一応の準備は済んだはず。rackup してみる。

[takatoh@aybesea sombrero]$ bundle exec rackup config.ru

これで localhost:9292 で待ち受ける。ブラウザで確認したら OK だった。

外部からアクセスするにはポートを開けてやる必要がある。

[takatoh@aybesea sombrero]$ sudo firewall-cmd --add-port=9292/tcp --zone=public --permanent
[sudo] takatoh のパスワード:
success

さらにアプリを起動するときにも -o 0.0.0.0 オプションが必要。これは Sinatra の仕様。

[takatoh@aybesea sombrero]$ bundle exec rackup -o 0.0.0.0 config.ru

これでアクセスできるはず……できないな。
firewalld をリスタートさせてみる。

[takatoh@aybesea sombrero]$ sudo systemctl restart firewalld
[sudo] takatoh のパスワード:
[takatoh@aybesea sombrero]$ sudo firewall-cmd --list-ports
9292/tcp

今度は大丈夫。外部からもアクセスできて、期待どおりに動作していることが確認出来た。

rbenvを使ってRubyをインストールする(ユーザーローカル)→成功

ユーザーローカルにインストールする。まずは rbenv のインストール。

[takatoh@aybesea ~]$ git clone https://github.com/sstephenson/rbenv.git .rbenv

.bash_profile につぎの行を追記。

export RBENV_ROOT=$HOME/.rbenv
export PATH=$RBENV_ROOT/bin:$PATH
eval "$(rbenv init -)"

設定を読み直す。

[takatoh@aybesea ~]$ source .bash_profile

ruby-build をインストール。

[takatoh@aybesea ~]$ git clone git://github.com/sstephenson/ruby-build.git .rbenv/plugins/ruby-build
[takatoh@aybesea ~]$ cd .rbenv/plugins/ruby-build
[takatoh@aybesea ruby-build]$ sudo ./install.sh

これでインストールはOKのはず。

[takatoh@aybesea ~]$ rbenv -v
rbenv 1.1.1-28-gb943955

さあ、Ruby 2.5.0 をインストールしよう。

[takatoh@aybesea ~]$ rbenv install 2.5.0
Downloading ruby-2.5.0.tar.bz2...
-> https://cache.ruby-lang.org/pub/ruby/2.5/ruby-2.5.0.tar.bz2
Installing ruby-2.5.0...
Installed ruby-2.5.0 to /home/takatoh/.rbenv/versions/2.5.0

rbenv rehash を実行。

[takatoh@aybesea ~]$ rbenv rehash

グローバルに使用する Ruby を指定。

[takatoh@aybesea ~]$ rbenv global 2.5.0

インストールできているか確認。

[takatoh@aybesea ~]$ ruby -v
ruby 2.5.0p0 (2017-12-25 revision 61468) [x86_64-linux]
[takatoh@aybesea ~]$ which ruby
~/.rbenv/shims/ruby
[takatoh@aybesea ~]$ which gem
~/.rbenv/shims/gem

参考ページ

cf. ruby 2.3.1をCentOS7に導入する。 – Qiita

rbenvを使ってRubyをインストールする(システムワイド)→失敗

CentOS 7 には、標準では Ruby がインストールされてない。なのでインストールするんだけど、今回はせっかくなので rbenv を使ってみることにした。それもユーザー単位ではなくシステムワイドにインストールする。

環境

[takatoh@aybesea ~]$ cat /etc/centos-release
CentOS Linux release 7.4.1708 (Core)

準備

予め依存するパッケージをインストールしておく。git はインストール済み。

[takatoh@aybesea ~]$ sudo yum install gcc gcc-c++ openssl-devel readline-devel

rbenvのインストールと設定

インストール先を /usr/local/rbenv にする。

[takatoh@aybesea ~]$ sudo git clone https://github.com/sstephenson/rbenv.git /usr/local/rbenv

環境変数等の設定。/etc/profile.d の下に rbenv.sh を作って、つぎのようにする。

export RBENV_ROOT="/usr/local/rbenv"
export PATH="${RBENV_ROOT}/bin:${PATH}"
eval "$(rbenv init --no-rehash -)"

rbenv.sh を反映する。

[takatoh@aybesea ~]$ source /etc/profile.d/rbenv.sh
mkdir: ディレクトリ `/usr/local/rbenv/shims' を作成できません: 許可がありません
mkdir: ディレクトリ `/usr/local/rbenv/versions' を作成できません: 許可がありません
[takatoh@aybesea ~]$ sudo source /etc/profile.d/rbenv.sh
sudo: source: コマンドが見つかりません

あれ、困った。ログインし直してみよう。
ログインし直した結果、端末に次のように表示された。

mkdir: ディレクトリ `/usr/local/rbenv/shims' を作成できません: 許可がありません
mkdir: ディレクトリ `/usr/local/rbenv/versions' を作成できません: 許可がありません

先にディレクトリを作ってやったらどうだろう。

[takatoh@aybesea ~]$ sudo mkdir /usr/local/rbenv/shims
[sudo] takatoh のパスワード:
[takatoh@aybesea ~]$ sudo mkdir /usr/local/rbenv/versions
[takatoh@aybesea ~]$ source /etc/profile.d/rbenv.sh

ruby-buildのインストール

[takatoh@aybesea ~]$ sudo mkdir /usr/local/rbenv/plugins
[takatoh@aybesea ~]$ cd /usr/local/rbenv/plugins
[takatoh@aybesea plugins]$ sudo git clone https://github.com/sstephenson/ruby-build.git ruby-build

install.sh を実行。

[takatoh@aybesea plugins]$ cd ruby-build
[takatoh@aybesea ruby-build]$ sudo ./install.sh

Rubyのインストール

さて、これで準備は整ったはずだ。Ruby をインストールしよう。インストールできる Ruby のバージョンは rbenv install --list コマンドで見ることができる。

[takatoh@aybesea ~]$ rbenv install --list

せっかくなので、リリースされたばかりの 2.5.0 をインストールしよう。

[takatoh@aybesea ~]$ rbenv install 2.5.0
Downloading ruby-2.5.0.tar.bz2...
-> https://cache.ruby-lang.org/pub/ruby/2.5/ruby-2.5.0.tar.bz2
Installing ruby-2.5.0...
mkdir: ディレクトリ `/usr/local/rbenv/versions/2.5.0' を作成できません: 許可がありません

BUILD FAILED (CentOS Linux 7 using ruby-build 20171226)

Inspect or clean up the working tree at /tmp/ruby-build.20171231060736.25143
Results logged to /tmp/ruby-build.20171231060736.25143.log

Last 10 log lines:
/tmp/ruby-build.20171231060736.25143 ~
/tmp/ruby-build.20171231060736.25143/ruby-2.5.0 /tmp/ruby-build.20171231060736.25143 ~
[takatoh@aybesea ~]$ sudo rbenv install 2.5.0
[sudo] takatoh のパスワード:
sudo: rbenv: コマンドが見つかりません

あれ、ダメか。さっきの設定が root ユーザーには読み込まれてない様だ。かと言って sudo しないと書き込めないし。フルパスで指定してみるか。

[takatoh@aybesea ~]$ sudo /usr/local/rbenv/bin/rbenv install 2.5.0
rbenv: no such command `install'

ダメかーー!
設定がうまくいってないのかな。参考ページの通りにやってるんだけど。
あきらめてユーザーローカルに変更するか。

参考ページ

cf. CentOS7へのrbenvを用いたrubyの導入(システムワイド版) – Typo

middleman deplyが動いてくれない

www.panicblanket.com にホームページを作った。とはいっても2ページしか無いんだけど。
作成には Ruby 製静的サイトジェネレータの Middleman を使った。Middleman の使い方はググればいっぱい出てくるのでここでは省略。とりあえず日本語の公式サイトへのリンクだけ載せておこう。

 cf. Middleman

基本的にはこの公式サイトの説明のとおりにやっていけば、サイトを作れる。というか作れた。
問題はサーバへのデプロイだ。デプロイは、要するにサーバの然るべきディレクトリにファイルをコピーすればいいので、FTP でも何でもいいんだけど、ファイル数が多くなればそれだけ面倒になる。で、公式サイトでは middleman-deploy というプラグインを使うといい、みたいなことが書いてあったのでそうすることにした。
ところがこれが罠だったわけだ。使い方は簡単、Gemfile に middleman-deploy を追加して、bundle install --path vendor/bundle コマンドでインストール。config.rb にデプロイのための設定を書き足して(今回は FTP を使うことにした)、bundle exec middleman deploy を実行するだけ。
で、実行したところこんなエラーが出た。

takatoh@envelopes $ bundle exec middleman deploy
/home/takatoh/w/www.panicblanket.com/vendor/bundle/ruby/2.3.0/gems/middleman-core-4.2.1/lib/middleman-core/extensions.rb:96:in `load': Tried to activate old-style extension: deploy. They are no longer supported. (RuntimeError)
	from /home/takatoh/w/www.panicblanket.com/vendor/bundle/ruby/2.3.0/gems/middleman-core-4.2.1/lib/middleman-core/extensions.rb:127:in `block in load_settings'
	from /home/takatoh/w/www.panicblanket.com/vendor/bundle/ruby/2.3.0/gems/middleman-core-4.2.1/lib/middleman-core/extensions.rb:125:in `each'
	from /home/takatoh/w/www.panicblanket.com/vendor/bundle/ruby/2.3.0/gems/middleman-core-4.2.1/lib/middleman-core/extensions.rb:125:in `load_settings'
	from /home/takatoh/w/www.panicblanket.com/vendor/bundle/ruby/2.3.0/gems/middleman-core-4.2.1/lib/middleman-core/extension_manager.rb:12:in `initialize'
	from /home/takatoh/w/www.panicblanket.com/vendor/bundle/ruby/2.3.0/gems/middleman-core-4.2.1/lib/middleman-core/application.rb:263:in `new'
	from /home/takatoh/w/www.panicblanket.com/vendor/bundle/ruby/2.3.0/gems/middleman-core-4.2.1/lib/middleman-core/application.rb:263:in `initialize'
	from /home/takatoh/w/www.panicblanket.com/vendor/bundle/ruby/2.3.0/gems/middleman-cli-4.2.1/bin/middleman:49:in `new'
	from /home/takatoh/w/www.panicblanket.com/vendor/bundle/ruby/2.3.0/gems/middleman-cli-4.2.1/bin/middleman:49:in `'
	from /home/takatoh/w/www.panicblanket.com/vendor/bundle/ruby/2.3.0/bin/middleman:23:in `load'
	from /home/takatoh/w/www.panicblanket.com/vendor/bundle/ruby/2.3.0/bin/middleman:23:in `
'

長いけど、最初のところに、「Tried to activate old-style extension: deploy. They are no longer supported. (RuntimeError)」って書いてある。deploy は古いスタイルの拡張で、すでにサポートされていない、らしい。GitHub の middleman-deploy のページを見てみると、インストールしたバージョン 1.0 がリリースされたのが 2014 年。これ以降新しいバージョンのリリースがない。そりゃ古いよなぁ。でも公式サイトに書いてあるんだぜ?どうしろってんだ。

結局、FTP でファイルをひとつずつアップした。スタイルシートを含めても3ファイルしか無いので、大したことはなかったけど、これからファイル数が増えたらなんか考えなきゃいけない。みんなどうしてるんだろう?

さくらのVPSプラン乗り換え計画(11)

Rails アプリを unicorn で動かす。

unicornのインストールと設定

Gemfile に unicorn を追加。

gem 'unicorn'

インストール。

[root@tk2-254-36564 lathercraft]# bundle install --path vendor/bundle

unicorn の設定ファイルはつぎのようにした。

worker_processes 2
working_directory "/var/www/lathercraft"

listen "/var/run/unicorn/unicorn_lathercraft.sock"
pid "/var/run/unicorn/unicorn_lathercraft.pid"

preload_app true

timeout 1200

/var/run/unicorn ディレクトリを作成。

[root@tk2-254-36564 lathercraft]# mkdir /var/run/unicorn

Nginxの設定

upstream unicorn-lathercraft {
    server unix:/var/run/unicorn/unicorn_lathercraft.sock;
}

server {
    # port
    listen 80;

    # server name
    server_name www2.lathercraft.net;

    # document root
    root /var/www/lathercraft/public;

    # index
    #index index.php index.html index.htm;

    # log files
    access_log /var/log/nginx/www.lathercraft.net/access.log main;
    error_log /var/log/nginx/www.lathercraft.net/error.log warn;

    keepalive_timeout 6000;
    proxy_connect_timeout 6000;
    proxy_read_timeout 6000;
    proxy_send_timeout 6000;

    client_max_body_size 8192M;

    location /kel-mirrors {
        root /var/www/lathercraft/recent/;
        rewrite '^/kel-mirrors(.*)$' $1;
        break;
    }

    location / {
        root /var/www/lathercraft;

        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_pass http://unicorn-lathercraft;
    }
}

ログファイル用のディレクトリを作成。

[root@tk2-254-36564 lathercraft]# mkdir /var/log/nginx/www.lathercraft.net

Nginxの再起動とunicornの起動

Nginx を再起動。

[root@tk2-254-36564 lathercraft]# service nginx restart
Stopping nginx:                                            [  OK  ]
Starting nginx:                                            [  OK  ]

unicorn を起動。

[root@tk2-254-36564 lathercraft]# export SECRET_KEY_BASE=bundle exec rails secret
[root@tk2-254-36564 lathercraft]# bundle exec unicorn_rails -c unicorn.rb -E production
I, [2017-05-05T11:58:43.619697 #13435]  INFO -- : Refreshing Gem list
DEPRECATION WARNING: The configuration option `config.serve_static_assets` has been renamed to `config.serve_static_files` to clarify its role (it merely enables serving everything in the `public` folder and is unrelated to the asset pipeline). The `serve_static_assets` alias will be removed in Rails 5.0. Please migrate your configuration files accordingly. (called from block in  at /var/www/lathercraft/config/environments/production.rb:23)
I, [2017-05-05T11:58:46.475292 #13435]  INFO -- : listening on addr=/var/run/unicorn/unicorn_lathercraft.sock fd=10
I, [2017-05-05T11:58:46.475781 #13435]  INFO -- : worker=0 spawning...
I, [2017-05-05T11:58:46.479485 #13435]  INFO -- : worker=1 spawning...
I, [2017-05-05T11:58:46.481100 #13438]  INFO -- : worker=0 spawned pid=13438
I, [2017-05-05T11:58:46.481436 #13435]  INFO -- : master process ready
I, [2017-05-05T11:58:46.481630 #13438]  INFO -- : worker=0 ready
I, [2017-05-05T11:58:46.482935 #13441]  INFO -- : worker=1 spawned pid=13441
I, [2017-05-05T11:58:46.483183 #13441]  INFO -- : worker=1 ready

さて、これでいいはず。

名前解決

ちゃんと動いているはずだけど、確認するには www2.lathercraft.net の名前解決化できないといけない。これはさくらインターネットのゾーン編集をする。

……結果、無事動いていることを確認。

unicornの自動起動

最後に、OS起動時に unicorn が自動起動するようにしておく。/etc/init.d/unicorn_lathercraft をつぎのようにした。

#!/bin/bash
#
# unicorn_lathercraft Startup script for unicorn.
#
# chkconfig: - 85 15
# description: lathercraft on unicorn start/stop script.
#

set -e
set -u

export PATH=/usr/local/rvm/rubies/ruby-2.3.3/bin:/usr/local/rvm/gems/ruby-2.3.3/bin:$PATH
export RUBYLIB=/usr/local/rvm/gems/ruby-2.3.3:/usr/local/rvm/gems/ruby-2.3.3@global
export GEM_HOME=/usr/local/rvm/gems/ruby-2.3.3:/usr/local/rvm/gems/ruby-2.3.3@global
export GEM_PATH=/usr/local/rvm/gems/ruby-2.3.3:/usr/local/rvm/gems/ruby-2.3.3@global
#echo `ruby -v`
#echo `which ruby`
APP_NAME=lathercraft
APP_ROOT="/var/www/$APP_NAME"
CNF="$APP_ROOT/unicorn.rb"
PID="/var/run/unicorn/unicorn_lathercraft.pid"
ENV=production
UNICORN_OPTS="-c $CNF -E $ENV -D"
old_pid="$PID.oldbin"

#export SECRET_KEY_BASE=`cd /var/www/lathercraft; bundle exec rake secret`

cd $APP_ROOT || exit 1

sig () {
    test -s "$PID" && kill -$1 `cat $PID`
}
oldsig () {
    test -s $old_pid && kill -$1 `cat $old_pid`
}

case ${1-help} in
start)
sig 0 && echo >&2 "Already running" && exit 0
cd $APP_ROOT
export SECRET_KEY_BASE=`bundle exec rake secret`
bundle exec unicorn_rails $UNICORN_OPTS
;;
stop)
sig QUIT && exit 0
echo >&2 "Not running"
;;
force-stop)
sig TERM && exit 0
echo >&2 "Not running"
;;
restart|reload)
sig HUP && echo reloaded OK && exit 0
echo >&2 "Couldn't reload, starting instead"
unicorn_rails $UNICORN_OPTS
;;
upgrade)
sig USR2 && exit 0
echo >&2 "Couldn't upgrade, starting instead"
unicorn_rails $UNICORN_OPTS
;;
rotate)
sig USR1 && echo rotated logs OK && exit 0
echo >&2 "Couldn't rotate logs" && exit 1
;;
*)
echo >&2 "Usage: $0 <start|stop|restart|upgrade|rotate|force-stop>"
exit 1
;;
esac

これでいいはず。スタートしてみよう。

[root@tk2-254-36564 init.d]# chmod 755 unicorn_lathercraft
[root@tk2-254-36564 init.d]# service unicorn_lathercraft start

OK。
自動起動するように設定。

[root@tk2-254-36564 init.d]# chkconfig unicorn_lathercraft on
[root@tk2-254-36564 init.d]# chkconfig --list unicorn_lathercraft
unicorn_lathercraft	0:off	1:off	2:on	3:on	4:on	5:on	6:off

これで完了。

さくらのVPSプラン乗り換え計画(10)

新しいプランのサーバで Rails アプリが一応動くようになったので、旧プランのサーバからデータを移行する。

まずは mysqldump コマンドで旧プランのデータベースを取り出す。

[takatoh@www2465uo ~]$ mysqldump -u lathercraft -p lathercraft_production > lcp-20170505.sql
[takatoh@www2465uo ~]$ tar czf lcp-20170505.sql.tgz lcp-20170505.sql

ファイルをローカルにダウンロード。

takatoh@envelopes $ scp -P xxxxx [email protected]:lcp-20170505.sql.tgz .
lcp-20170505.sql.tgz                          100%   10MB  10.1MB/s   00:01

ダウンロードしたファイルを新プランのサーバにアップロード。

takatoh@envelopes $ scp -P 60000 lcp-20170505.sql.tgz [email protected]:
lcp-20170505.sql.tgz                          100%   10MB  10.1MB/s   00:01

新プランのサーバにログインして、.tgz ファイルを展開。

takatoh@envelopes $ ssh -p 60000 [email protected]
Last login: Fri May  5 11:06:46 2017 from fntsitm001026.sitm.fnt.ngn.ppp.infoweb.ne.jp

SAKURA Internet [Virtual Private Server SERVICE]

[takatoh@tk2-254-36564 ~]$ ls
lcp-20170505.sql.tgz
[takatoh@tk2-254-36564 ~]$ tar xzf lcp-20170505.sql.tgz
[takatoh@tk2-254-36564 ~]$ ls
lcp-20170505.sql  lcp-20170505.sql.tgz

データベースにリストアする。

[takatoh@tk2-254-36564 ~]$ mysql -u lathercraft -p lathercraft_production < lcp-20170505.sql
Enter password:

アプリを立ち上げて確認。

[root@tk2-254-36564 lathercraft]# export SECRET_KEY_BASE=bundle exec rake secret
[root@tk2-254-36564 lathercraft]# bundle exec rails s -e production -b 0.0.0.0
=> Booting WEBrick
=> Rails 4.2.8 application starting in production on http://0.0.0.0:3000
=> Run `rails server -h` for more startup options
=> Ctrl-C to shutdown server
DEPRECATION WARNING: The configuration option `config.serve_static_assets` has been renamed to `config.serve_static_files` to clarify its role (it merely enables serving everything in the `public` folder and is unrelated to the asset pipeline). The `serve_static_assets` alias will be removed in Rails 5.0. Please migrate your configuration files accordingly. (called from block in  at /var/lathercraft/config/environments/production.rb:23)
[2017-05-05 11:18:51] INFO  WEBrick 1.3.1
[2017-05-05 11:18:51] INFO  ruby 2.3.3 (2016-11-21) [x86_64-linux]
[2017-05-05 11:18:51] INFO  WEBrick::HTTPServer#start: pid=12500 port=3000

ブラウザでも確認出来てOK。

ところでうえで気がついたんだけど、アプリを /var/www/lathercraft 以下に置くつもりが /var/lathercraft 以下においてしまっている。なので移動する。

[root@tk2-254-36564 var]# cp -r -a lathercraft www/lathercraft
[root@tk2-254-36564 var]# cd www/lathercraft
[root@tk2-254-36564 lathercraft]# ls
Gemfile       README.rdoc  app  config     db   log     test  vendor
Gemfile.lock  Rakefile     bin  config.ru  lib  public  tmp

再度アプリを立ち上げて確認。

[root@tk2-254-36564 lathercraft]# bundle exec rails s -e production -b 0.0.0.0

OK。

さくらのVPSプラン乗り換え計画(9)

昨日、MySQL と Ruby のインストールが完了したので、今日は Rails アプリを動作させるところまでが目標。と言っても、現状(旧プランの VPS で)動いているアプリを真似ればいいはず。

development でテスト

いきなり本番でやるのではなくまずはテスト。
/var/www に移動して BitBucket からクローン。

[takatoh@tk2-254-36564 ~]$ cd /var
[takatoh@tk2-254-36564 var]$ sudo mkdir www
[takatoh@tk2-254-36564 var]$ sudo -s
[root@tk2-254-36564 var]# git clone https://[email protected]/takatoh/lathercraft.git

ライブラリのインストール。

[root@tk2-254-36564 lathercraft]# bundle install --path vendor/bundle

設定ファイルを編集。

[root@tk2-254-36564 lathercraft]# cp config/secrets.yml.example config/secrets.yml
[root@tk2-254-36564 lathercraft]# cp config/site_config.yml.example config/site_config.yml
[root@tk2-254-36564 lathercraft]# vi config/site_config.yml

データベースのマイグレーション。

[root@tk2-254-36564 lathercraft]# bundle exec rake db:migrate

とりあえずこれでいいはず。iptables でポート 3000 番を開放して、アプリを立ち上げてみる。

[root@tk2-254-36564 lathercraft]# bundle exec rails s -b 0.0.0.0
=> Booting WEBrick
=> Rails 4.2.8 application starting in development on http://0.0.0.0:3000
=> Run `rails server -h` for more startup options
=> Ctrl-C to shutdown server
[2017-05-05 09:53:11] INFO  WEBrick 1.3.1
[2017-05-05 09:53:11] INFO  ruby 2.3.3 (2016-11-21) [x86_64-linux]
[2017-05-05 09:53:11] INFO  WEBrick::HTTPServer#start: pid=10211 port=3000

OK。うまく動いた。

データベースの下準備

本番では、データベースに Sqlite3 じゃなく MySQL を使うので、データベースユーザを作っておく。

[root@tk2-254-36564 lathercraft]# mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 18
Server version: 5.1.73 Source distribution

Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> CREATE USER 'lathercraft'@'localhost' IDENTIFIED BY 'xxxxxxxx';
Query OK, 0 rows affected (0.00 sec)

mysql> exit
Bye

設定ファイルの編集とデータベースのマイグレーション

本番用に設定ファイルを編集。

[root@tk2-254-36564 lathercraft]# vi config/site_config.yml
[root@tk2-254-36564 lathercraft]# vi config/database.yml

config/database.yml はこうした。

(前略)
production:
adapter: mysql2
encoding: utf8
pool: 5
database: lathercraft_production
username: lathercraft
password: xxxxxxxx
host: localhost

MySQL 用のライブラリがインストールされていないのでインストール。

[root@tk2-254-36564 lathercraft]# gem install mysql2
Fetching: mysql2-0.4.6.gem (100%)
Building native extensions.  This could take a while...
ERROR:  Error installing mysql2:
	ERROR: Failed to build gem native extension.

    current directory: /usr/local/rvm/gems/ruby-2.3.3/gems/mysql2-0.4.6/ext/mysql2
/usr/local/rvm/rubies/ruby-2.3.3/bin/ruby -r ./siteconf20170505-10249-1r6ezbc.rb extconf.rb
checking for rb_absint_size()... yes
checking for rb_absint_singlebit_p()... yes
checking for ruby/thread.h... yes
checking for rb_thread_call_without_gvl() in ruby/thread.h... yes
checking for rb_thread_blocking_region()... no
checking for rb_wait_for_single_fd()... yes
checking for rb_hash_dup()... yes
checking for rb_intern3()... yes
checking for rb_big_cmp()... yes
-----
Using mysql_config at /usr/bin/mysql_config
-----
checking for mysql.h... no
checking for mysql/mysql.h... no
-----
mysql.h is missing. You may need to 'apt-get install libmysqlclient-dev' or 'yum install mysql-devel', and try again.
-----
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:
	--with-opt-dir
	--without-opt-dir
	--with-opt-include
	--without-opt-include=${opt-dir}/include
	--with-opt-lib
	--without-opt-lib=${opt-dir}/lib
	--with-make-prog
	--without-make-prog
	--srcdir=.
	--curdir
	--ruby=/usr/local/rvm/rubies/ruby-2.3.3/bin/$(RUBY_BASE_NAME)
	--with-mysql-dir
	--without-mysql-dir
	--with-mysql-include
	--without-mysql-include=${mysql-dir}/include
	--with-mysql-lib
	--without-mysql-lib=${mysql-dir}/lib
	--with-mysql-config
	--without-mysql-config

To see why this extension failed to compile, please check the mkmf.log which can be found here:

  /usr/local/rvm/gems/ruby-2.3.3/extensions/x86_64-linux/2.3.0/mysql2-0.4.6/mkmf.log

extconf failed, exit code 1

Gem files will remain installed in /usr/local/rvm/gems/ruby-2.3.3/gems/mysql2-0.4.6 for inspection.
Results logged to /usr/local/rvm/gems/ruby-2.3.3/extensions/x86_64-linux/2.3.0/mysql2-0.4.6/gem_make.out

あれ、エラーだ。yum install mysql-devel しろってか。

[root@tk2-254-36564 lathercraft]# yum install mysql-devel

もう一度。

[root@tk2-254-36564 lathercraft]# gem install mysql2
Building native extensions.  This could take a while...
Successfully installed mysql2-0.4.6
Parsing documentation for mysql2-0.4.6
Installing ri documentation for mysql2-0.4.6
Done installing documentation for mysql2 after 1 seconds
1 gem installed

OK。
じゃ、データベースの作成とマイグレーション。

[root@tk2-254-36564 lathercraft]# bundle exec rake db:create RAILS_ENV=production
Specified 'mysql2' for database adapter, but the gem is not loaded. Add `gem 'mysql2'` to your Gemfile (and ensure its version is at the minimum required by ActiveRecord).
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/connection_specification.rb:177:in `rescue in spec'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/connection_specification.rb:174:in `spec'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_handling.rb:50:in `establish_connection'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.8/lib/active_record/tasks/mysql_database_tasks.rb:8:in `establish_connection'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.8/lib/active_record/tasks/mysql_database_tasks.rb:15:in `create'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.8/lib/active_record/tasks/database_tasks.rb:93:in `create'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.8/lib/active_record/tasks/database_tasks.rb:107:in `block in create_current'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.8/lib/active_record/tasks/database_tasks.rb:276:in `block in each_current_configuration'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.8/lib/active_record/tasks/database_tasks.rb:275:in `each'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.8/lib/active_record/tasks/database_tasks.rb:275:in `each_current_configuration'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.8/lib/active_record/tasks/database_tasks.rb:106:in `create_current'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.8/lib/active_record/railties/databases.rake:17:in `block (2 levels) in '
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/lib/rake/task.rb:250:in `block in execute'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/lib/rake/task.rb:250:in `each'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/lib/rake/task.rb:250:in `execute'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/lib/rake/task.rb:194:in `block in invoke_with_call_chain'
/usr/local/rvm/rubies/ruby-2.3.3/lib/ruby/2.3.0/monitor.rb:214:in `mon_synchronize'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/lib/rake/task.rb:187:in `invoke_with_call_chain'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/lib/rake/task.rb:180:in `invoke'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:152:in `invoke_task'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:108:in `block (2 levels) in top_level'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:108:in `each'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:108:in `block in top_level'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:117:in `run_with_threads'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:102:in `top_level'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:80:in `block in run'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:178:in `standard_exception_handling'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:77:in `run'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/exe/rake:27:in `'
/var/lathercraft/vendor/bundle/ruby/2.3.0/bin/rake:23:in `load'
/var/lathercraft/vendor/bundle/ruby/2.3.0/bin/rake:23:in `'
/usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/cli/exec.rb:74:in `load'
/usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/cli/exec.rb:74:in `kernel_load'
/usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/cli/exec.rb:27:in `run'
/usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/cli.rb:335:in `exec'
/usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/vendor/thor/lib/thor/command.rb:27:in `run'
/usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/vendor/thor/lib/thor/invocation.rb:126:in `invoke_command'
/usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/vendor/thor/lib/thor.rb:359:in `dispatch'
/usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/cli.rb:20:in `dispatch'
/usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/vendor/thor/lib/thor/base.rb:440:in `start'
/usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/cli.rb:11:in `start'
/usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/exe/bundle:32:in `block in '
/usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/friendly_errors.rb:121:in `with_friendly_errors'
/usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/exe/bundle:24:in `'
/usr/local/rvm/gems/ruby-2.3.3/bin/bundle:23:in `load'
/usr/local/rvm/gems/ruby-2.3.3/bin/bundle:23:in `

‘ /usr/local/rvm/gems/ruby-2.3.3/bin/ruby_executable_hooks:15:in `eval’ /usr/local/rvm/gems/ruby-2.3.3/bin/ruby_executable_hooks:15:in `
‘ Couldn’t create database for {“adapter”=>”mysql2”, “encoding”=>”utf8”, “pool”=>5, “database”=>”lathercraft_production”, “username”=>”lathercraft”, “password”=>”lathercraft”, “host”=>”localhost”} rake aborted! Gem::LoadError: Specified ‘mysql2’ for database adapter, but the gem is not loaded. Add `gem ‘mysql2’` to your Gemfile (and ensure its version is at the minimum required by ActiveRecord). /var/lathercraft/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/connection_specification.rb:177:in `rescue in spec’ /var/lathercraft/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/connection_specification.rb:174:in `spec’ /var/lathercraft/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_handling.rb:50:in `establish_connection’ /var/lathercraft/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.8/lib/active_record/tasks/database_tasks.rb:109:in `create_current’ /var/lathercraft/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.8/lib/active_record/railties/databases.rake:17:in `block (2 levels) in ‘ /var/lathercraft/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/exe/rake:27:in `’ /usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/cli/exec.rb:74:in `load’ /usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/cli/exec.rb:74:in `kernel_load’ /usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/cli/exec.rb:27:in `run’ /usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/cli.rb:335:in `exec’ /usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/vendor/thor/lib/thor/command.rb:27:in `run’ /usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/vendor/thor/lib/thor/invocation.rb:126:in `invoke_command’ /usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/vendor/thor/lib/thor.rb:359:in `dispatch’ /usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/cli.rb:20:in `dispatch’ /usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/vendor/thor/lib/thor/base.rb:440:in `start’ /usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/cli.rb:11:in `start’ /usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/exe/bundle:32:in `block in ‘ /usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/friendly_errors.rb:121:in `with_friendly_errors’ /usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/exe/bundle:24:in `’ /usr/local/rvm/gems/ruby-2.3.3/bin/bundle:23:in `load’ /usr/local/rvm/gems/ruby-2.3.3/bin/bundle:23:in `
‘ /usr/local/rvm/gems/ruby-2.3.3/bin/ruby_executable_hooks:15:in `eval’ /usr/local/rvm/gems/ruby-2.3.3/bin/ruby_executable_hooks:15:in `
‘ Gem::LoadError: mysql2 is not part of the bundle. Add it to Gemfile. /usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/rubygems_integration.rb:351:in `block (2 levels) in replace_gem’ /var/lathercraft/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/mysql2_adapter.rb:3:in `’ /var/lathercraft/vendor/bundle/ruby/2.3.0/gems/activesupport-4.2.8/lib/active_support/dependencies.rb:274:in `require’ /var/lathercraft/vendor/bundle/ruby/2.3.0/gems/activesupport-4.2.8/lib/active_support/dependencies.rb:274:in `block in require’ /var/lathercraft/vendor/bundle/ruby/2.3.0/gems/activesupport-4.2.8/lib/active_support/dependencies.rb:240:in `load_dependency’ /var/lathercraft/vendor/bundle/ruby/2.3.0/gems/activesupport-4.2.8/lib/active_support/dependencies.rb:274:in `require’ /var/lathercraft/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/connection_specification.rb:175:in `spec’ /var/lathercraft/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_handling.rb:50:in `establish_connection’ /var/lathercraft/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.8/lib/active_record/tasks/database_tasks.rb:109:in `create_current’ /var/lathercraft/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.8/lib/active_record/railties/databases.rake:17:in `block (2 levels) in ‘ /var/lathercraft/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/exe/rake:27:in `’ /usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/cli/exec.rb:74:in `load’ /usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/cli/exec.rb:74:in `kernel_load’ /usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/cli/exec.rb:27:in `run’ /usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/cli.rb:335:in `exec’ /usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/vendor/thor/lib/thor/command.rb:27:in `run’ /usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/vendor/thor/lib/thor/invocation.rb:126:in `invoke_command’ /usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/vendor/thor/lib/thor.rb:359:in `dispatch’ /usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/cli.rb:20:in `dispatch’ /usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/vendor/thor/lib/thor/base.rb:440:in `start’ /usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/cli.rb:11:in `start’ /usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/exe/bundle:32:in `block in ‘ /usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/friendly_errors.rb:121:in `with_friendly_errors’ /usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/exe/bundle:24:in `’ /usr/local/rvm/gems/ruby-2.3.3/bin/bundle:23:in `load’ /usr/local/rvm/gems/ruby-2.3.3/bin/bundle:23:in `
‘ /usr/local/rvm/gems/ruby-2.3.3/bin/ruby_executable_hooks:15:in `eval’ /usr/local/rvm/gems/ruby-2.3.3/bin/ruby_executable_hooks:15:in `
‘ Tasks: TOP => db:create (See full trace by running task with –trace)
あー、mysql2 を Gemfile に書いておかなきゃダメなのか。

[root@tk2-254-36564 lathercraft]# vi Gemfile
[root@tk2-254-36564 lathercraft]# bundle install --path vendor/bundle

これでどうだ。

[root@tk2-254-36564 lathercraft]# bundle exec rake db:create RAILS_ENV=production
Mysql2::Error: Access denied for user 'lathercraft'@'localhost' to database 'lathercraft_production': CREATE DATABASE `lathercraft_production` DEFAULT CHARACTER SET `utf8` COLLATE `utf8_unicode_ci`
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/mysql2-0.4.6/lib/mysql2/client.rb:120:in `_query'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/mysql2-0.4.6/lib/mysql2/client.rb:120:in `block in query'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/mysql2-0.4.6/lib/mysql2/client.rb:119:in `handle_interrupt'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/mysql2-0.4.6/lib/mysql2/client.rb:119:in `query'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:309:in `block in execute'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/abstract_adapter.rb:484:in `block in log'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/activesupport-4.2.8/lib/active_support/notifications/instrumenter.rb:20:in `instrument'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/abstract_adapter.rb:478:in `log'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:309:in `execute'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/mysql2_adapter.rb:225:in `execute'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:377:in `create_database'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.8/lib/active_record/tasks/mysql_database_tasks.rb:16:in `create'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.8/lib/active_record/tasks/database_tasks.rb:93:in `create'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.8/lib/active_record/tasks/database_tasks.rb:107:in `block in create_current'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.8/lib/active_record/tasks/database_tasks.rb:276:in `block in each_current_configuration'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.8/lib/active_record/tasks/database_tasks.rb:275:in `each'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.8/lib/active_record/tasks/database_tasks.rb:275:in `each_current_configuration'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.8/lib/active_record/tasks/database_tasks.rb:106:in `create_current'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.8/lib/active_record/railties/databases.rake:17:in `block (2 levels) in '
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/lib/rake/task.rb:250:in `block in execute'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/lib/rake/task.rb:250:in `each'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/lib/rake/task.rb:250:in `execute'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/lib/rake/task.rb:194:in `block in invoke_with_call_chain'
/usr/local/rvm/rubies/ruby-2.3.3/lib/ruby/2.3.0/monitor.rb:214:in `mon_synchronize'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/lib/rake/task.rb:187:in `invoke_with_call_chain'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/lib/rake/task.rb:180:in `invoke'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:152:in `invoke_task'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:108:in `block (2 levels) in top_level'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:108:in `each'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:108:in `block in top_level'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:117:in `run_with_threads'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:102:in `top_level'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:80:in `block in run'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:178:in `standard_exception_handling'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:77:in `run'
/var/lathercraft/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/exe/rake:27:in `'
/var/lathercraft/vendor/bundle/ruby/2.3.0/bin/rake:23:in `load'
/var/lathercraft/vendor/bundle/ruby/2.3.0/bin/rake:23:in `'
/usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/cli/exec.rb:74:in `load'
/usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/cli/exec.rb:74:in `kernel_load'
/usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/cli/exec.rb:27:in `run'
/usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/cli.rb:335:in `exec'
/usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/vendor/thor/lib/thor/command.rb:27:in `run'
/usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/vendor/thor/lib/thor/invocation.rb:126:in `invoke_command'
/usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/vendor/thor/lib/thor.rb:359:in `dispatch'
/usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/cli.rb:20:in `dispatch'
/usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/vendor/thor/lib/thor/base.rb:440:in `start'
/usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/cli.rb:11:in `start'
/usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/exe/bundle:32:in `block in '
/usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/lib/bundler/friendly_errors.rb:121:in `with_friendly_errors'
/usr/local/rvm/gems/ruby-2.3.3/gems/bundler-1.14.6/exe/bundle:24:in `'
/usr/local/rvm/gems/ruby-2.3.3/bin/bundle:23:in `load'
/usr/local/rvm/gems/ruby-2.3.3/bin/bundle:23:in `

‘ /usr/local/rvm/gems/ruby-2.3.3/bin/ruby_executable_hooks:15:in `eval’ /usr/local/rvm/gems/ruby-2.3.3/bin/ruby_executable_hooks:15:in `
‘ Couldn’t create database for {“adapter”=>”mysql2”, “encoding”=>”utf8”, “pool”=>5, “database”=>”lathercraft_production”, “username”=>”lathercraft”, “password”=>”lathercraft”, “host”=>”localhost”}
ダメだ。なんでだ……あ、データベースユーザに権限がないからか?

[root@tk2-254-36564 lathercraft]# mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 21
Server version: 5.1.73 Source distribution

Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> CREATE DATABASE lathercraft_production;
Query OK, 1 row affected (0.00 sec)

mysql> GRANT ALL ON lathercraft_production.* To 'lathercraaft'@'localhost';
Query OK, 0 rows affected (0.00 sec)

mysql> exit
Bye

ついでに空のデータベースもつくちゃった。
ではマイグレーション。

[root@tk2-254-36564 lathercraft]# export SECRET_KEY_BASE=bundle exec rake secret
[root@tk2-254-36564 lathercraft]# bundle exec rake db:migrate RAILS_ENV=production
DEPRECATION WARNING: The configuration option `config.serve_static_assets` has been renamed to `config.serve_static_files` to clarify its role (it merely enables serving everything in the `public` folder and is unrelated to the asset pipeline). The `serve_static_assets` alias will be removed in Rails 5.0. Please migrate your configuration files accordingly. (called from block in  at /var/lathercraft/config/environments/production.rb:23)
== 20140708134805 CreateBrands: migrating =====================================
-- create_table(:brands)
   -> 0.6798s
-- add_index(:brands, :name, {:unique=>true})
   -> 0.0727s
-- add_index(:brands, :slug, {:unique=>true})
   -> 0.0407s
== 20140708134805 CreateBrands: migrated (0.7937s) ============================

== 20140708135345 CreateProducts: migrating ===================================
-- create_table(:products)
   -> 0.0093s
-- add_index(:products, [:brand_id, :slug], {:unique=>true})
   -> 0.8482s
== 20140708135345 CreateProducts: migrated (0.8579s) ==========================

== 20140708140110 CreateItems: migrating ======================================
-- create_table(:items)
   -> 0.0908s
-- add_index(:items, :md5, {:unique=>true})
   -> 0.3057s
== 20140708140110 CreateItems: migrated (0.3968s) =============================

== 20140708215016 DeviseCreateUsers: migrating ================================
-- create_table(:users)
   -> 0.0661s
-- add_index(:users, :email, {:unique=>true})
   -> 0.5320s
-- add_index(:users, :reset_password_token, {:unique=>true})
   -> 0.2549s
-- add_index(:users, :confirmation_token, {:unique=>true})
   -> 0.1549s
== 20140708215016 DeviseCreateUsers: migrated (1.0086s) =======================

== 20140719083223 CreateCategories: migrating =================================
-- create_table(:categories)
   -> 0.1566s
== 20140719083223 CreateCategories: migrated (0.1568s) ========================

== 20140719085230 AddCategoryIdToItem: migrating ==============================
-- add_column(:items, :category_id, :integer)
   -> 0.5393s
== 20140719085230 AddCategoryIdToItem: migrated (0.5394s) =====================

== 20140720065147 AddAdminToUsers: migrating ==================================
-- add_column(:users, :admin, :boolean, {:null=>false, :default=>false})
   -> 1.0957s
== 20140720065147 AddAdminToUsers: migrated (1.0958s) =========================

== 20140720134222 CreateStorages: migrating ===================================
-- create_table(:storages)
   -> 0.3241s
== 20140720134222 CreateStorages: migrated (0.3243s) ==========================

== 20140721073254 CreateDownloads: migrating ==================================
-- create_table(:downloads)
   -> 0.1023s
== 20140721073254 CreateDownloads: migrated (0.1025s) =========================

== 20140721080127 CreateStoredItems: migrating ================================
-- create_table(:stored_items)
   -> 0.1760s
== 20140721080127 CreateStoredItems: migrated (0.1762s) =======================

== 20140801123109 CreateRemovedItems: migrating ===============================
-- create_table(:removed_items)
   -> 0.2218s
== 20140801123109 CreateRemovedItems: migrated (0.2219s) ======================

== 20140801132346 AddBrandToRemovedItems: migrating ===========================
-- add_column(:removed_items, :brand, :string)
   -> 0.5079s
== 20140801132346 AddBrandToRemovedItems: migrated (0.5081s) ==================

== 20140802001131 AddNameToUsers: migrating ===================================
-- add_column(:users, :name, :string)
   -> 0.1279s
-- add_index(:users, :name, {:unique=>true})
   -> 0.4112s
== 20140802001131 AddNameToUsers: migrated (0.5393s) ==========================

== 20140802070045 CreateContacts: migrating ===================================
-- create_table(:contacts)
   -> 0.0461s
== 20140802070045 CreateContacts: migrated (0.0462s) ==========================

== 20140808134556 AddOnHoldToItems: migrating =================================
-- add_column(:items, :on_hold, :boolean)
   -> 0.2378s
== 20140808134556 AddOnHoldToItems: migrated (0.2380s) ========================

== 20141029120011 AddCopyrightToProducts: migrating ===========================
-- add_column(:products, :copyright, :string)
   -> 0.1440s
== 20141029120011 AddCopyrightToProducts: migrated (0.1441s) ==================

== 20141030114708 AddR18ToProducts: migrating =================================
-- add_column(:products, :r18, :boolean)
   -> 0.1771s
== 20141030114708 AddR18ToProducts: migrated (0.1772s) ========================

== 20141106130350 CreateAdditionalLinks: migrating ============================
-- create_table(:additional_links)
   -> 0.1317s
== 20141106130350 CreateAdditionalLinks: migrated (0.1318s) ===================

== 20141213055526 AddRemoteAddrToDownloads: migrating =========================
-- add_column(:downloads, :remote_addr, :string)
   -> 0.0770s
== 20141213055526 AddRemoteAddrToDownloads: migrated (0.0772s) ================

== 20151022105014 ChangeColumnOfItems: migrating ==============================
-- change_column(:items, :file_size, :integer, {:limit=>8})
   -> 0.2759s
== 20151022105014 ChangeColumnOfItems: migrated (0.2761s) =====================

== 20160601172945 AddReferrerToDownloads: migrating ===========================
-- add_column(:downloads, :referrer, :string)
   -> 0.1129s
== 20160601172945 AddReferrerToDownloads: migrated (0.1130s) ==================

== 20160603235736 AddDownloadsToRemovedItems: migrating =======================
-- add_column(:removed_items, :downloads, :integer)
   -> 0.0603s
== 20160603235736 AddDownloadsToRemovedItems: migrated (0.0604s) ==============

よし。

確認

アプリを production 環境で立ち上げてみよう。

[root@tk2-254-36564 lathercraft]# bundle exec rails s -e production -b 0.0.0.0
=> Booting WEBrick
=> Rails 4.2.8 application starting in production on http://0.0.0.0:3000
=> Run `rails server -h` for more startup options
=> Ctrl-C to shutdown server
DEPRECATION WARNING: The configuration option `config.serve_static_assets` has been renamed to `config.serve_static_files` to clarify its role (it merely enables serving everything in the `public` folder and is unrelated to the asset pipeline). The `serve_static_assets` alias will be removed in Rails 5.0. Please migrate your configuration files accordingly. (called from block in  at /var/lathercraft/config/environments/production.rb:23)
[2017-05-05 10:34:34] INFO  WEBrick 1.3.1
[2017-05-05 10:34:34] INFO  ruby 2.3.3 (2016-11-21) [x86_64-linux]
[2017-05-05 10:34:34] INFO  WEBrick::HTTPServer#start: pid=12017 port=3000

OK。ブラウザからも確認できた。
警告が出てるのはアセット関連だな。ついでに直しておこうか。

[root@tk2-254-36564 lathercraft]# cd config/environments
[root@tk2-254-36564 environments]# vi production.rb

production.rb はつぎの行を修正した(true に変更)。

config.serve_static_assets = true

アセットのプリコンパイル。

[root@tk2-254-36564 environments]# bundle exec rake assets:precompile
(in /var/lathercraft)
I, [2017-05-05T10:45:12.773119 #12052]  INFO -- : Writing /var/lathercraft/public/assets/application-9d56a9000f8aea926db88f2516d6dbf4.js
I, [2017-05-05T10:45:12.852083 #12052]  INFO -- : Writing /var/lathercraft/public/assets/application-f83f6d0d6aec02ba6b82a5bb6d9cf65a.css

もう一度アプリを立ち上げて確認。

[root@tk2-254-36564 environments]# bundle exec rails s -e production -b 0.0.0.0
=> Booting WEBrick
=> Rails 4.2.8 application starting in production on http://0.0.0.0:3000
=> Run `rails server -h` for more startup options
=> Ctrl-C to shutdown server
DEPRECATION WARNING: The configuration option `config.serve_static_assets` has been renamed to `config.serve_static_files` to clarify its role (it merely enables serving everything in the `public` folder and is unrelated to the asset pipeline). The `serve_static_assets` alias will be removed in Rails 5.0. Please migrate your configuration files accordingly. (called from block in  at /var/lathercraft/config/environments/production.rb:23)
[2017-05-05 10:46:02] INFO  WEBrick 1.3.1
[2017-05-05 10:46:02] INFO  ruby 2.3.3 (2016-11-21) [x86_64-linux]
[2017-05-05 10:46:02] INFO  WEBrick::HTTPServer#start: pid=12055 port=3000

OK。ちゃんとスタイルシートも適用されるようになった。
とりあえずここで休憩。

さくらのVPSプラン乗り換え計画(3)

Ruby と Git をインストール。
まず Ruby。

takatoh@tk2-254-36564:~$ sudo apt install ruby ruby-dev
takatoh@tk2-254-36564:~$ ruby -v
ruby 2.3.1p112 (2016-04-26) [x86_64-linux-gnu]

bundler が入っていないのでインストール。

takatoh@tk2-254-36564:~$ sudo gem install bundler

つぎは Git。

takatoh@tk2-254-36564:~$ sudo apt install git
takatoh@tk2-254-36564:~$ git --version
git version 2.7.4