さくらの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

Rails 4.2.8にしたら外部からアクセスできなくなった

Rails を 4.1.4 から 4.2.8(4.2 系の最新版)にアップデートしたら、rails s で起動したサーバに外部(ほかの PC)からアクセスできなくなっていた。4.2 で挙動が変わったらしい。

 cf. rails sで起動したサーバにブラウザからアクセスできない – Qiita

上の参考ページにあるように、-b オプションをつければいい。

takatoh@envelopes $ bundle exec rails s -b 0.0.0.0

球面上の点を平面上にステレオ投影する

先週のさらに続き。先週は、球面上の点を平面上に投影するのに X, Y 座標をそのまま使って水平投影したけど、今度はステレオ投影というのをやってみる。
ステレオ投影は Wikipedia に詳しく載っている。
先週と同じように、下半球の点 300 個を XY 平面(赤道面)上に投影する。やってみたのが下の図。

コードは次の通り。

#!/usr/bin/env ruby
# encoding: utf-8 require 'csv' def sp(x, y, z)
[x / (1.0 - z), y / (1.0 - z)]
end csv = File.open(ARGV.shift, "r") csv.each_line do |line|
x, y, z = line.parse_csv.map{|v| v.to_f }
r = Math.sqrt(x * x + y * y + z * z)
print sp(x, y, z).map{|v| v * r }.to_csv
end

やっつけ仕事なので、ヘルプもないけど、先週の gss_gen コマンド(--cartesian オプション付き)の結果を入力として、投影点の座標を CSV で出力する。

多数の点を球面上に一様分布させる(2)

一昨日の続き。最初と最後の点を極から移動(位置調整)するのを実装した。ついでに、gem 化して RubyGems.org にアップしておいた。gem install gss_generator でインストールできる。
使い方は次の通り。

^o^ > gss_gen --cartesian --relocate 1.0 600 > c600r.csv

--cartesian はデカルト座標系で出力、--relocate は位置調整のオプション。結果は CSV 形式で標準出力に出力するので c600r.csv ファイルにリダイレクトしている。

結果を一昨日と同様の図にしたものを載せる。

最初の点が極(中心)からずれて、一様性が増しているのがわかる。

多数の点を球面上に一様分布させる

ちょっと面白いものを見つけた。

cf. LEDドームのLEDの並びを決めるのに使用した計算式 – jakaladaのブログ

球面上に任意個の点を一様分布させる、座標を求めるもの。一般化螺旋集合(generalized spiral set)というものを使っている。元の資料(論文)はここ。

cf. 多数の点を球面上に一様分布させるソフトウェアGSS Generator

上のリンク先のブログでは Python を使っているので、Ruby でやってみた。

#!/usr/bin/env ruby
# encoding: utf-8

require 'gss'
require 'optparse'
require 'csv'

options = {}
opts = OptionParser.new
opts.banner = "Generate points with uniform distribution on the sphere."
opts.on("-c", "--cartesian", "Cartesian coordinate."){|v|
  options[:cartesian] = true
}
opts.on_tail("-h", "--help", "Show this message."){|v|
  print opts.help
  exit
}
opts.on_tail("-v", "--version", "Show version."){|v|
  puts "v#{GSS::VERSION}"
  exit
}
opts.parse!

r = ARGV.shift.to_f
n = ARGV.shift.to_i

gss = GSS::GSS.new
points = gss.generate(r, n)
points.each do |p|
  if options[:cartesian]
    coord = p.to_cartesian
    print coord.to_csv
  else
    print [p.r, p.theta, p.phi].to_csv
  end
end
# encoding: utf-8

require "gss/polar_point"

module GSS
  class GSS
    def generate(r, n)
      theta_1 = Math::PI
      phi_1 = 0.0

      points = []
      points << PolarPoint.new(r, theta_1, phi_1)
      2.upto(n) do |k|
        h_k = -1.0 + 2.0 * (k - 1) / (n - 1)
        theta_k = Math.acos(h_k)
        phi_k = points.last.phi + 3.6 / Math.sqrt(n) * 1 / Math.sqrt(1 - h_k ** 2)
        phi_k = phi_k.infinite? ? 0.0 : phi_k % (Math::PI * 2.0)
        points << PolarPoint.new(r, theta_k, phi_k)
      end
      points
    end
  end # of class GSS
end # of module GSS
# encoding: utf-8
module GSS
  class PolarPoint
    attr_reader :r, :theta, :phi

    def initialize(r, theta, phi)
      @r = r
      @theta = theta
      @phi = phi
    end

    def to_cartesian
      x = @r * Math.sin(@theta) * Math.cos(@phi)
      y = @r * Math.sin(@theta) * Math.sin(@phi)
      z = @r * Math.cos(@theta)
      [x, y, z]
    end
  end # of class PolarPoint
end # of module GSS

最初のがコマンドで、あとの2つがライブラリ。引数に球の半径と配置したい点の個数を指定すると、各点の極座標を CSV 形式で出力する。

^o^ > ruby -Ilib exe/gss_gen 1.0 600

極座標じゃなく、デカルト座標(XYZ座標)がほしい時には --cartesian オプション。

^o^ > ruby -Ilib exe/gss_gen --cartesian 1.0 600

下の図は、発生させた600個の点のうち下半分の300個を XY 平面上に投影した図。

各点を順に線でつないでみると、螺旋になっているのがよくわかる。

……なんか螺旋が逆になってるな。元論文じゃ球面を下から見たと書いてあるからそのせいか?

ともあれ、それらしいのはできた。ただし、最初と最後の点の座標を調整するのはやってない。時間があったらやってみよう。

SinatraでSECURITY WARNING: No secret option provided to Rack::Session::Cookie.というワーニングが出たときの対処法

Sinatra でアプリを作ってるんだけど、セッションを利用するとタイトルのようなワーニングが出た。もっと詳しく書くと次のとおり。

SECURITY WARNING: No secret option provided to Rack::Session::Cookie.
This poses a security threat. It is strongly recommended that you
provide a secret to prevent exploits that may be possible from crafted
cookies. This will not be supported in future versions of Rack, and
future versions will even invalidate your existing user cookies.

ググってみても見つかるのは、Rails のバージョンを上げろとか、Rack のバージョンを 1.4.1 にしろとかいうのばっかり。Rails は使ってないし、Rack は 1.6.5 なんだけどなあ。そんな中で見つけたのが↓このページ。

cf. SECURITY WARNING: No secret option provided to Rack::Session::Cookie

config.ru で :session_secret に値を設定すればいいらしい。
具体的には次のようにした。

enable :sessions
set :session_secret, 'somethingverysecret1234'

これでめでたくワーニングが出なくなった。

Ubuntu 16.04にNokogiriがインストールできない

rubygems の Nokogiri のインストールで躓いた。環境は:

  • Ubuntu 16.04 LTS
  • Ruby 2.3.1
  • Gem 2.5.1

いろいろ試した結果、次のパッケージを sudo apt install したらインストールできた。

  • ruby-dev
  • libxml2
  • libxml2-dev
  • zlib1g-dev

これらをインストールしたうえで、Nokogiri をインストール。

takatoh@apostrophe $ sudo gem install nokogiri
Building native extensions.  This could take a while...
Successfully installed nokogiri-1.7.0.1
Parsing documentation for nokogiri-1.7.0.1
Installing ri documentation for nokogiri-1.7.0.1
Done installing documentation for nokogiri after 8 seconds
1 gem installed

Railsアプリの引っ越し(4)デーモンとして動かす編

起動スクリプトを、これも apostrophe からコピー。

tonzlr@wplj:/etc/init.d$ cd
tonzlr@wplj:~$ cd /etc/init.d
tonzlr@wplj:/etc/init.d$ sudo scp tonzlr@apostrophe:/etc/init.d/tonzlr .
sudo tonzlr のパスワード: 
tonzlr@apostrophe's password: 
tonzlr                                        100%  455     0.4KB/s   00:00

これも変更しないでいいんじゃないかな。

#!/bin/bash

PATH=/usr/local/bin:/usr/bin:/bin:/sbin:PATH
TONZLR_ROOT=/home/tonzlr/tonzlr

case "$1" in
start)
echo "Starting Tonzlr"
cd ${TONZLR_ROOT}
export SECRET_KEY_BASE=`rake secret`
bundle exec unicorn_rails -c unicorn.conf -E production -D
;;
stop)
echo "Stoping Tonzlr"
PID=`cat ${TONZLR_ROOT}/unicorn.pid`
kill -QUIT ${PID}
;;
*)
echo "Usage: tonzlr {start|stop}" >&2
exit 1
;;
esac

exit 0

起動確認。

tonzlr@wplj:~/tonzlr$ sudo /etc/init.d/tonzlr start
Starting Tonzlr

OK。

Unit ファイルを書く。

[Unit]
Description=Tonzlr service
After=network.target

[Service]
ExecStart=/etc/init.d/tonzlr start
ExecStop=/etc/init.d/tonzlr stop
Restart=always
Type=forking
PIDFile=/home/tonzlr/tonzlr/unicorn.pid

[Install]
WantedBy=multi-user.target

そして、/etc/systemd/system/tonzlr.service にリンクを張る。

tonzlr@wplj:~/tonzlr$ sudo ln -s /lib/systemd/system/tonzlr.service /etc/systemd/system/tonzlr.service

起動確認。

tonzlr@wplj:~/tonzlr$ sudo systemctl start tonzlr

OK。start したり stop したりして確認できた。

Ubuntu の起動時に自動起動するようにする。

tonzlr@wplj:~/tonzlr$ sudo systemctl enable tonzlr
Synchronizing state of tonzlr.service with SysV init with /lib/systemd/systemd-sysv-install...
Executing /lib/systemd/systemd-sysv-install enable tonzlr
insserv: warning: script 'K01bruschetta' missing LSB tags and overrides
insserv: warning: script 'tonzlr' missing LSB tags and overrides
insserv: warning: script 'bruschetta' missing LSB tags and overrides
update-rc.d: error: tonzlr Default-Start contains no runlevels, aborting.

むぅ、またエラーが出てる。だけど、この間の Flask アプリではこれでもちゃんと自動起動できるようになっていたので、今回もそれを期待してリブートしてみる。

tonzlr@wplj:~/tonzlr$ sudo reboot

……はたしてリブートした結果……おお、ちゃんと自動起動されている!

よし、最後に、Nginx のヴァーチャルホスト tonzlr を設定する。

upstream unicorn-tonzlr {
    server 127.0.0.1:9009;
}

server {
    # port
    listen 80;

    # server name
    server_name tonzlr;

    # document root
    root /home/tonzlr/tonzlr;

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

    # log files
    access_log /var/log/nginx/tonzlr/access.log combined;
    error_log /var/log/nginx/tonzlr/error.log warn;

    keepalive_timeout 60;
    proxy_connect_timeout 60;
    proxy_read_timeout 60;
    proxy_send_timeout 60;

    location / {
        #root /home/tonzlr/tonzlr;

        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-tonzlr;
    }

}

sites-enabled/tonzlr にリンクを張って:

tonzlr@wplj:/etc/nginx$ sudo ln -s /etc/nginx/sites-available/tonzlr /etc/nginx/sites-enabled/tonzlr

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

tonzlr@wplj:/etc/nginx$ sudo mkdir /var/log/nginx/tonzlr

Nginx をリロード。

tonzlr@wplj:/etc/nginx$ sudo systemctl reload nginx

hosts ファイルに tonzlr を追加して、http://tonzlr/ にブラウザでアクセスしてみる。

OK!!!!!!!!!
あとは、他のマシンの hosts ファイルを書き換えるだけだ。

Railsアプリの引っ越し(3)Unicornで動かす編

Unicorn のインストール。

tonzlr@wplj:~/tonzlr$ sudo apt install unicorn
[sudo] tonzlr のパスワード: 
パッケージリストを読み込んでいます... 完了
依存関係ツリーを作成しています                
状態情報を読み取っています... 完了
以下のパッケージが自動でインストールされましたが、もう必要とされていません:
  libpango1.0-0 libpangox-1.0-0 ubuntu-core-launcher
これを削除するには 'sudo apt autoremove' を利用してください。
以下の追加パッケージがインストールされます:
  ruby-kgio ruby-rack ruby-raindrops
以下のパッケージが新たにインストールされます:
  ruby-kgio ruby-rack ruby-raindrops unicorn
アップグレード: 0 個、新規インストール: 4 個、削除: 0 個、保留: 8 個。
269 kB のアーカイブを取得する必要があります。
この操作後に追加で 898 kB のディスク容量が消費されます。
続行しますか? [Y/n] Y
取得:1 http://jp.archive.ubuntu.com/ubuntu xenial/universe amd64 ruby-kgio amd64 2.10.0-1build1 [27.7 kB]
取得:2 http://jp.archive.ubuntu.com/ubuntu xenial/universe amd64 ruby-rack all 1.6.4-3 [81.3 kB]
取得:3 http://jp.archive.ubuntu.com/ubuntu xenial/universe amd64 ruby-raindrops amd64 0.16.0-1build1 [33.0 kB]
取得:4 http://jp.archive.ubuntu.com/ubuntu xenial/universe amd64 unicorn amd64 4.9.0-2build2 [127 kB]
269 kB を 0秒 で取得しました (1,720 kB/s)
以前に未選択のパッケージ ruby-kgio を選択しています。
(データベースを読み込んでいます ... 現在 216599 個のファイルとディレクトリがインストールされています。)
.../ruby-kgio_2.10.0-1build1_amd64.deb を展開する準備をしています ...
ruby-kgio (2.10.0-1build1) を展開しています...
以前に未選択のパッケージ ruby-rack を選択しています。
.../ruby-rack_1.6.4-3_all.deb を展開する準備をしています ...
ruby-rack (1.6.4-3) を展開しています...
以前に未選択のパッケージ ruby-raindrops を選択しています。
.../ruby-raindrops_0.16.0-1build1_amd64.deb を展開する準備をしています ...
ruby-raindrops (0.16.0-1build1) を展開しています...
以前に未選択のパッケージ unicorn を選択しています。
.../unicorn_4.9.0-2build2_amd64.deb を展開する準備をしています ...
unicorn (4.9.0-2build2) を展開しています...
man-db (2.7.5-1) のトリガを処理しています ...
systemd (229-4ubuntu16) のトリガを処理しています ...
ureadahead (0.100.0-19) のトリガを処理しています ...
ureadahead will be reprofiled on next reboot
ruby-kgio (2.10.0-1build1) を設定しています ...
ruby-rack (1.6.4-3) を設定しています ...
ruby-raindrops (0.16.0-1build1) を設定しています ...
unicorn (4.9.0-2build2) を設定しています ...
insserv: warning: script 'K01bruschetta' missing LSB tags and overrides
insserv: warning: script 'bruschetta' missing LSB tags and overrides
insserv: warning: script 'K01bruschetta' missing LSB tags and overrides
insserv: warning: current start runlevel(s) (empty) of script `unicorn' overrides LSB defaults (2 3 4 5).
insserv: warning: current stop runlevel(s) (0 1 2 3 4 5 6) of script `unicorn' overrides LSB defaults (0 1 6).
insserv: warning: script 'bruschetta' missing LSB tags and overrides
systemd (229-4ubuntu16) のトリガを処理しています ...
ureadahead (0.100.0-19) のトリガを処理しています ...

apostrophe から設定ファイル unicorn.conf をコピー。

tonzlr@wplj:~/tonzlr$ scp tonzlr@apostrophe:tonzlr/unicorn.conf .
tonzlr@apostrophe's password: 
unicorn.conf                                  100%  166     0.2KB/s   00:00

たぶん、変更しないでいいはず。

tonzlr@wplj:~/tonzlr$ cat unicorn.conf
listen "9009"
worker_processes 1
working_directory "/home/tonzlr/tonzlr"
pid "./unicorn.pid"
stdout_path "./unicorn.log"
stderr_path "./unicorn.log"
preload_app true
tonzlr@wplj:~/tonzlr$ bundle exec unicorn_rails -c unicorn.conf -E production

OK。ブラウザで http://localhost:9009/ にアクセスして確認できた。