Crowi-Plusを導入する@CentOS7

この投稿はSilbird Advent Calendar 2017の13日目の記事です。

こんにちは、[9日目の記事内で謎の出演](https://qiita.com/crasae/items/fc76bc6476a183f2bef8#%E3%81%9D%E3%81%97%E3%81%A6crowi%E3%82%92%E7%99%BA%E8%A6%8B)を果たしてしまった忍者です(?)
社内Slackで面白そうなネタが流れてきたので、やっぱり何事も試してみねーとわかんねーよな！！というわけでCrowi-Plus( https://github.com/weseek/crowi-plus )をAWS上に構築した手順を備忘録ついでに記します
ホントは当時弊社にいる光のアルバイトがDockerで色々やっていて、~~便乗~~流行りに乗ってDockerでどっかーんとしたかったんですが、所々あっていつもの方式でTryすることに
この時とりあえず試用目的だし動けばいいやレベルで作ってたので所々悪手があります。。。

#下ごしらえ
まずはインスタンスをブッ立ってて必要なものを入れていきます
##Make a Machine
![image.png](https://qiita-image-store.s3.amazonaws.com/0/96944/b9930fda-6740-8239-c073-18179e392001.png)

## update!
```console
$ sudo yum update
```
## git wget (nano)
```console
$ sudo yum install git wget nano
```
何故なら僕はnano派なのです
##Node Version Manager
https://github.com/creationix/nvm
を読むとインストールスクリプトがあるのでありがたく実行

```console
$ curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.7/install.sh | bash
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 12540  100 12540    0     0  47282      0 --:--:-- --:--:-- --:--:-- 47320
=> Downloading nvm from git to '/home/centos/.nvm'
=> Cloning into '/home/centos/.nvm'...
remote: Counting objects: 264, done.
remote: Compressing objects: 100% (229/229), done.
remote: Total 264 (delta 31), reused 107 (delta 25), pack-reused 0
Receiving objects: 100% (264/264), 116.48 KiB | 0 bytes/s, done.
Resolving deltas: 100% (31/31), done.
Note: checking out '65f0572bdc5c618f747df4b1e70a76fbc0174b82'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b new_branch_name

=> Compressing and cleaning up git repository

=> Appending nvm source string to /home/centos/.bashrc
=> Appending bash_completion source string to /home/centos/.bashrc
=> Close and reopen your terminal to start using nvm or run the following to use it now:

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion
```
よきに.bashrcまで弄ってくれるのでexitして再接続

## Node and NPM via NVM
Crowi-Plusでは6.xを使えと書いてあるので、とりまその系列の最新を入れる

```console
$ nvm install 6
Downloading and installing node v6.12.2...
Downloading https://nodejs.org/dist/v6.12.2/node-v6.12.2-linux-x64.tar.xz...
######################################################################## 100.0%
Computing checksum with sha256sum
Checksums matched!
Now using node v6.12.2 (npm v3.10.10)
Creating default alias: default -> 6.12.2 (-> v6.12.2)
```
ちなみにインストール可能なバージョンは`ls-remote`で確認可能

```console
$ nvm ls-remote
        v0.1.14
       <--中略-->
        v6.12.1   (LTS: Boron)
        v6.12.2   (Latest LTS: Boron)
         v7.0.0
       <--中略-->
         v9.2.1
```
とりあえず実行してみて正常に入ったかどうか

```console
$ node
> ^C
(To exit, press ^C again or type .exit)
> ^C
```
```console
$ npm

Usage: npm <command>

where <command> is one of:
    access, adduser, bin, bugs, c, cache, completion, config,
    ddp, dedupe, deprecate, dist-tag, docs, edit, explore, get,
    help, help-search, i, init, install, install-test, it, link,
    list, ln, login, logout, ls, outdated, owner, pack, ping,
    prefix, prune, publish, rb, rebuild, repo, restart, root,
    run, run-script, s, se, search, set, shrinkwrap, star,
    stars, start, stop, t, tag, team, test, tst, un, uninstall,
    unpublish, unstar, up, update, v, version, view, whoami

npm <cmd> -h     quick help on <cmd>
npm -l           display full usage info
npm help <term>  search for help on <term>
npm help npm     involved overview

Specify configs in the ini-formatted file:
    /home/centos/.npmrc
or on the command line via: npm <command> --key value
Config info can be viewed via: npm help config

npm@3.10.10 /home/centos/.nvm/versions/node/v6.12.2/lib/node_modules/npm
```
大丈夫っぽい、だがしかし、npmは4.xを使えとの事なのでnpmをアップデートする

```console
$ npm install -g npm@4.6.1
```
# Yarn
npmで入れる
なんかネイティブインストールを推奨されるが気にせず入れる

```console
$ npm install -g yarn
npm WARN deprecated yarn@1.3.2: It is recommended to install Yarn using the native installation method for your environment. See https://yarnpkg.com/en/docs/install
/home/centos/.nvm/versions/node/v6.12.2/bin/yarn -> /home/centos/.nvm/versions/node/v6.12.2/lib/node_modules/yarn/bin/yarn.js
/home/centos/.nvm/versions/node/v6.12.2/bin/yarnpkg -> /home/centos/.nvm/versions/node/v6.12.2/lib/node_modules/yarn/bin/yarn.js
/home/centos/.nvm/versions/node/v6.12.2/lib
└── yarn@1.3.2 
```

# MongoDB
yumで入れ…たいところですが、

```console
$ yum search mongo
Loaded plugins: fastestmirror
Determining fastest mirrors
 * base: ftp.iij.ad.jp
 * extras: ftp.iij.ad.jp
 * updates: ftp.iij.ad.jp
====== N/S matched: mongo ======
google-noto-sans-mongolian-fonts.noarch : Sans Mongolian font
autocorr-mn.noarch : Mongolian auto-correction rules
hunspell-mn.noarch : Mongolian hunspell dictionaries
hyphen-mn.noarch : Mongolian hyphenation rules

  Name and summary matches only, use "search all" for everything.
```
標準のrepoにはないので公式ドキュメント( https://docs.mongodb.com/manual/tutorial/install-mongodb-on-red-hat/ )を参考に

```console
$ sudo nano /etc/yum.repos.d/mongodb-org-3.6.repo
```

```:/etc/yum.repos.d/mongodb-org-3.6.repo
[mongodb-org-3.6]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.6/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-3.6.asc
```
```console
$ sudo yum install mongodb-org
```
起動して、自動起動入れて、ちゃんと上がったか確認

```console
$ sudo systemctl start mongod
$ sudo systemctl enable mongod
$ sudo systemctl status mongod
● mongod.service - High-performance, schema-free document-oriented database
   Loaded: loaded (/usr/lib/systemd/system/mongod.service; enabled; vendor preset: disabled)
   Active: active (running) since Tue 2017-12-12 10:11:08 UTC; 21s ago
     Docs: https://docs.mongodb.org/manual
 Main PID: 2572 (mongod)
   CGroup: /system.slice/mongod.service
           └─2572 /usr/bin/mongod -f /etc/mongod.conf

Dec 12 10:11:08 ip-172-31-2-118.ap-northeast-1.compute.internal systemd[1]: Starting High-performance, schema-free document-oriented database...
Dec 12 10:11:08 ip-172-31-2-118.ap-northeast-1.compute.internal systemd[1]: Started High-performance, schema-free document-oriented database.
Dec 12 10:11:08 ip-172-31-2-118.ap-northeast-1.compute.internal mongod[2568]: about to fork child process, waiting until server is ready for connections.
Dec 12 10:11:08 ip-172-31-2-118.ap-northeast-1.compute.internal mongod[2568]: forked process: 2572
Dec 12 10:11:09 ip-172-31-2-118.ap-northeast-1.compute.internal mongod[2568]: child process started successfully, parent exiting
```
とりあえず動いてるっぽいですね
本当ならここで認証を掛けた方がいいが割愛

# 本体導入
## Crowi-Plus
とりあえず何も考えず/usr/localにﾄﾞﾝ

```console
$ cd /usr/local/
$ sudo git clone -b v2.2.4 https://github.com/weseek/crowi-plus.git
Cloning into 'crowi-plus'...
remote: Counting objects: 12867, done.
remote: Compressing objects: 100% (39/39), done.
remote: Total 12867 (delta 24), reused 25 (delta 12), pack-reused 12816
Receiving objects: 100% (12867/12867), 5.02 MiB | 2.88 MiB/s, done.
Resolving deltas: 100% (9120/9120), done.
Note: checking out '2f4a462e2d5493b3f8dda65bd5d5dcb9b81f3c7e'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b new_branch_name
```
yarnしていく…が権限がないのでo+w

```console
$ cd crowi-plus
$ sudo chmod -R o+w ./
$ yarn
yarn install v1.3.2
[1/5] Validating package.json...
[2/5] Resolving packages...
[3/5] Fetching packages...
warning Pattern ["options@latest"] is trying to unpack in the same destination "/home/centos/.cache/yarn/v1/npm-options-0.0.6-ec22d312806bb53e731773e7cdaefcf1c643128f" as pattern ["options@>=0.0.5"]. This could result in a non deterministic behavior, skipping.
info fsevents@1.1.2: The platform "linux" is incompatible with this module.
info "fsevents@1.1.2" is an optional dependency and failed compatibility check. Excluding it from installation.
[4/5] Linking dependencies...
[5/5] Building fresh packages...
Done in 18.84s.
```
Build the clientしてみる

```console
$ npm run build:prod

> crowi-plus@2.2.4 prebuild:prod /usr/local/crowi-plus
> npm run plugin:def


> crowi-plus@2.2.4 plugin:def /usr/local/crowi-plus
> node bin/generate-plugin-definitions-source.js


> crowi-plus@2.2.4 build:prod /usr/local/crowi-plus
> npm run clean && webpack --config config/webpack.prod.js  --progress --profile --bail


> crowi-plus@2.2.4 clean /usr/local/crowi-plus
> npm run clean:js && npm run clean:dll && npm run clean:report


> crowi-plus@2.2.4 clean:js /usr/local/crowi-plus
> rimraf -- public/js


> crowi-plus@2.2.4 clean:dll /usr/local/crowi-plus
> rimraf -- public/dll


> crowi-plus@2.2.4 clean:report /usr/local/crowi-plus
> rimraf -- report

9844ms building modules                                                                   
34ms sealing
1ms optimizing 
0ms basic module optimization 
9ms module optimization 
3ms advanced module optimization 
11ms basic chunk optimization       
0ms chunk optimization 
0ms advanced chunk optimization 
1ms module and chunk tree optimization 
0ms chunk modules optimization 
0ms advanced chunk modules optimization 
16ms module reviving
6ms module order optimization 
9ms module id optimization 
4ms chunk reviving 
0ms chunk order optimization 
30ms chunk id optimization
46ms hashing
1ms module assets processing 
102ms chunk assets processing
2ms additional chunk assets processing 
0ms recording 
19893ms additional asset processing
4035ms chunk asset optimization
41ms asset optimization
664ms emitting
Hash: 7f5d042ebb8626bd35a5
Version: webpack 3.8.1
Time: 34595ms
                                             Asset       Size  Chunks                    Chunk Names
              c7e698a4d0956f4a939f42a05685bbf5.ttf     241 kB          [emitted]         
              1d71438462d532b62b05cdd7e6d7197d.eot    88.1 kB          [emitted]         
              0f3da1edf1b5c6a94a6ad948a7664451.eot    89.9 kB          [emitted]         
              58153ac7194e141d1e73ea88c6b63861.eot    75.7 kB          [emitted]         
             e7acc589bb558fe58936a853f570193c.woff     114 kB          [emitted]         
              2da39ecf9246383937da11b44b7bd9b4.ttf     288 kB          [emitted]  [big]  
             e74f0128884561828ce8c9cf5c284ab8.woff    98.6 kB          [emitted]         
              8256cfd7e4017a7690814879409212cd.ttf     238 kB          [emitted]         
             1cb8e94f1185f1131a0c895165998f2b.woff     116 kB          [emitted]         
              f3565095e6c9158140444970f5a2c5ed.ttf     285 kB          [emitted]  [big]  
             6b058fc2634b01d837c3432316c3141f.woff    98.8 kB          [emitted]         
              72217712eb8d28872e7069322f3fda23.eot    75.7 kB          [emitted]         
                   0.ba95229729d9c3288982.chunk.js     475 kB       0  [emitted]  [big]  
                app.d06471008c16711a5c23.bundle.js     107 kB       1  [emitted]         app
legacy-presentation.91e5190bbc7070c501cf.bundle.js     128 kB       2  [emitted]         legacy-presentation
             legacy.9e66c701e69b68c37da4.bundle.js    15.5 kB       3  [emitted]         legacy
        legacy-form.2158020681ab9c9594d4.bundle.js    12.2 kB       4  [emitted]         legacy-form
             plugin.3d735e1a1885dc82f83c.bundle.js  801 bytes       5  [emitted]         plugin
       legacy-admin.63b1400f4fd2804ea133.bundle.js    1.17 kB       6  [emitted]         legacy-admin
            commons.6ab1fa7932ce61a8511a.bundle.js    2.12 MB       7  [emitted]  [big]  commons
              style.43b6f8c002a124cccd0d.bundle.js     234 kB       8  [emitted]         style
 style-presentation.d78eac4f7e3bbfddf940.bundle.js    9.76 kB       9  [emitted]         style-presentation
 [320] ./resource/js/app.js 5.2 kB {1} [built]
        factory:236ms building:990ms = 1226ms
 [331] ./resource/js/util/Crowi.js 8.63 kB {1} [built]
       [] -> factory:208ms building:1572ms = 1780ms
 [357] ./resource/js/util/CrowiRenderer.js 6.09 kB {1} [built]
       [] -> factory:209ms building:1609ms = 1818ms
 [538] ./resource/js/util/PreProcessor/Linker.js 1.43 kB {1} [built]
       [] -> factory:453ms building:1473ms = 1926ms
 [972] ./resource/js/legacy/crowi.js 28.8 kB {3} [built]
        factory:231ms building:1148ms dependencies:0ms = 1379ms
 [992] ./resource/js/legacy/crowi-form.js 20.4 kB {4} [built]
        factory:232ms building:1182ms dependencies:2076ms = 3490ms
 [994] ./resource/js/legacy/thirdparty-js/jquery.selection.js 13 kB {4} [built]
       [] -> factory:23ms building:1821ms dependencies:0ms = 1844ms
 [997] ./resource/js/legacy/crowi-admin.js 1.52 kB {6} [built]
        factory:232ms building:1027ms dependencies:1ms = 1260ms
 [998] ./resource/js/legacy/crowi-presentation.js 2 kB {2} [built]
        factory:232ms building:1013ms dependencies:1ms = 1246ms
[1015] ./resource/js/plugin.js 1.95 kB {5} [built]
        factory:231ms building:1006ms = 1237ms
[1016] ./tmp/plugins/plugin-definitions.js 106 bytes {5} [optional] [built]
       [] -> factory:199ms building:1816ms = 2015ms
[1017] ./resource/styles/index.js 88 bytes {8} [built]
        factory:232ms building:1016ms = 1248ms
[1018] ./resource/css/crowi.scss 1.16 kB {8} [built]
       [] -> factory:1394ms building:11ms dependencies:608ms = 2013ms
[1023] ./resource/styles/presentation.js 51 bytes {9} [built]
        factory:32ms building:1151ms = 1183ms
[1024] ./resource/css/crowi-reveal.scss 1.18 kB {9} [built]
       [] -> factory:1432ms building:24ms dependencies:620ms = 2076ms
    + 1017 hidden modules
```
エラーは見えなかったので起動してみる

```console
$ MONGO_URI=mongodb://localhost/crowi npm run server:prod

> crowi-plus@2.2.4 server:prod /usr/local/crowi-plus
> node app.js --production | pino-clf common

Warning: connect.session() MemoryStore is not
designed for a production environment, as it will leak
memory, and will not scale past a single process.
```
Warnは見えるがエラーは見えないので動いているっぽいのでブラウザで確認する
どこのポートで待ち受けてるのか知りたいので一旦BGに移してnetstatで確認する

```console
^Z
[1]+  Stopped                 MONGO_URI=mongodb://localhost/crowi npm run server:prod
$ bg
[1]+ MONGO_URI=mongodb://localhost/crowi npm run server:prod &
$ sudo netstat -ap | grep node
tcp        0      0 localhost:53518         localhost:27017         ESTABLISHED 4751/node           
tcp        0      0 localhost:53510         localhost:27017         ESTABLISHED 4751/node           
tcp        0      0 localhost:53514         localhost:27017         ESTABLISHED 4751/node           
tcp        0      0 localhost:53512         localhost:27017         ESTABLISHED 4751/node           
tcp        0      0 localhost:53516         localhost:27017         ESTABLISHED 4751/node           
tcp6       0      0 [::]:hbci               [::]:*                  LISTEN      4751/node
```
`hbci`(3000)で待ち受けてるっぽいので、アクセスすると
![image.png](https://qiita-image-store.s3.amazonaws.com/0/96944/c23780b4-1109-02be-33b3-8c84b3884e54.png)
セットアップ画面と無事ご対面！
ただ、`PASSWORD_SEED`を設定してないのでこのままセットアップを進めるのはログインできなくなりそうで怖いので一旦サービス化するとともに設定も煮詰める。

```console:裏で仮起動してたサーバーを終了
$ fg
^C
```

##サービス化
うっかりnvmを使ってしまったのでそのままだと動かない
なのでExecStartのパスをちょっと弄る
nodeがどこにあるのか調べて

```console
$ nvm which 6
/home/centos/.nvm/versions/node/v6.12.2/bin/node
```
そのパスをそのまま使う(悪手)

```:/etc/systemd/system/crowi.service
[Unit]
Description=Crowi
After=network.target mongod.service

[Service]
WorkingDirectory=/usr/local/crowi-plus
EnvironmentFile=/etc/sysconfig/crowi
ExecStart=/home/centos/.nvm/versions/node/v6.12.2/bin/npm run server:prod

[Install]
WantedBy=multi-user.target
```
また、Crowiの設定はEnvなので、`EnvironmentFile`で指定したファイルにEnvの内容を書き込む

```:/etc/sysconfig/crowi
PORT=3000
NODE_ENV=production
MONGO_URI="mongodb://localhost/crowi"
PASSWORD_SEED=hogehoge
SECRET_TOKEN=fugafuga
PATH=/home/centos/.nvm/versions/node/v6.12.2/bin:/sbin:/bin:/usr/sbin:/usr/bin
```
ここで、`PASSWORD_SEED`と`SECRET_TOKEN`を適切に設定する
設定ファイルを書き終わったら起動して、自動起動設定をして、様子を見てみる

```console
$ sudo systemctl start crowi
$ sudo systemctl enable crowi
Created symlink from /etc/systemd/system/multi-user.target.wants/crowi.service to /etc/systemd/system/crowi.service.
$ sudo systemctl status crowi
● crowi.service - Crowi
   Loaded: loaded (/etc/systemd/system/crowi.service; enabled; vendor preset: disabled)
   Active: active (running) since Tue 2017-12-12 10:59:40 UTC; 9s ago
 Main PID: 5018 (npm)
   CGroup: /system.slice/crowi.service
           ├─5018 npm
           ├─5028 sh -c node app.js --production | pino-clf common
           ├─5029 node app.js --production
           └─5030 node /usr/local/crowi-plus/node_modules/.bin/pino-clf common

Dec 12 10:59:40 ip-172-31-2-118.ap-northeast-1.compute.internal systemd[1]: Started Crowi.
Dec 12 10:59:40 ip-172-31-2-118.ap-northeast-1.compute.internal systemd[1]: Starting Crowi...
Dec 12 10:59:41 ip-172-31-2-118.ap-northeast-1.compute.internal npm[5018]: > crowi-plus@2.2.4 server:prod /usr/local/crowi-plus
Dec 12 10:59:41 ip-172-31-2-118.ap-northeast-1.compute.internal npm[5018]: > node app.js --production | pino-clf common
Dec 12 10:59:42 ip-172-31-2-118.ap-northeast-1.compute.internal npm[5018]: Warning: connect.session() MemoryStore is not
Dec 12 10:59:42 ip-172-31-2-118.ap-northeast-1.compute.internal npm[5018]: designed for a production environment, as it will leak
Dec 12 10:59:42 ip-172-31-2-118.ap-northeast-1.compute.internal npm[5018]: memory, and will not scale past a single process.
```
無事Activeになったので改めて初期設定を進める
この時登録したアカウントが初代Adminとなる

##アップデート
アップデートはDBに変更がない限り

```
git pull
yarn
npm start
```
するだけなのでらくちん！

# あとがき
かなり駆け足で記していきましたが、一通り構築手順をまとめた(つもり)です
ただの構築記事なのでアレですが、誰かのCrowiライフの第一歩のお手伝いが出来れば幸いです

明日はQiita:TeamからCrowiに記事をお引越しする記事を光のアルバイトが書いてくれます！(予定)