Redmineのバージョンアップ（Redmine3.2 -> 4.1とRedmica1.2への切り替え）その２（構築）

はじめに
概要　調査・検討 / 構築 / 移行 / 番外編 のうちの、構築です

- [その１ 概要・調査検討](https://qiita.com/ssugimoto/items/6fee7bbf0d7c07ef9321)
- その２ 構築（このページ）
- [その３ 移行](https://qiita.com/ssugimoto/items/c5e5a0e0085bad1062d2)
- [その４ Redmine バージョンアップにおける番外編](https://qiita.com/ssugimoto/items/e62472e74fa7b0a1154f)


# 環境構築
まずは、Redmine4.1を動く環境を構築せねばと思ってやり始めるが、バージョンアップ時に使うマイグレーションが途中でエラーになる。
Redmine4.0, 4.1 どちらのバージョンアップを試してみたが同じエラーになる。そのエラーの解消を含めてRedmine4.1とRedMica1.2について記載します
<font color="blue">
**手順等、一部割愛しています**
**失敗・エラー時、実行ログを載せているため見にくいです**
</font>

---

## Redmine4.1の環境構築
### Ruby
- Redmine4.1のRubyバージョンは2.3以上が必要、Redmine3.2利用している状況では2.2.3を使っている
- 最初は 2.3を入れた。後で判明するが 2.6以上が必要
    - https://www.nslabs.jp/redmine-install.rhtml での対応表は最低2.3～だった。他に対応バージョンを記載しているサイト https://redmine.jp/tech_note/supported-rubies/ , 
http://guide.redmine.jp/RedmineInstall/

|Redmineバージョン| Ruby on Railsバージョン |Rubyバージョン|
|-----|-----|-----|
|4.1 |5.2| 2.3 〜 2.6 ★|
|4.0 |5.2| 2.2.2 〜 2.6 ◎|
|3.4.x |4.2| 2.2 〜 2.4 EOL|
|3.3.x EOL| 4.2| 2.2 〜 2.3 EOL|
|3.2.x EOL| 4.2| 2.2 EOL|

- rubyのバージョン管理は、'rbenv' を使っている
- rbenv-update があるか確認する

```
find /opt -name ruby-build
/opt/rbenv/plugins/ruby-build
/opt/rbenv/plugins/ruby-build/bin/ruby-build
/opt/rbenv/plugins/ruby-build/share/ruby-build
```

- 入っていないので入れる

```
echo $RBENV_ROOT
/opt/rbenv
```

```
# cd /opt/rbenv/plugins/
# git clone https://github.com/rkh/rbenv-update.git "$RBENV_ROOT/plugins/rbenv-update"

Cloning into '/opt/rbenv/plugins/rbenv-update'...
remote: Enumerating objects: 242, done.
remote: Total 242 (delta 0), reused 0 (delta 0), pack-reused 242
Receiving objects: 100% (242/242), 32.07 KiB | 0 bytes/s, done.
Resolving deltas: 100% (51/51), done.

# ls -l
drwxr-xr-x 4 root root  57  3月  5 16:37 rbenv-update
drwxr-xr-x 7 root root 145  5月 17  2016 ruby-build
```

- rbenv を updateする

```
# cd /opt/rbenv/plugins/rbenv-update
# rbenv update

update中
Updating rbenv
 |  From git://github.com/sstephenson/rbenv
 |  9fdce5d..d604acb  master     -> origin/master
 |  From git://github.com/sstephenson/rbenv
 |  * [new tag]         v1.1.0     -> v1.1.0
 |  * [new tag]         v1.1.1     -> v1.1.1
 |  * [new tag]         v1.1.2     -> v1.1.2
Updating rbenv-update
Updating ruby-build
 |  From git://github.com/sstephenson/ruby-build

# rbenv install -l
2.5.8
2.6.6
2.7.2
3.0.0
jruby-9.2.16.0
mruby-2.1.2
rbx-5.0
truffleruby-21.0.0
truffleruby+graalvm-21.0.0

Only latest stable releases for each Ruby implementation are shown.
Use 'rbenv install --list-all / -L' to show all local versions.

```

```
# openssl version
OpenSSL 1.0.1e-fips 11 Feb 2013
```

```
# rbenv install 2.6.6

約10分くらいかかった
```

- 使えるバージョンを確認

```
# rbenv versions
* 2.2.3 (set by /opt/rbenv/version)
  2.6.6
```
- globalを変更

```
# rbenv global 2.6.6
# rbenv versions
  2.2.3
* 2.6.6 (set by /opt/rbenv/version)

# ruby -v
ruby 2.6.6p146 (2020-03-31 revision 67876) [x86_64-linux]

```
---

### Redmine本体の場所

- ディレクトリ
/path/to/redmine3.2.0
/path/to/redmine4.1.1
それぞれディレクトリ分けてインストールしている。

- `/opt/redmine3.2.0` , `/opt/redmine4.1.1` のディレクトリとして運用

### Redmine本体のインストール
- Redmine4.1.1 を https://www.redmine.org/releases/ から tar.gzをダウンロードして展開する

```
cd /opt/
curl -O https://www.redmine.org/releases/redmine-4.1.1.tar.gz
tar xvzf redmine-4.1.1.tar.gz

展開後、所有者変更
chown -R apache:apache redmine-4.1.1
```

- cronやapache等のためにシンボリックリンクを使っているため、シンボリックリンクを変更

```
変更前
# cd /opt
# ls -l
合計 8
drwxr-xr-x  13 root   root   4096  3月  5 16:54 rbenv
lrwxrwxrwx   1 root   root     19  5月 18  2016 redmine -> /opt/redmine-3.2.0/
 
# unlink redmine
# ln -s /opt/redmine-4.1.1/ redmine

# ls -l
合計 2664
drwxr-xr-x  13 root   root      4096  3月  5 16:54 rbenv
lrwxrwxrwx   1 root   root        19  3月  5 17:56 redmine -> /opt/redmine-4.1.1/
drwxrwxr-x  19 apache apache    4096  5月 28  2016 redmine-3.2.0
drwxrwxr-x  17 apache apache    4096  4月  7  2020 redmine-4.1.1
-rw-r--r--   1 root   root   2712056  3月  5 17:43 redmine-4.1.1.tar.gz
drwxr-xr-x.  2 root   root         6  3月 26  2015 rh
```

### 設定ファイルのコピー（DB接続情報、Redmineからのメール送信の情報）

```
# cp -avp /opt/redmine-3.2.0/config/database.yml /opt/redmine-4.1.1/config/
# cp -avp /opt/redmine-3.2.0/config/configuration.yml /opt/redmine-4.1.1/config/
```

### bundlerを入れる、 Gemfileに バージョン記載があるので、その範囲であること

```
# gem install bundler:1.14.3 --no-rdoc --no-ri

ERROR:  While executing gem ... (OptionParser::InvalidOption)
    invalid option: --no-rdoc

# bundler -v
Bundler version 1.17.2

bundler 入れなくても良さげ（Redmine4.0の時はいれたけど）
```

### Redmineのインストールディレクトリで、必要な Gemを取得

```
# cd /opt/redmine-4.1.1
# bundle install --path vendor/bundler --without development test
```

最後に以下のメッセージが出た

```
HEADS UP! i18n 1.1 changed fallbacks to exclude default locale.
But that may break your application.

Please check your Rails app for 'config.i18n.fallbacks = true'.
If you're using I18n (>= 1.1.0) and Rails (< 5.2.2), this should be
'config.i18n.fallbacks = [I18n.default_locale]'.
If not, fallbacks will be broken in your app by I18n 1.1.x.

For more info see:
https://github.com/svenfuchs/i18n/releases/tag/v1.1.0
```

対応
https://blog.goo.ne.jp/system-oni800/e/d63153bec6f9429f85c17d602bf16db5
https://mocomo012.hatenablog.com/entry/2019/10/16/194221
http://midnight-engineering.hatenadiary.jp/entry/2019/01/02/181645

を参考に、

```
# vi ./config/environments/production.rb
```
```
  config.logger.level = Logger::WARN
  config.i18n.fallbacks = [I18n.default_locale]　　＜＜追加
```

```
# diff production.rb production.rb_bak 
27d26
<   config.i18n.fallbacks = [I18n.default_locale]
```

```diff:production.rb
+ config.i18n.fallbacks = [I18n.default_locale]
```


- 再度、bundler を実行する

```
cd /opt/redmine-4.1.1
bundle install --path vendor/bundler --without development test

以下となって正常終了
Using rouge 3.12.0
Bundle complete! 31 Gemfile dependencies, 59 gems now installed.
Gems in the groups development and test were not installed.
Bundled gems are installed into `./vendor/bundler`
```

- Passengerも入れる

```
# cd /opt/redmine-4.1.1
# gem install passenger --no-rdoc --no-ri

ERROR:  While executing gem ... (OptionParser::InvalidOption)
    invalid option: --no-rdoc


rbenv rehash  は実施してみた。環境変数が古いのか。
引数変えれば良さげ（https://teratail.com/questions/151110）
バージョン変わって引数かわったかも
```

- Passengerも入れる（引数変更）

```
# gem install passenger --no-document


以下となって終了

Fetching rack-2.2.3.gem
Fetching passenger-6.0.7.gem
Successfully installed rack-2.2.3
Building native extensions. This could take a while...
Successfully installed passenger-6.0.7
2 gems installed
```

- passenger の apache入れる（10-15分くらい？）

```
# passenger-install-apache2-module

(passenger-install-apache2-module --auto --languages ruby  　　という引数指定もある）


Please edit your Apache configuration file, and add these lines:
と出る、以下のメッセージはメモっておく

   LoadModule passenger_module /opt/rbenv/versions/2.6.6/lib/ruby/gems/2.6.0/gems/passenger-6.0.7/buildout/apache2/mod_passenger.so
   <IfModule mod_passenger.c>
     PassengerRoot /opt/rbenv/versions/2.6.6/lib/ruby/gems/2.6.0/gems/passenger-6.0.7
     PassengerDefaultRuby /opt/rbenv/versions/2.6.6/bin/ruby
   </IfModule>

```

続けて、

```
Validating installation...

 * Checking whether this Passenger install is in PATH... ✓
 * Checking whether there are no other Passenger installations... (!)

   You are currently validating against Phusion Passenger 6.0.7, located in:
   
     /opt/rbenv/versions/2.6.6/lib/ruby/gems/2.6.0/gems/passenger-6.0.7/bin/passenger
   
   Besides this Passenger installation, the following other
   Passenger installations have also been detected:
   
     /opt/rbenv/shims/passenger
   
   Please uninstall these other Passenger installations to avoid
   confusion or conflicts.

 * Checking whether Apache is installed... ✓
 * Checking whether the Passenger module is correctly configured in Apache... ✗

   Incorrect Passenger module path detected
   
   Phusion Passenger for Apache requires a 'LoadModule passenger_module'
   directive inside an Apache configuration file. This directive has been
   detected in the following config file:
   
      /etc/httpd/conf.d/redmine.conf
   
   However, the directive refers to the following Apache module, which is wrong:
   
      /opt/rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/passenger-5.0.28/buildout/apache2/mod_passenger.so
   
   Please edit the config file and change the directive to this instead:
   
      LoadModule passenger_module /opt/rbenv/versions/2.6.6/lib/ruby/gems/2.6.0/gems/passenger-6.0.7/buildout/apache2/mod_passenger.so


Detected 1 error(s), 1 warning(s).
Please solve the above issues, then press ENTER to continue.

```

既存のApacheのconfファイル `redmine.conf` は書き換えられなかったという　エラー？

上記のメモの通り、Apacheのconfファイルを変更する

```
cd /etc/httpd/conf.d/

vi redmine.conf
```

また、`/var/www` でシンボリックリンクを作成しているため変更する

```
# cd /var/www/html
# ls -l

redmine -> /opt/redmine-3.2.0/public     ←前のバージョンのシンボリックリンク

# unlink redmine
# ln -s /opt/redmine-4.1.1/public redmine

redmine -> /opt/redmine-4.1.1/public  ←変更後のシンボリックリンク

```

- 新しいセッション保護用の秘密鍵を生成してください。

```
# cd /opt/redmine-4.1.1
# bundle exec rake generate_secret_token
# ls -l /opt/redmine-4.1.1/config/initializers/

secret_token.rb ←このファイルが出来上がる
```

- bundle

```
# cd /opt/redmine-4.1.1
# export RAILS_ENV=production
# bundle update 

以下メッセージでbundleの更新完了
Using rouge 3.12.0
Bundle updated!
Gems in the groups development and test were not installed.
```

#### rakeマイグレーション
- VMWareでクローンしているため、MySQLのデータベース内には Redmine3.2として使っていたデータが格納されている、そのためこの手順ではインポートしていないが、実行の移行時にはインポートする
- マイグレーション実行前のMySQLのバックアップ

```
mysqldump -uXXXXX -pXXXXX データベース名| gzip > /home/redmine_`date +%y_%m_%d`.gz
```

- DBマイグレーションの実行、ここから緊張する、成功するか失敗するか、祈れ。

```
# cd /path/to/redmine
# export RAILS_ENV=production
# bundle exec rake db:migrate
```

- エラー発生！、原因究明をしていく

```
 bundle exec rake db:migrate
== 20160404080304 ForcePasswordResetDuringSetup: migrating ====================
== 20160404080304 ForcePasswordResetDuringSetup: migrated (0.0782s) ===========

== 20160416072926 RemovePositionDefaults: migrating ===========================
-- change_column("boards", :position, :integer, {:default=>nil})
   -> 0.0372s
-- change_column("custom_fields", :position, :integer, {:default=>nil})
   -> 0.0582s
-- change_column("enumerations", :position, :integer, {:default=>nil})
   -> 0.0333s
-- change_column("issue_statuses", :position, :integer, {:default=>nil})
   -> 0.0309s
-- change_column("roles", :position, :integer, {:default=>nil})
   -> 0.0286s
-- change_column("trackers", :position, :integer, {:default=>nil})
   -> 0.0219s
== 20160416072926 RemovePositionDefaults: migrated (0.2921s) ==================

== 20160529063352 AddRolesSettings: migrating =================================
-- add_column(:roles, :settings, :text, {})
   -> 0.0745s
== 20160529063352 AddRolesSettings: migrated (0.0746s) ========================

== 20161001122012 AddTrackerIdIndexToWorkflows: migrating =====================
-- add_index(:workflows, :tracker_id)
   -> 0.1898s
== 20161001122012 AddTrackerIdIndexToWorkflows: migrated (0.1899s) ============

== 20161002133421 AddIndexOnMemberRolesInheritedFrom: migrating ===============
-- add_index(:member_roles, :inherited_from)
   -> 0.2305s
== 20161002133421 AddIndexOnMemberRolesInheritedFrom: migrated (0.2307s) ======

== 20161010081301 ChangeIssuesDescriptionLimit: migrating =====================
-- change_column(:issues, :description, :text, {:limit=>16777216})
   -> 12.4342s
== 20161010081301 ChangeIssuesDescriptionLimit: migrated (12.4345s) ===========

== 20161010081528 ChangeJournalDetailsValueLimit: migrating ===================
-- change_column(:journal_details, :value, :text, {:limit=>16777216})
   -> 20.0198s
-- change_column(:journal_details, :old_value, :text, {:limit=>16777216})
   -> 18.6174s
== 20161010081528 ChangeJournalDetailsValueLimit: migrated (38.6376s) =========

== 20161010081600 ChangeJournalsNotesLimit: migrating =========================
-- change_column(:journals, :notes, :text, {:limit=>16777216})
rake aborted!
StandardError: An error has occurred, all later migrations canceled:

Mysql2::Error: Invalid default value for 'created_on': ALTER TABLE `journals` CHANGE `notes` `notes` longtext DEFAULT NULL
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/mysql2-0.5.3/lib/mysql2/client.rb:131:in `_query'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/mysql2-0.5.3/lib/mysql2/client.rb:131:in `block in query'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/mysql2-0.5.3/lib/mysql2/client.rb:130:in `handle_interrupt'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/mysql2-0.5.3/lib/mysql2/client.rb:130:in `query'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:187:in `block (2 levels) in execute'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activesupport-5.2.4.2/lib/active_support/dependencies/interlock.rb:48:in `block in permit_concurrent_loads'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activesupport-5.2.4.2/lib/active_support/concurrency/share_lock.rb:187:in `yield_shares'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activesupport-5.2.4.2/lib/active_support/dependencies/interlock.rb:47:in `permit_concurrent_loads'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:186:in `block in execute'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/connection_adapters/abstract_adapter.rb:581:in `block (2 levels) in log'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/connection_adapters/abstract_adapter.rb:580:in `block in log'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activesupport-5.2.4.2/lib/active_support/notifications/instrumenter.rb:23:in `instrument'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/connection_adapters/abstract_adapter.rb:571:in `log'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:185:in `execute'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/connection_adapters/mysql/database_statements.rb:28:in `execute'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:371:in `change_column'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:871:in `block in method_missing'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:840:in `block in say_with_time'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:840:in `say_with_time'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:860:in `method_missing'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration/compatibility.rb:26:in `change_column'
/opt/redmine-4.1.1/db/migrate/20161010081600_change_journals_notes_limit.rb:5:in `up'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:817:in `exec_migration'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:798:in `block (2 levels) in migrate'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:797:in `block in migrate'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/connection_adapters/abstract/connection_pool.rb:416:in `with_connection'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:796:in `migrate'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:977:in `migrate'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:1292:in `block in execute_migration_in_transaction'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:1345:in `ddl_transaction'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:1291:in `execute_migration_in_transaction'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:1263:in `block in migrate_without_lock'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:1262:in `each'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:1262:in `migrate_without_lock'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:1210:in `block in migrate'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:1363:in `with_advisory_lock'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:1210:in `migrate'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:1036:in `up'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:1011:in `migrate'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/tasks/database_tasks.rb:172:in `migrate'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/railties/databases.rake:60:in `block (2 levels) in <top (required)>'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/rake-13.0.3/exe/rake:27:in `<top (required)>'
/opt/rbenv/versions/2.5.8/bin/bundle:23:in `load'
/opt/rbenv/versions/2.5.8/bin/bundle:23:in `<main>'

Caused by:
ActiveRecord::StatementInvalid: Mysql2::Error: Invalid default value for 'created_on': ALTER TABLE `journals` CHANGE `notes` `notes` longtext DEFAULT NULL
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/mysql2-0.5.3/lib/mysql2/client.rb:131:in `_query'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/mysql2-0.5.3/lib/mysql2/client.rb:131:in `block in query'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/mysql2-0.5.3/lib/mysql2/client.rb:130:in `handle_interrupt'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/mysql2-0.5.3/lib/mysql2/client.rb:130:in `query'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:187:in `block (2 levels) in execute'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activesupport-5.2.4.2/lib/active_support/dependencies/interlock.rb:48:in `block in permit_concurrent_loads'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activesupport-5.2.4.2/lib/active_support/concurrency/share_lock.rb:187:in `yield_shares'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activesupport-5.2.4.2/lib/active_support/dependencies/interlock.rb:47:in `permit_concurrent_loads'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:186:in `block in execute'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/connection_adapters/abstract_adapter.rb:581:in `block (2 levels) in log'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/connection_adapters/abstract_adapter.rb:580:in `block in log'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activesupport-5.2.4.2/lib/active_support/notifications/instrumenter.rb:23:in `instrument'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/connection_adapters/abstract_adapter.rb:571:in `log'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:185:in `execute'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/connection_adapters/mysql/database_statements.rb:28:in `execute'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:371:in `change_column'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:871:in `block in method_missing'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:840:in `block in say_with_time'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:840:in `say_with_time'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:860:in `method_missing'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration/compatibility.rb:26:in `change_column'
/opt/redmine-4.1.1/db/migrate/20161010081600_change_journals_notes_limit.rb:5:in `up'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:817:in `exec_migration'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:798:in `block (2 levels) in migrate'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:797:in `block in migrate'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/connection_adapters/abstract/connection_pool.rb:416:in `with_connection'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:796:in `migrate'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:977:in `migrate'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:1292:in `block in execute_migration_in_transaction'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:1345:in `ddl_transaction'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:1291:in `execute_migration_in_transaction'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:1263:in `block in migrate_without_lock'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:1262:in `each'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:1262:in `migrate_without_lock'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:1210:in `block in migrate'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:1363:in `with_advisory_lock'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:1210:in `migrate'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:1036:in `up'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:1011:in `migrate'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/tasks/database_tasks.rb:172:in `migrate'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/railties/databases.rake:60:in `block (2 levels) in <top (required)>'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/rake-13.0.3/exe/rake:27:in `<top (required)>'
/opt/rbenv/versions/2.5.8/bin/bundle:23:in `load'
/opt/rbenv/versions/2.5.8/bin/bundle:23:in `<main>'

Caused by:
Mysql2::Error: Invalid default value for 'created_on'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/mysql2-0.5.3/lib/mysql2/client.rb:131:in `_query'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/mysql2-0.5.3/lib/mysql2/client.rb:131:in `block in query'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/mysql2-0.5.3/lib/mysql2/client.rb:130:in `handle_interrupt'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/mysql2-0.5.3/lib/mysql2/client.rb:130:in `query'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:187:in `block (2 levels) in execute'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activesupport-5.2.4.2/lib/active_support/dependencies/interlock.rb:48:in `block in permit_concurrent_loads'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activesupport-5.2.4.2/lib/active_support/concurrency/share_lock.rb:187:in `yield_shares'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activesupport-5.2.4.2/lib/active_support/dependencies/interlock.rb:47:in `permit_concurrent_loads'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:186:in `block in execute'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/connection_adapters/abstract_adapter.rb:581:in `block (2 levels) in log'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/connection_adapters/abstract_adapter.rb:580:in `block in log'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activesupport-5.2.4.2/lib/active_support/notifications/instrumenter.rb:23:in `instrument'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/connection_adapters/abstract_adapter.rb:571:in `log'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:185:in `execute'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/connection_adapters/mysql/database_statements.rb:28:in `execute'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:371:in `change_column'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:871:in `block in method_missing'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:840:in `block in say_with_time'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:840:in `say_with_time'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:860:in `method_missing'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration/compatibility.rb:26:in `change_column'
/opt/redmine-4.1.1/db/migrate/20161010081600_change_journals_notes_limit.rb:5:in `up'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:817:in `exec_migration'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:798:in `block (2 levels) in migrate'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:797:in `block in migrate'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/connection_adapters/abstract/connection_pool.rb:416:in `with_connection'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:796:in `migrate'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:977:in `migrate'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:1292:in `block in execute_migration_in_transaction'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:1345:in `ddl_transaction'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:1291:in `execute_migration_in_transaction'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:1263:in `block in migrate_without_lock'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:1262:in `each'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:1262:in `migrate_without_lock'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:1210:in `block in migrate'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:1363:in `with_advisory_lock'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:1210:in `migrate'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:1036:in `up'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/migration.rb:1011:in `migrate'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/tasks/database_tasks.rb:172:in `migrate'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/activerecord-5.2.4.2/lib/active_record/railties/databases.rake:60:in `block (2 levels) in <top (required)>'
/opt/redmine-4.1.1/vendor/bundler/ruby/2.5.0/gems/rake-13.0.3/exe/rake:27:in `<top (required)>'
/opt/rbenv/versions/2.5.8/bin/bundle:23:in `load'
/opt/rbenv/versions/2.5.8/bin/bundle:23:in `<main>'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)```
```

- 原因は、DATETIME型のカラムで DEFAULT `'0000-00-00 00:00:00'` があることで、ALTERが失敗する
    - ALTERしているカラムが文字列やlogtext型への変更が要因ではなく、ALTERした後の定義に、DEFAULT `'0000-00-00 00:00:00'` が存在することがNG
    - 長年RedmineをMySQLの古いバージョンから使いつづけ、今回のマイグレーションで見つかった問題

- テーブル定義の一例

```
mysql> desc time_entries;
+-------------+---------------+------+-----+---------------------+----------------+
| Field       | Type          | Null | Key | Default             | Extra          |
+-------------+---------------+------+-----+---------------------+----------------+
| id          | int(11)       | NO   | PRI | NULL                | auto_increment |
| project_id  | int(11)       | NO   | MUL | 0                   |                |
| user_id     | int(11)       | NO   | MUL | 0                   |                |
| issue_id    | int(11)       | YES  | MUL | NULL                |                |
| hours       | float         | NO   |     | 0                   |                |
| comments    | varchar(1024) | YES  |     | NULL                |                |
| activity_id | int(11)       | NO   | MUL | 0                   |                |
| spent_on    | date          | NO   |     | 0000-00-00          |                |
| tyear       | int(11)       | NO   |     | 0                   |                |
| tmonth      | int(11)       | NO   |     | 0                   |                |
| tweek       | int(11)       | NO   |     | 0                   |                |
| created_on  | datetime      | NO   | MUL | 0000-00-00 00:00:00 |                |
| updated_on  | datetime      | NO   |     | 0000-00-00 00:00:00 |                |
+-------------+---------------+------+-----+---------------------+----------------+

```
- 対策
    - 今後のためも考え、DEFAULT '0000-00-00 00:00:00' を撲滅させる
    - DEFAULT `CURRENT_TIMESTAMP` にはしない、Redmine4.1を新規構築してDEFAULTはNULLであることは別で確認済
- 対策例、1回のALTER文で行うこと

```
-- comments
/*
ALTER TABLE comments MODIFY created_on datetime DEFAULT null;
ALTER TABLE comments MODIFY created_on datetime not null ;
ALTER TABLE comments MODIFY updated_on datetime DEFAULT null;
ALTER TABLE comments MODIFY updated_on datetime not null ;
*/

-- ↑のように2つのカラムがあると1つごとのSQLではダメ、なので↓のようにする
ALTER TABLE comments 
 MODIFY created_on datetime DEFAULT null ,
 MODIFY updated_on datetime DEFAULT null;
ALTER TABLE comments 
 MODIFY created_on datetime not null ,
 MODIFY updated_on datetime not null ;

````

#### rakeマイグレーション前に、ALTERを実行する

- 先述の通り、ALTERしてからDBマイグレーションを行うと完走する

```
# export RAILS_ENV=production
# bundle exec rake db:migrate

== 20160404080304 ForcePasswordResetDuringSetup: migrating ====================
== 20160404080304 ForcePasswordResetDuringSetup: migrated (0.1158s) ===========

略

== 20190620135549 ChangeRolesNameLimit: migrating =============================
-- change_column(:roles, :name, :string, {:limit=>255, :default=>""})
   -> 0.0302s
== 20190620135549 ChangeRolesNameLimit: migrated (0.0303s) ====================
```

#### キャッシュクリア

```
 bundle exec rake tmp:clear
```

#### Redmineを起動（Apacheを起動）
- 構築なので、プラグインをいれない状態での動作確認
- スーパーユーザーの権限（システム管理権限）を保持したユーザでログインする
- 管理 -> 情報 を見ると
![redmine4.1.1.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1482752/b5d4d5b7-07d0-47eb-e809-3d3d1a207a04.png)

---

## プラグインの導入

- プラグイン導入の指標 Redmine公式のpluginのページ
    - https://www.redmine.org/plugins
    - いっぱいある、導入時の指標の１つとしてスターの数で判断

### Redmine3.2.0で導入しているプラグイン、これらをバージョンアップ

```
Redmine plugins:
  redmine_code_review            0.7.0
  redmine_default_custom_query   1.2.0
  redmine_messenger              1.0.3
  redmine_slack                  0.1
  view_customize                 1.1.4
```

---

### redmine_code_review

- plugin のページ
    - https://www.redmine.org/plugins/redmine_code_review
    - https://www.r-labs.org/projects/r-labs/wiki/Code_Review
    - Compatible with:	Redmine 4.1.x, 4.0.x
- Githubリポジトリ https://github.com/haru/redmine_code_review
    - https://github.com/haru/redmine_code_review/releases
    - https://github.com/haru/redmine_code_review/releases/download/1.0.0/redmine_code_review-1.0.0.zip

    ```
    Changelog
    1.0.0 (2018-12-31)
    Compatible with Redmine 4.1.x, 4.0.x.
    Download
    https://github.com/haru/redmine_code_review/releases/tag/1.0.0
    ```

- 1.0.0以降は出ていない、1.0.0でRedmine4.0も4.1も対応している

- install

  ```
    https://www.r-labs.org/projects/r-labs/wiki/Code_Review_en
    では
    1.Copy the plugin into the vendor/plugins directory
    2.Migrate plugin: rake db:migrate_plugins RAILS_ENV=production
    3.Start Redmine
    ・・・

    と記載があり、vendorディレクトリに入れるようになっているが Redmin3.2では vendorには入れていない。{redmine_dir}/plugins に入れている
  ```

  https://www.redmine.org/plugins/redmine_code_review の通りインストールする

  ```
      1.Copy the plugin into the plugins directory
      ```
          cd {redmine_path}/plugins
          curl -OL https://github.com/haru/redmine_code_review/releases/download/1.0.0/redmine_code_review-1.0.0.zip
          unzip redmine_code_review-1.0.0.zip
          rm -rf __MACOSX/
          chown -R apache:apache redmine_code_review
      ````
      2.Migrate plugin: rake redmine:plugins:migrate RAILS_ENV=production
      ```
          cd {redmine_path}
          bundle exec rake redmine:plugins:migrate RAILS_ENV=production
      ```
      3.Restart Redmine
      ```
          systemctl reload httpd.service
      ```
      4.Enable the module on the project setting page.
      5.Goto Code Review setting tab and select the tracker for code reviews.

      redmine_code_review-1.0.0.zip 展開すると、「__MACOSX」不要なファイルがたくさんある
  ```

- 検証
    - プロジェクト 設定-> モジュール「コードレビュー」をチェックON -> 保存
    - プロジェクト 設定 タブ「コードレビュー」が表示され、割り当てるトラッカー、アサインするトラッカーが表示・選択でき、「更新」できること

---

### redmine_default_custom_query

- plugin のページ https://www.redmine.org/plugins/redmine_default_custom_query
- 対応バージョン Redmine3.1.x ～ Redmine3.4.x の記載までgithubの情報が最新
- https://github.com/hidakatsuya/redmine_default_custom_query/blob/master/README.md
    - ここみると、Redmine4.0, Ruby2.6までの記載はある
    - Version 1.5.0が最終リリースで 2019-10-27
    - issues の#48 で 4.1.1で error がある模様 （https://github.com/hidakatsuya/redmine_default_custom_query/issues/48）

- install

```
    cd /path/to/your-redmine/plugins

    git clone https://github.com/hidakatsuya/redmine_default_custom_query.git redmine_default_custom_query

    chown -R apache:apache redmine_default_custom_query
    cd ../
    bundle install --without development test
    bundle exec rake redmine:plugins:migrate RAILS_ENV=production
    または
                rake redmine:plugins:migrate NAME=redmine_default_custom_query RAILS_ENV=production
```

- 検証
    - 設定 -> プロジェクト -> モジュール「デフォルトカスタムクエリ」をチェックON -> 保存 
        -> プロジェクト設定にて タブ「デフォルトカスタムクエリ」が表示される -> タブを選択し、デフォルトカスタムクエリのプルダウンを選択 -> チケット一覧がその条件にあった一覧になること

---

### redmine_messenger

slack,mattermost,rocketchatプラグインをforkしているのでいい感じに使える

- plugin のページ https://www.redmine.org/plugins/

```
    Messenger plugin for Redmine with Slack, Discord, Rocket.Chat and Mattermost support. It notifies your chat server when something happened in your specific Redmine projects.

    This plugin is a fork of redmine_slack, redmine_mattermost and redmine_rocketchat. With one installation you can use all popular messengers and decide which one is the best for your team in order to collaborate and receive notifications about important Redmine changes in real-time.
```

```
    Changelog
    1.0.6 (2019-12-31)
    Compatible with Redmine 4.1.x, 4.0.x.
    
    See Changelog at Github.
```

- Redmineからslackへの通知は、このpluginでいけるのでは？（プラグイン「redmine_slack」は「redmine_messenger」で代替可能そう）
    - Redmine version 4.0.0以上、Ruby2.4以上となっている（昔は、古いRedmineのバージョンでも動いたと思われる、Redmine3.2で動かしていたので）
- install インストール方法 
https://github.com/alphanodes/redmine_messenger#installation

    ```
    cd {$REDMINE_ROOT}/plugins
    git clone https://github.com/AlphaNodes/redmine_messenger.git redmine_messenger
    chown -R apache:apache redmine_messenger
    cd {$REDMINE_ROOT}
    bundle update
    bundle exec rake redmine:plugins:migrate RAILS_ENV=production
    ```

- 検証

  ```
  設定例は以下がわかりやすい
  https://qiita.com/Yoto_3/items/417d40e900c65cae23ec

  redmineがインストールされたサーバから直にcurlでリクエストすると何がダメか切り分けしやすい
  https://docs.mattermost.com/developer/webhooks-incoming.html

  例）
  curl -i -X POST -H "Content-Type: application/json" -d "{\"text\": \"Hello, this is some text\nThis is more text. :tada:\"}" https://xxx/hooks/5qqrphwdwbabcdfghijklmn

  MattermostのRedmine用のワークスペースを設定する場合は
  URL:https://xxx/hooks/h7z3ihg8qabcdefghijklmn
  チャンネル：redmine_hook
  ```

---

### Redmine Slack
- plugin のページ https://github.com/sciyoshi/redmine-slack だが、メンテナンスされていない
- https://www.redmine.org/plugins/redmine_slack  （https://github.com/evolvingweb/redmine_slack） を変わりに導入するか？
- また、前述記載済の「redmine_messenger」でslack連携可能な記載があるのでそれを使う方が良いのではないか？
→ redmine_messangerを使う方針で決定

---

### view_customize
- plugin のページ https://www.redmine.org/plugins/view_customize
- Githubリポジトリ https://github.com/onozaty/redmine-view-customize
- 対応バージョン Redmine 4.1.x, 4.0.x, 3.4.x, 3.3.x, 3.2.x, 3.1.x

    ```
    Changelog
    2.8.1 (2021-02-13)
    Compatible with Redmine 4.1.x, 4.0.x, 3.4.x, 3.3.x, 3.2.x, 3.1.x.

    https://github.com/onozaty/redmine-view-customize/releases/tag/v2.8.1
    ```
- インストール方法

    ```
    Installation notes
    cd {RAILS_ROOT}/plugins
    git clone https://github.com/onozaty/redmine-view-customize.git view_customize

    chown -R apache:apache view_customize
    cd ../
    bundle install --without development test
    bundle exec rake redmine:plugins:migrate RAILS_ENV=production
    ```
- 検証
    - http://redmineのホスト/admin
    - 管理 -> 設定 プラグインにて、当該プラグインがエラーなく表示されること
    - チケットのコメントの背景が薄い黄色になること
    - チケットの関連するチケット　と　履歴コメントの間に、 「show All」が表示されること、その切替が動作すること
    - https://redmineのホスト/view_customizes での表示を確認する

---

### プラグイン入れたもの一覧とバージョン
![redmine-プラグイン入れたもの一覧とバージョン.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1482752/5984c565-2eaa-3471-5071-8c031a6fadc3.png)

---

## テーマとfavicon
### themesの適用と

`redmine_theme_farend_fancy-master`を従来から使っており、https://github.com/farend/redmine_theme_farend_fancy によると、

```
public/themes以下にテーマを保存
Redmineのインストールディレクトリで以下のコマンドを実行してください。

git clone https://github.com/farend/redmine_theme_farend_fancy.git public/themes/farend_fancy
gitコマンドが利用できない場合、以下のURLからzipファイルをダウンロードし展開してください。

https://github.com/farend/redmine_theme_farend_fancy/archive/master.zip
アーカイブを展開した結果作成されたディレクトリをRedmineインストールディレクトリ以下のpublic/themesディレクトリにfarend_fancyという名前でコピーしてください。

新しいテーマの利用
Redmineの管理画面で新しいテーマを利用する設定を行います。

「管理」→「設定」→「表示」画面内の項目「テーマ」で「Fare fancy」を選択、画面最下部の「保存」ボタンをクリックしてください。

```

#### 設定例
- install

```
cd /opt/redmine-4.1.1/public/themes
git clone https://github.com/farend/redmine_theme_farend_fancy.git farend_fancy
chown -R apache:apache farend_fancy

Redmine画面
管理 -> 表示 -> テーマのプルダウン、Farend fancy を選択

```

### favicon.ico のコピー

単にファイルのコピーのみ

```
cp -avp /opt/redmine-3.2.0/public/favicon.ico /opt/redmine-4.1.1/public/
`/opt/redmine-3.2.0/public/favicon.ico' -> `/opt/redmine-4.1.1/public/favicon.ico'
```

---

## ログローテーション
- Apache / Redmine / MySQL  等のログローテーション回数等を設定する
- Redmineはデフォルトだと１ファイルに出力するため、日々のローテーション等に変えておく方が良い
- Apacheはアクエス元、アクエス先などを保持しておくため長期保持する（RedmineのログはApacheよりも詳細な内容になる

### MySQLのログローテーション
- 参考
- https://leben.mobi/blog/mysql-logrotate/linux/
- https://pgmemo.tokyo/data/archives/1114.html
- https://blog.inouetakuya.info/entry/20130320/1363776504

```
# logrotate -dv /etc/logrotate.d/mysql 
```

- テスト

```
logrotate -dv /etc/logrotate.d/mysql
```

- 実際にローテーション

```
logrotate -v /etc/logrotate.d/mysql
```

- 以下の日付を変更することで、ローテーションテストできる

```
# cat /var/lib/logrotate.status |grep mysql
"/var/log/mysql/mysqld.log" 2021-3-16-17:0:0
```

### Redmineのログローテーション

```
# cat /etc/logrotate.d/redmine 
/opt/redmine-3.2.0/log/*.log {
    daily
    notifempty
    missingok
    copytruncate
    compress
    rotate 14
    su apache apache
}
```

変更後、シンボリックリンクのパスでローテーションするようにした

```
# cat /etc/logrotate.d/redmine 
```

```
/opt/redmine-3.2.0/log/*.log {
    daily
    notifempty
    missingok
    copytruncate
    compress
    rotate 14
    su apache apache
}

# symbolic link
/opt/redmine/log/*.log {
    dateext
    daily
    notifempty
    missingok
    copytruncate
    compress
    rotate 365
    su apache apache
}
 
```

動作確認

```
# logrotate -dv /etc/logrotate.d/redmine 
```

以下の日付を変更することで、ローテーションテストできる

```
# cat /var/lib/logrotate.status |grep redmine
"/opt/redmine-3.2.0/log/production.log" 2021-3-5-14:36:5
```

実際にローテーション

```
logrotate -v /etc/logrotate.d/redmine
```

---

## MySQLとテーブルの文字エンコードを変更（utf8 -> utf8mb4）
- 1.. ここまでの作業で、Redmineのバージョンアップとしての構築はできていますが、画面や連携等で絵文字入力、ファイル名に絵文字があるとエラーで登録できず不便なので対応する

- 2.. mysqlの設定ファイル確認

```
# cat /etc/my.cnf
```

- 3.. mysqlに接続して database　単位での characterを確認

```
mysql -uXXXX -p -h localhost

mysql> show variables like "character%";
+--------------------------+----------------------------+
| Variable_name            | Value                      |
+--------------------------+----------------------------+
| character_set_client     | utf8                       |
| character_set_connection | utf8                       |
| character_set_database   | latin1                     |
| character_set_filesystem | binary                     |
| character_set_results    | utf8                       |
| character_set_server     | latin1                     |
| character_set_system     | utf8                       |
| character_sets_dir       | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
8 rows in set (0.01 sec)

mysql> use databasenamaeXXXX;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

show variables like "character%";Database changed
mysql> show variables like "character%";
+--------------------------+----------------------------+
| Variable_name            | Value                      |
+--------------------------+----------------------------+
| character_set_client     | utf8                       |
| character_set_connection | utf8                       |
| character_set_database   | utf8                       |
# For advice on how to change settings please see
| character_set_filesystem | binary                     |
| character_set_results    | utf8                       |
# For advice on how to change settings please see
| character_set_server     | latin1                     |
| character_set_system     | utf8                       |
| character_sets_dir       | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
8 rows in set (0.00 sec)

mysql> 
mysql> quit;
Bye
```

- 4.. `/etc/my.cnf` に utf8mb4を設定追加 、２つのセクションに追加する

```
[mysqld]
character-set-server = utf8mb4

[client]
default-character-set=utf8mb4

```

- 5.. mysqlインスタンスを再起動 

```
systemctl restart mysqld.service 
```

- 6.. データベース内の設定を変更

```
mysql> use redmine;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show variables like "character%";
+--------------------------+----------------------------+
| Variable_name            | Value                      |
+--------------------------+----------------------------+
| character_set_client     | utf8mb4                    |
| character_set_connection | utf8mb4                    |
| character_set_database   | utf8                       |
| character_set_filesystem | binary                     |
| character_set_results    | utf8mb4                    |
| character_set_server     | utf8mb4                    |
| character_set_system     | utf8                       |
| character_sets_dir       | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
8 rows in set (0.01 sec)
```

- 7.. database は utf8 のままなので、

mysql内のredmineデータベースの文字コードを変更

```
mysql> alter database redmine character set utf8mb4;
Query OK, 1 row affected (0.00 sec)

mysql> show variables like "character%";
+--------------------------+----------------------------+
| Variable_name            | Value                      |
+--------------------------+----------------------------+
| character_set_client     | utf8mb4                    |
| character_set_connection | utf8mb4                    |
| character_set_database   | utf8mb4                    |
| character_set_filesystem | binary                     |
| character_set_results    | utf8mb4                    |
| character_set_server     | utf8mb4                    |
| character_set_system     | utf8                       |
| character_sets_dir       | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
8 rows in set (0.00 sec)
```

- 8.. database内の全テーブルのエンコードを変える

ALTER分の生成は移行編の記事の方で詳細を記載予定

ファイル `/tmp/alters_table_CHARSET.sql` としてSQL生成

```
alter table `ar_internal_metadata` convert to character set utf8mb4;
alter table `attachments` convert to character set utf8mb4;
alter table `auth_sources` convert to character set utf8mb4;
alter table `boards` convert to character set utf8mb4;
alter table `changes` convert to character set utf8mb4;
・・・
````

utf8mb4への変更するALTERをSQLファイル読み込みで実行する。ALTER文のコピー＆ペーストは途中でエラーになることがあるので量が多いときは非推奨

```
mysql -uXXXX -p -D redmineが使うdatabasename < /tmp/alters_table_CHARSET.sql
```


- 9.. redmineのデータベース設定ファイルを変更する

`/opt/redmine-4.1.1/config/database.yml`

```
production:
   adapter: mysql2
   database: redmineが使うデータベース
   host: localhost
   username: XXXX
   password: XXXX
   encoding: utf8mb4
```

redmine用 httpdを開始する

```
# systemctl start httpd.service
```

- 動作確認 絵文字のサンプル、チケットの本文やコメント等に入力して反映できるか試す

```
マグロ🍣スシ マグロ🐟スシ
```

## ここまでで、Redmine4.1の構築とバージョンは完了

---

# RedMica1.2への切替え（バージョンアップ）

手順は、[インストール済みのRedmineをRedMica 1.2に切り替える手順](https://blog.redmine.jp/articles/mica-1_2/migration-from-redmine/) を参考にすれば良い。その手順では
既存のredmine4.1の場所をベースに、 `git clone` して gitの管理ファイルを使い、 `git pull`, `git checkout ` 運用でバージョンアップしていく場合に有用な手順です。

<font color="Red">Redmine4.1とは別ディレクトリで運用していくケースでは少し異なり、途中でミスってます（なので最後まで手順確認してから行うようにしてください）。
ミスしている過程を載せているため、一部の後続手順を前に持ってきてください。</font>

### RedMicaを取得し配置する
```
curl -O https://github.com/redmica/redmica/archive/refs/tags/v1.2.1.tar.gz
```
curlが失敗、HTTPステータス304なのが要因なのかな。wgetでは成功する


```
# cd /tmp 
# wget -c  https://github.com/redmica/redmica/archive/refs/tags/v1.2.1.tar.gz

ファイル名を変更
# mv v1.2.1.tar.gz redmica-1.2.1.tar.gz

/opt/ にもっていくので移動
# mv redmica-1.2.1.tar.gz /opt/
# tar -xvzf redmica-1.2.1.tar.gz 

# cd /opt/redmica-1.2.1

git 関係ファイルがないことを確認
# gt status
```

### RedMica1.2を使う設定をしていく

- bundle

```
cd /opt/redmica-1.2.1
bundle update
```

`bundle update `すると、データベースのymlを設定するメッセージ（`Please configure your config/database.yml first`）が表示されるが、updateは処理される

- config ファイル（database.yml、configuration.yml）をRedmine4.1の場所からコピーする

```
# cp -avp /opt/redmine-4.1.1/config/database.yml /opt/redmica-1.2.1/config/
# cp -avp /opt/redmine-4.1.1/config/configuration.yml /opt/redmica-1.2.1/config/
```

- 再度 `bundle update` を行う

- pluginsディレクトリまるごと redmine4.1からコピー

```
cp -avp /opt/redmine-4.1.1/plugins/* /opt/redmica-1.2.1/plugins/
```

- マイグレーション

コマンド

```
# export RAILS_ENV=production
# bundle exec rake db:migrate

または bin/rails db:migrate RAILS_ENV=production
```

実行

```
# cd /opt/redmica-1.2.1
# export RAILS_ENV=production
# bundle exec rake db:migrate
Could not find gem 'factory_girl' in any of the gem sources listed in your Gemfile.
Run `bundle install` to install missing gems.
````

RedMicaのディレクトリはRedmine4.1ディレクトリと同じ前提の手順のため、コマンドが不足している。
install の方をしないといけない

```
cd /opt/redmica-1.2.1

bundle update
bundle install
```

- 再度、dbマイグレーションを行う がエラーになる

```
# cd /opt/redmica-1.2.1
# bin/rails db:migrate RAILS_ENV=production
rails aborted!
ArgumentError: Missing `secret_key_base` for 'production' environment, set this string with `rails credentials:edit`
/opt/redmica-1.2.1/config/environment.rb:16:in `<top (required)>'
bin/rails:4:in `require'
bin/rails:4:in `<main>'
Tasks: TOP => db:migrate => db:load_config => environment
(See full trace by running task with --trace)
```

要因、シークレットキー生成しが必要なので、下記を実行する

```
# cd /opt/redmica-1.2.1
# bundle exec rake generate_secret_token

```

- プラグインのマイグレーション	

```
# export RAILS_ENV=production
# bundle exec rake redmine:plugins:migrate RAILS_ENV=production
```

- キャッシュクリア

```
bundle exec rake tmp:clear
```

- テーマとfavicon

```
cp -avp /opt/redmine-4.1.1/public/themes/farend_fancy /opt/redmica-1.2.1/public/themes/
cp -avp /opt/redmine-4.1.1/public/favicon.ico /opt/redmica-1.2.1/public/
```

- RedMica関連ファイルのパーミッション変更しておく

```
# cd /opt/redmica-1.2.1
# chown -R apache:apache *
```

- シンボリックリンク変更

Apacheの読み込み用、/var/www/html のサブディレクトリ、 Apacheのconfファイル

- Apacheのreload

- 画面でバージョン確認と動作確認

![redmica1.2.1_抜粋.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1482752/7a5bd0c0-6e91-7ebc-f6c9-d4a6cf996035.png)


ここまでで、Redmica1.2へのバージョンアップ・切替えが完了
VMWareを使っている場合はスナップショット作成をしておくと戻しやすくなります

---

## rakeコマンドでメール送信しているがエラーになっている

rake コマンド実行の

```
#!/bin/bash
echo $PATH
export PATH="/opt/rbenv/shims:/opt/rbenv/shims:$PATH"
echo $PATH
cd /opt/redmine;
rake redmine:send_reminders days=3 RAILS_ENV=production
echo fix.`date +"%Y%m%d_%H%M%S"`
```

エラー内容
Gemfileでは reke は 13.0.3 が必要だとなっているのでエラーになっている


```
/opt/rbenv/shims:/opt/rbenv/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
/opt/rbenv/shims:/opt/rbenv/shims:/opt/rbenv/shims:/opt/rbenv/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
rake aborted!
Gem::LoadError: You have already activated rake 12.3.3, but your Gemfile requires rake 13.0.3. Prepending `bundle exec` to your command may solve this.
/opt/redmine-4.1.1/config/boot.rb:6:in `<top (required)>'
/opt/redmine-4.1.1/config/application.rb:3:in `<top (required)>'
/opt/redmine-4.1.1/Rakefile:5:in `<top (required)>'
(See full trace by running task with --trace)
````



バージョン確認

```
$ bundle -v
Bundler version 1.17.2
$ which rake
/opt/rbenv/shims/rake
$ rake -v
rake aborted!
No Rakefile found (looking for: rakefile, Rakefile, rakefile.rb, Rakefile.rb)

(See full trace by running task with --trace)
$ rake --version
rake, version 12.3.3

$ gem list rake

*** LOCAL GEMS ***

rake (12.3.3)

```

いったん消して、別バージョンを入れる

```
$ cd /path/to/redmine
$ gem uninstall rake -v 12.3.3

$ gem uninstall rake -v 12.3.3
Gem 'rake' is not installed

$ gem install rake -v 13.0.3

$ bundle update rake

```

指定バージョンインストール後

```
$ rake --version
rake, version 13.0.3
$ which rake
/opt/rbenv/shims/rake
$ gem list rake

*** LOCAL GEMS ***

rake (13.0.3)
```

rakeコマンド成功を確認する