[Centos7] mongodb を起動できなくなるerrorの対処

# install

インストールする際はこの辺を見ました
[[公式] Install MongoDB Community Edition on Red Hat or CentOS](https://docs.mongodb.com/manual/tutorial/install-mongodb-on-red-hat/#install-mongodb-community-edition-on-red-hat-or-centos)
[CentOS7 に MongoDB を導入する方法](https://qiita.com/tomy0610/items/f540150ac8acaa47ff66)

# version

mongodのバージョンは `v4.2.1` です

```bash
$ mongod --version
db version v4.2.1
git version: edf6d45851c0b9ee15548f0f847df141764a317e
OpenSSL version: OpenSSL 1.0.1e-fips 11 Feb 2013
allocator: tcmalloc
modules: none
build environment:
    distmod: rhel70
    distarch: x86_64
    target_arch: x86_64
```


# error1
## Failed to unlink socket file /tmp/mongodb-27017.sock Operation not permitted

1回起動できたんですけどね。
設定とかいじっていたら、以下のようなエラーが....(´・ω・`)

```bash
$ sudo systemctl start mongod
Job for mongod.service failed because the control process exited with error code. See "systemctl status mongod.service" and "journalctl -xe" for details.

$ sudo systemctl status mongod
● mongod.service - MongoDB Database Server
   Loaded: loaded (/usr/lib/systemd/system/mongod.service; enabled; vendor preset: disabled)
   Active: failed (Result: exit-code) since 日 2019-11-17 14:03:40 JST; 30s ago
     Docs: https://docs.mongodb.org/manual
  Process: 3471 ExecStart=/usr/bin/mongod $OPTIONS (code=exited, status=14)
  Process: 3469 ExecStartPre=/usr/bin/chmod 0755 /var/run/mongodb (code=exited, status=0/SUCCESS)
  Process: 3466 ExecStartPre=/usr/bin/chown mongod:mongod /var/run/mongodb (code=exited, status=0/SUCCESS)
  Process: 3465 ExecStartPre=/usr/bin/mkdir -p /var/run/mongodb (code=exited, status=0/SUCCESS)
 Main PID: 2847 (code=exited, status=0/SUCCESS)

11月 17 14:03:40 localhost.localdomain systemd[1]: Starting MongoDB Database Server...
11月 17 14:03:40 localhost.localdomain mongod[3471]: about to fork child process, waiting until server is ready for connections.
11月 17 14:03:40 localhost.localdomain mongod[3471]: forked process: 3475
11月 17 14:03:40 localhost.localdomain systemd[1]: mongod.service: control process exited, code=exited status=14
11月 17 14:03:40 localhost.localdomain systemd[1]: Failed to start MongoDB Database Server.
11月 17 14:03:40 localhost.localdomain systemd[1]: Unit mongod.service entered failed state.
11月 17 14:03:40 localhost.localdomain systemd[1]: mongod.service failed.
```

ちょっとログでも見てみましょう

```bash
$ sudo cat /var/log/mongodb/mongod.log

# * * 一部省略 * *
2019-11-17T14:16:17.192+0900 I  CONTROL  [main] ***** SERVER RESTARTED *****
2019-11-17T14:16:17.220+0900 I  CONTROL  [main] Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'
2019-11-17T14:16:17.332+0900 I  CONTROL  [initandlisten] MongoDB starting : pid=4687 port=27017 dbpath=/var/lib/mongo 64-bit host=localhost.localdomain
2019-11-17T14:16:17.332+0900 I  CONTROL  [initandlisten] db version v4.2.1
2019-11-17T14:16:17.332+0900 I  CONTROL  [initandlisten] git version: edf6d45851c0b9ee15548f0f847df141764a317e
2019-11-17T14:16:17.332+0900 I  CONTROL  [initandlisten] OpenSSL version: OpenSSL 1.0.1e-fips 11 Feb 2013
2019-11-17T14:16:17.332+0900 I  CONTROL  [initandlisten] allocator: tcmalloc
2019-11-17T14:16:17.332+0900 I  CONTROL  [initandlisten] modules: none
2019-11-17T14:16:17.332+0900 I  CONTROL  [initandlisten] build environment:
2019-11-17T14:16:17.332+0900 I  CONTROL  [initandlisten]     distmod: rhel70
2019-11-17T14:16:17.333+0900 I  CONTROL  [initandlisten]     distarch: x86_64
2019-11-17T14:16:17.333+0900 I  CONTROL  [initandlisten]     target_arch: x86_64
2019-11-17T14:16:17.333+0900 I  CONTROL  [initandlisten] options: { config: "/etc/mongod.conf", net: { bindIp: "127.0.0.1", port: 27017 }, processManagement: { fork: true, pidFilePath: "/var/run/mongodb/mongod.pid", timeZoneInfo: "/usr/share/zoneinfo" }, storage: { dbPath: "/var/lib/mongo", journal: { enabled: true } }, systemLog: { destination: "file", logAppend: true, path: "/var/log/mongodb/mongod.log" } }
2019-11-17T14:16:17.333+0900 E  NETWORK  [initandlisten] Failed to unlink socket file /tmp/mongodb-27017.sock Operation not permitted
2019-11-17T14:16:17.334+0900 F  -        [initandlisten] Fatal Assertion 40486 at src/mongo/transport/transport_layer_asio.cpp 693
2019-11-17T14:16:17.334+0900 F  -        [initandlisten]

***aborting after fassert() failure
```

気になる（手がかりになりそう）のはこれらですね

```bash
# statusの結果
11月 17 14:03:40 localhost.localdomain systemd[1]: mongod.service: control process exited, code=exited status=14

# logの内容
2019-11-17T14:16:17.333+0900 E  NETWORK  [initandlisten] Failed to unlink socket file /tmp/mongodb-27017.sock Operation not permitted
```

## 対策

頼りになったのはここ
[StackExchange MongoDB loads but breaks, returning status=14](
https://askubuntu.com/questions/823288/mongodb-loads-but-breaks-returning-status-14)

やり取りの中では次のようにしろと書いてあるが、、、

### 記載されている内容

```bash
$ chown -R mongodb:mongodb /var/lib/mongodb
$ chown mongodb:mongodb /tmp/mongodb-27017.sock
```

ただ、今回installされたのは、`mongodb` じゃなくて `mongod` なんですよね。なぜか。
というわけで、まず正確なpath確認からいきます

### 実際にやったこと

```bash
$ which mongod
/usr/bin/mongod

# 正しい path は、/var/lib/mongodb じゃなくて /usr/bin/mongod と判明
```

というわけで権限変更をやってみると...

```bash
$ chown -R mongodb:mongodb /usr/bin/mongod
chown: ユーザ指定が不正: `mongodb:mongodb'

$ sudo chown -R mongodb:mongodb /usr/bin/mongod
chown: ユーザ指定が不正: `mongodb:mongodb'
```

mongodbなんてuserはいないらしい！！
えぇ...本当に？
どれどれ....

```bash
$ cat /etc/passwd
# ...略
mongod:x:997:993:mongod:/var/lib/mongo:/bin/false
```

...確かにいませんでした。
`mongodb` ではなくて、 `mongod` ね...
パスだけじゃなくて、userもらしい。

こんどこそけんげんをへんこうするぞ！(`・ω・´)

```bash
# sudo をつけないと権限不足だった
$ sudo chown -R mongod:mongod /usr/bin/mongod
$ sudo chown mongod:mongod /tmp/mongodb-27017.sock
```

chownの結果は無反応。
しかし、Linuxコマンドは「返事がないのは良い知らせ」であることが多い！
多分 chown は成功したのでしょう。

いざ、mongod を再起動！

```bash
$ systemctl start mongod.service
==== AUTHENTICATING FOR org.freedesktop.systemd1.manage-units ===
Authentication is required to manage system services or units.
Authenticating as: kame.piyo (kame)
Password: # <- sudo passwordを入力
==== AUTHENTICATION COMPLETE ===

# ....なぜか若干間が空く
# prompt が戻ってきたら status を確認してみよう
$ systemctl status mongod.service
● mongod.service - MongoDB Database Server
   Loaded: loaded (/usr/lib/systemd/system/mongod.service; enabled; vendor preset: disabled)
   Active: active (running) since 日 2019-11-17 14:18:34 JST; 8s ago
     Docs: https://docs.mongodb.org/manual
  Process: 4915 ExecStart=/usr/bin/mongod $OPTIONS (code=exited, status=0/SUCCESS)
  Process: 4912 ExecStartPre=/usr/bin/chmod 0755 /var/run/mongodb (code=exited, status=0/SUCCESS)
  Process: 4909 ExecStartPre=/usr/bin/chown mongod:mongod /var/run/mongodb (code=exited, status=0/SUCCESS)
  Process: 4908 ExecStartPre=/usr/bin/mkdir -p /var/run/mongodb (code=exited, status=0/SUCCESS)
 Main PID: 4918 (mongod)
   CGroup: /system.slice/mongod.service
           mq4918 /usr/bin/mongod -f /etc/mongod.conf

11月 17 14:18:25 localhost.localdomain systemd[1]: Starting MongoDB Database Server...
11月 17 14:18:25 localhost.localdomain mongod[4915]: about to fork child process, waiting until server is ready for connections.
11月 17 14:18:25 localhost.localdomain mongod[4915]: forked process: 4918
11月 17 14:18:34 localhost.localdomain systemd[1]: Started MongoDB Database Server.
```

うしうし^^

# ~~error2~~

## NonExistentPath: Data directory /data/db not found., terminating

~~上手く起動できたと思ったのもつかの間....
今度は接続できない~~

落ち着いて考えたら、`$ mongod`ってコマンドは普通打たないです。はい。
なので、このエラー(error2)対策は正直あてになりません。

ただ、他の人もなぜか同じ現象に苦しんでいたようなので、記事は残しておきます。

```bash
$ mongod
2019-11-17T14:57:06.422+0900 I  CONTROL  [main] Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'
2019-11-17T14:57:06.493+0900 I  CONTROL  [initandlisten] MongoDB starting : pid=6049 port=27017 dbpath=/data/db 64-bit host=localhost.localdomain
2019-11-17T14:57:06.493+0900 I  CONTROL  [initandlisten] db version v4.2.1
2019-11-17T14:57:06.493+0900 I  CONTROL  [initandlisten] git version: edf6d45851c0b9ee15548f0f847df141764a317e
2019-11-17T14:57:06.493+0900 I  CONTROL  [initandlisten] OpenSSL version: OpenSSL 1.0.1e-fips 11 Feb 2013
2019-11-17T14:57:06.493+0900 I  CONTROL  [initandlisten] allocator: tcmalloc
2019-11-17T14:57:06.493+0900 I  CONTROL  [initandlisten] modules: none
2019-11-17T14:57:06.494+0900 I  CONTROL  [initandlisten] build environment:
2019-11-17T14:57:06.494+0900 I  CONTROL  [initandlisten]     distmod: rhel70
2019-11-17T14:57:06.494+0900 I  CONTROL  [initandlisten]     distarch: x86_64
2019-11-17T14:57:06.494+0900 I  CONTROL  [initandlisten]     target_arch: x86_64
2019-11-17T14:57:06.494+0900 I  CONTROL  [initandlisten] options: {}
2019-11-17T14:57:06.498+0900 I  STORAGE  [initandlisten] exception in initAndListen: NonExistentPath: Data directory /data/db not found., terminating
2019-11-17T14:57:06.499+0900 I  NETWORK  [initandlisten] shutdown: going to close listening sockets...
2019-11-17T14:57:06.500+0900 I  NETWORK  [initandlisten] removing socket file: /tmp/mongodb-27017.sock
2019-11-17T14:57:06.500+0900 I  -        [initandlisten] Stopping further Flow Control ticket acquisitions.
2019-11-17T14:57:06.500+0900 I  CONTROL  [initandlisten] now exiting
2019-11-17T14:57:06.500+0900 I  CONTROL  [initandlisten] shutting down with code:100
```

くっ....orz

今度はここが怪しいですね...

```bash
# エラー内容から抜粋
2019-11-17T14:57:06.498+0900 I  STORAGE  [initandlisten] exception in initAndListen: NonExistentPath: Data directory /data/db not found., terminating
```

まぁ、そんなディレクトリないですし....

```bash
$ ls /data
ls: /data にアクセスできません: そのようなファイルやディレクトリはありません
```

## 対策2

今度はここがあてになりました。

- [mongoDB起動で「directory /data/db not found」のエラーが発生した](https://kamotora.net/system/mongodb/mongod-directory-data-db-not-found/)
- [Mac側のmongoが起動しなくなったらdbpathを疑う](https://qiita.com/FumiyaShibusawa/items/cb224d3658be8acf4b8e)

### やったこと

まず正しい dbpath を確認


```bash
$ cat /etc/mongod.conf
# ...省略
# Where and how to store data.
storage:
  dbPath: /var/lib/mongo
  journal:
    enabled: true
# 以下略
```

dbPath: /var/lib/mongo でした
というわけで...

```bash
$ sudo mongod --dbpath /var/lib/mongo
```

なら起動できた。
けど....毎回 dbpath 指定するの嫌じゃないですか...？

もうちょっと調べようかな...？？

# error3

## 669: /var/lib/mongo/WiredTiger.turtle: handle-open: open: Permission denied

またはっせい！

```bash
$ sudo service mongod start
Redirecting to /bin/systemctl start mongod.service
Job for mongod.service failed because the control process exited with error code. See "systemctl status mongod.service" and "journalctl -xe" for details.
```

またログを見てみましょう

```bash
$ sudo cat /var/log/mongodb/mongod.log

2019-11-17T15:14:09.272+0900 I  CONTROL  [main] ***** SERVER RESTARTED *****
2019-11-17T15:14:09.330+0900 I  CONTROL  [main] Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'
2019-11-17T15:14:09.403+0900 I  CONTROL  [initandlisten] MongoDB starting : pid=6904 port=27017 dbpath=/var/lib/mongo 64-bit host=localhost.localdomain
2019-11-17T15:14:09.403+0900 I  CONTROL  [initandlisten] db version v4.2.1
2019-11-17T15:14:09.403+0900 I  CONTROL  [initandlisten] git version: edf6d45851c0b9ee15548f0f847df141764a317e
2019-11-17T15:14:09.403+0900 I  CONTROL  [initandlisten] OpenSSL version: OpenSSL 1.0.1e-fips 11 Feb 2013
2019-11-17T15:14:09.403+0900 I  CONTROL  [initandlisten] allocator: tcmalloc
2019-11-17T15:14:09.403+0900 I  CONTROL  [initandlisten] modules: none
2019-11-17T15:14:09.403+0900 I  CONTROL  [initandlisten] build environment:
2019-11-17T15:14:09.404+0900 I  CONTROL  [initandlisten]     distmod: rhel70
2019-11-17T15:14:09.404+0900 I  CONTROL  [initandlisten]     distarch: x86_64
2019-11-17T15:14:09.404+0900 I  CONTROL  [initandlisten]     target_arch: x86_64
2019-11-17T15:14:09.404+0900 I  CONTROL  [initandlisten] options: { config: "/etc/mongod.conf", net: { bindIp: "127.0.0.1", port: 27017 }, processManagement: { fork: true, pidFilePath: "/var/run/mongodb/mongod.pid", timeZoneInfo: "/usr/share/zoneinfo" }, storage: { dbPath: "/var/lib/mongo", journal: { enabled: true } }, systemLog: { destination: "file", logAppend: true, path: "/var/log/mongodb/mongod.log" } }
2019-11-17T15:14:09.406+0900 I  STORAGE  [initandlisten] Detected data files in /var/lib/mongo created by the 'wiredTiger' storage engine, so setting the active storage engine to 'wiredTiger'.
2019-11-17T15:14:09.406+0900 I  STORAGE  [initandlisten] wiredtiger_open config: create,cache_size=487M,cache_overflow=(file_max=0M),session_max=33000,eviction=(threads_min=4,threads_max=4),config_base=false,statistics=(fast),log=(enabled=true,archive=true,path=journal,compressor=snappy),file_manager=(close_idle_time=100000,close_scan_interval=10,close_handle_minimum=250),statistics_log=(wait=0),verbose=[recovery_progress,checkpoint_progress],
2019-11-17T15:14:16.011+0900 E  STORAGE  [initandlisten] WiredTiger error (13) [1573971256:11482][6904:0x7f4ce72d9c00], wiredtiger_open: __posix_open_file, 669: /var/lib/mongo/WiredTiger.turtle: handle-open: open: Permission denied Raw: [1573971256:11482][6904:0x7f4ce72d9c00], wiredtiger_open: __posix_open_file, 669: /var/lib/mongo/WiredTiger.turtle: handle-open: open: Permission denied
2019-11-17T15:14:16.014+0900 E  STORAGE  [initandlisten] WiredTiger error (13) [1573971256:14409][6904:0x7f4ce72d9c00], wiredtiger_open: __posix_open_file, 669: /var/lib/mongo/WiredTiger.turtle: handle-open: open: Permission denied Raw: [1573971256:14409][6904:0x7f4ce72d9c00], wiredtiger_open: __posix_open_file, 669: /var/lib/mongo/WiredTiger.turtle: handle-open: open: Permission denied
2019-11-17T15:14:16.017+0900 E  STORAGE  [initandlisten] WiredTiger error (13) [1573971256:17051][6904:0x7f4ce72d9c00], wiredtiger_open: __posix_open_file, 669: /var/lib/mongo/WiredTiger.turtle: handle-open: open: Permission denied Raw: [1573971256:17051][6904:0x7f4ce72d9c00], wiredtiger_open: __posix_open_file, 669: /var/lib/mongo/WiredTiger.turtle: handle-open: open: Permission denied
2019-11-17T15:14:16.017+0900 W  STORAGE  [initandlisten] Failed to start up WiredTiger under any compatibility version.
2019-11-17T15:14:16.017+0900 F  STORAGE  [initandlisten] Reason: 13: Permission denied
2019-11-17T15:14:16.017+0900 F  -        [initandlisten] Fatal Assertion 28595 at src/mongo/db/storage/wiredtiger/wiredtiger_kv_engine.cpp 786
2019-11-17T15:14:16.017+0900 F  -        [initandlisten]

***aborting after fassert() failure
```

今度はここが怪しい...もう疲れてきたな

```bash
2019-11-17T15:14:16.011+0900 E  STORAGE  [initandlisten] WiredTiger error (13) [1573971256:11482][6904:0x7f4ce72d9c00], wiredtiger_open: __posix_open_file, 669: /var/lib/mongo/WiredTiger.turtle: handle-open: open: Permission denied Raw: [1573971256:11482][6904:0x7f4ce72d9c00], wiredtiger_open: __posix_open_file, 669: /var/lib/mongo/WiredTiger.turtle: handle-open: open: Permission denied
```

## 対策3

[MongoDBが急に起動できなくなった時の対処法](https://qiita.com/kojamam/items/7ea74def635391e26346)

もう疲れたので、何も考えずに書いてある通りにとりあえずやってみた

### やったこと

```bash
$ sudo chown -R mongod:mongod /var/lib/mongo
chown: `/var/lib/mongod' にアクセスできません: そのようなファイルやディレクトリはありません
# あっそうですよね

# pathを調べて...
$ which mongo
/usr/bin/mongo

# 権限変更して...
$ sudo chown -R mongod:mongod /usr/bin/mongo

# mongod起動して...
$ sudo service mongod start

# いざアクセス！
$ mongo
MongoDB shell version v4.2.1
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("65202a1c-c8e4-4a65-b53e-1c37351d757c") }
MongoDB server version: 4.2.1
Server has startup warnings:
2019-11-17T15:17:42.055+0900 I  CONTROL  [initandlisten]
2019-11-17T15:17:42.055+0900 I  CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2019-11-17T15:17:42.055+0900 I  CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2019-11-17T15:17:42.055+0900 I  CONTROL  [initandlisten]
2019-11-17T15:17:42.056+0900 I  CONTROL  [initandlisten]
2019-11-17T15:17:42.079+0900 I  CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2019-11-17T15:17:42.079+0900 I  CONTROL  [initandlisten] **        We suggest setting it to 'never'
2019-11-17T15:17:42.079+0900 I  CONTROL  [initandlisten]
2019-11-17T15:17:42.079+0900 I  CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.
2019-11-17T15:17:42.080+0900 I  CONTROL  [initandlisten] **        We suggest setting it to 'never'
2019-11-17T15:17:42.080+0900 I  CONTROL  [initandlisten]
---
Enable MongoDB's free cloud-based monitoring service, which will then receive and display
metrics about your deployment (disk utilization, CPU, operation statistics, etc).

The monitoring data will be available on a MongoDB website with a unique URL accessible to you
and anyone you share the URL with. MongoDB may use this information to make product
improvements and to suggest MongoDB products and deployment options to you.

To enable free monitoring, run the following command: db.enableFreeMonitoring()
To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---

>
```

なぜかうまくいった...
もう詳しく調べる気が起きない

# 補足

後で気がついたのだけど、 `mongod` と `mongo` を混同していたっぽい。

- mongod は、データベースを起動するために使うもの
- mongo は、起動したデータベースにアクセスするときに使うもの

ということみたいですね。

コマンドとしては以下の順番で実行する

```bash
$ systemctl start mongod.service
$ mongo
```