「Mongo」Unauthorized 故障排查手记

故障现象

服务端的架构是Vue.js + Express + MongoDB来读取爬虫的数据,出现接口请求不到数据的情况,Express返回的错误信息如下

{"status":"1","msg":"Topology was destroyed"}

不是Express的问题,而是Mongo数据库挂了,重启后第二天依然宕机。查看Mongo日志可以看到不同的授权命令错误。

getLog: "startupWarnings" && replSetGetStatus: 1.0, forShell: 1.0

错误日志

2018-09-28T21:41:00.326+0800 I NETWORK  [thread1] connection accepted from 127.0.0.1:35736 #1 (1 connection now open)
2018-09-28T21:41:00.326+0800 I NETWORK  [conn1] received client metadata from 127.0.0.1:35736 conn1: { application: { name: "MongoDB Shell" }, driver: { name: "MongoDB Internal Client", version: "3.4.7" }, os: { type: "Linux", name: "CentOS Linux release 7.4.1708 (Core) ", architecture: "x86_64", version: "Kernel 3.10.0-514.26.2.el7.x86_64" } }
2018-09-28T21:41:00.328+0800 I ACCESS   [conn1] Unauthorized: not authorized on admin to execute command { getLog: "startupWarnings" }
2018-09-28T21:41:00.329+0800 I ACCESS   [conn1] Unauthorized: not authorized on admin to execute command { replSetGetStatus: 1.0, forShell: 1.0 }
2018-09-28T21:41:02.942+0800 I -        [conn1] end connection 127.0.0.1:35736 (1 connection now open)

翻译过来就是没有admin权限去执行某些命令。
在之前的使用中,爬虫数据库一直是使用readWrite权限的,并没有赋予dbAdmin权限,问题的症结就在于此。
重启Mongo后为问题库的用户添加dbAdmin权限即可。

use spider
db.updateUser("my",{roles:[{role:"dbAdmin",db:"spider"},{role:"readWrite",db:"spider"}]})
> show users
{
    "_id" : "spider.my",
    "user" : "my",
    "db" : "spider",
    "roles" : [
        {
            "role" : "dbAdmin",
            "db" : "spider"
        },
        {
            "role" : "readWrite",
            "db" : "spider"
        }
    ]
}

注意,出现故障的原因是Express进行数据库连接后执行的某些命令,但连接的用户没有执行权限,所以要修改的是服务端连接的用户,而不是其他用户。

serverStatus: 1.0

错误日志

2018-10-16T02:25:00.635+0800 I ACCESS   [conn825] Unauthorized: not authorized on test to execute command { serverStatus: 1.0 }
2018-10-16T02:25:05.607+0800 I -        [conn825] end connection 120.78.231.236:57936 (3 connections now open)
2018-10-16T04:11:14.000+0800 I NETWORK  [thread1] connection accepted from 106.15.76.92:54166 #826 (3 connections now open)
2018-10-16T04:11:14.044+0800 I ACCESS   [conn826] Unauthorized: not authorized on test to execute command { serverStatus: 1.0 }
2018-10-16T04:11:18.997+0800 I -        [conn826] end connection 106.15.76.92:54166 (3 connections now open)
2018-10-16T06:42:57.190+0800 I NETWORK  [thread1] connection accepted from 106.15.52.246:45912 #827 (3 connections now open)
2018-10-16T06:42:57.314+0800 I ACCESS   [conn827] Unauthorized: not authorized on test to execute command { serverStatus: 1.0 }
2018-10-16T06:43:02.223+0800 I -        [conn827] end connection 106.15.52.246:45912 (3 connections now open)

修改授权

use spider;
db.grantRolesToUser(
  "users",
   [
     {role: "clusterMonitor", db:"admin"},
     {role: "clusterAdmin", db:"admin"}
   ]
);

你可能感兴趣的:(「Mongo」Unauthorized 故障排查手记)