pymongo.errors.ServerSelectionTimeoutError: No replica set members match selector "Primary()"

我的工作环境:
mongo-1:"172.28.32.58:28010"
mongo-2:"172.28.32.59:28010"
mongo-3:"172.28.32.60:28010"

NOTE: filename: test_pymongo.py

from pymongo import MongoClient
from pymongo import ReadPreference

# single mongo
#c = MongoClient(host="mongo-1", port=28010) # okay
#c = MongoClient('mongodb://admin:123456@mongo-1:28010,mongo-2:28010/?replicaSet=rsname')

# mongo cluster
#c = MongoClient('mongodb://admin:123456@mongo-1:28010,mongo-2:28010,mongo-3:28010')
c = MongoClient('mongodb://admin:123456@mongo-1:28010,mongo-2:28010,mongo-3:28010',read_preference=ReadPreference.SECONDARY)
c = MongoClient('mongodb://admin:123456@mongo-1:28010,mongo-2:28010,mongo-3:28010',read_preference=ReadPreference. SECONDARY_PREFERRED)
#c = MongoClient('mongodb://admin:123456@mongo-1:28010,mongo-2:28010,mongo-3:28010',read_preference=ReadPreference.NEAREST)
#c = MongoClient('mongodb://admin:123456@mongo-1:28010,mongo-2:28010,mongo-3:28010/?readPreference=secondary')
#c = MongoClient('mongodb://admin:123456@mongo-3:28010/?readPreference=secondary')

print c.nodes
print c.database_names()

输出结果:

$ python test_pymongo.py
Traceback (most recent call last):
  File "test_pymongo.py", line 16, in <module>
    print c.database_names()
  File "/root/.virtualenvs/py2.7.13mpc/lib/python2.7/site-packages/pymongo/mongo_client.py", line 1088, in database_names
    "listDatabases")["databases"]]
  File "/root/.virtualenvs/py2.7.13mpc/lib/python2.7/site-packages/pymongo/database.py", line 478, in command
    with client._socket_for_reads(read_preference) as (sock_info, slave_ok):
  File "/root/.pyenv/versions/2.7.13/lib/python2.7/contextlib.py", line 17, in __enter__
    return self.gen.next()
  File "/root/.virtualenvs/py2.7.13mpc/lib/python2.7/site-packages/pymongo/mongo_client.py", line 798, in _socket_for_reads
    with self._get_socket(read_preference) as sock_info:
  File "/root/.pyenv/versions/2.7.13/lib/python2.7/contextlib.py", line 17, in __enter__
    return self.gen.next()
  File "/root/.virtualenvs/py2.7.13mpc/lib/python2.7/site-packages/pymongo/mongo_client.py", line 762, in _get_socket
    server = self._get_topology().select_server(selector)
  File "/root/.virtualenvs/py2.7.13mpc/lib/python2.7/site-packages/pymongo/topology.py", line 210, in select_server
    address))
  File "/root/.virtualenvs/py2.7.13mpc/lib/python2.7/site-packages/pymongo/topology.py", line 186, in select_servers
    self._error_message(selector))
pymongo.errors.ServerSelectionTimeoutError: No replica set members match selector "Primary()"

连接到mongo-2:

$ /opt/mongodb/bin/mongo 127.0.0.1:28010
MongoDB shell version: 3.2.12
connecting to: 127.0.0.1:28010/test
sys95:PRIMARY> use admin;
switched to db admin
sys95:PRIMARY> db.auth('admin','123456')
1
sys95:SECONDARY> rs.slaveOk();
sys95:SECONDARY> show dbs;
admin  0.000GB
cmdb   0.001GB
local  0.002GB
mpc    0.001GB
uop    0.000GB
sys95:SECONDARY> rs.conf();
{
    "_id" : "sys95",
    "version" : 1,
    "protocolVersion" : NumberLong(1),
    "members" : [
        {
            "_id" : 0,
            "host" : "172.28.32.58:28010",
            "arbiterOnly" : false,
            "buildIndexes" : true,
            "hidden" : false,
            "priority" : 3,
            "tags" : {

            },
            "slaveDelay" : NumberLong(0),
            "votes" : 1
        },
        {
            "_id" : 1,
            "host" : "172.28.32.59:28010",
            "arbiterOnly" : false,
            "buildIndexes" : true,
            "hidden" : false,
            "priority" : 2,
            "tags" : {

            },
            "slaveDelay" : NumberLong(0),
            "votes" : 1
        },
        {
            "_id" : 2,
            "host" : "172.28.32.60:28010",
            "arbiterOnly" : false,
            "buildIndexes" : true,
            "hidden" : false,
            "priority" : 1,
            "tags" : {

            },
            "slaveDelay" : NumberLong(0),
            "votes" : 1
        }
    ],
    "settings" : {
        "chainingAllowed" : true,
        "heartbeatIntervalMillis" : 2000,
        "heartbeatTimeoutSecs" : 10,
        "electionTimeoutMillis" : 10000,
        "getLastErrorModes" : {

        },
        "getLastErrorDefaults" : {
            "w" : 1,
            "wtimeout" : 0
        },
        "replicaSetId" : ObjectId("597955a8d6042b84ccda4599")
    }
}
sys95:SECONDARY>
sys95:SECONDARY> rs.status();
{
    "set" : "sys95",
    "date" : ISODate("2017-08-10T13:54:20.760Z"),
    "myState" : 2,
    "term" : NumberLong(13),
    "heartbeatIntervalMillis" : NumberLong(2000),
    "members" : [
        {
            "_id" : 0,
            "name" : "172.28.32.58:28010",
            "health" : 0,
            "state" : 8,
            "stateStr" : "(not reachable/healthy)",
            "uptime" : 0,
            "optime" : {
                "ts" : Timestamp(0, 0),
                "t" : NumberLong(-1)
            },
            "optimeDate" : ISODate("1970-01-01T00:00:00Z"),
            "lastHeartbeat" : ISODate("2017-08-10T13:54:14.845Z"),
            "lastHeartbeatRecv" : ISODate("2017-08-10T13:31:34.288Z"),
            "pingMs" : NumberLong(0),
            "lastHeartbeatMessage" : "No route to host",
            "configVersion" : -1
        },
        {
            "_id" : 1,
            "name" : "172.28.32.59:28010",
            "health" : 1,
            "state" : 2,
            "stateStr" : "SECONDARY",  ## mongo-2 is work well!
            "uptime" : 8331,
            "optime" : {
                "ts" : Timestamp(1502371925, 1),
                "t" : NumberLong(13)
            },
            "optimeDate" : ISODate("2017-08-10T13:32:05Z"),
            "infoMessage" : "could not find member to sync from",
            "configVersion" : 1,
            "self" : true
        },
        {
            "_id" : 2,
            "name" : "172.28.32.60:28010",
            "health" : 0,
            "state" : 8,
            "stateStr" : "(not reachable/healthy)",
            "uptime" : 0,
            "optime" : {
                "ts" : Timestamp(0, 0),
                "t" : NumberLong(-1)
            },
            "optimeDate" : ISODate("1970-01-01T00:00:00Z"),
            "lastHeartbeat" : ISODate("2017-08-10T13:54:16.797Z"),
            "lastHeartbeatRecv" : ISODate("2017-08-10T13:32:10.636Z"),
            "pingMs" : NumberLong(0),
            "lastHeartbeatMessage" : "No route to host",
            "configVersion" : -1
        }
    ],
    "ok" : 1
}
sys95:SECONDARY>
sys95:SECONDARY> rs.isMaster()
{
    "hosts" : [
        "172.28.32.58:28010",
        "172.28.32.59:28010",
        "172.28.32.60:28010"
    ],
    "setName" : "sys95",
    "setVersion" : 1,
    "ismaster" : false,
    "secondary" : true,
    "me" : "172.28.32.59:28010",
    "maxBsonObjectSize" : 16777216,
    "maxMessageSizeBytes" : 48000000,
    "maxWriteBatchSize" : 1000,
    "localTime" : ISODate("2017-08-11T02:39:19.300Z"),
    "maxWireVersion" : 4,
    "minWireVersion" : 0,
    "ok" : 1
}

结果:
和DBA确认过,如果Mongo集群中有3个节点,2个关掉之后,只保留一个secondary节点,没有primary节点,是无法对外提供功能的。

No primary available for writes

No replica set members match selector "Primary()"

扩展阅读:

High Availability and PyMongo¶
http://api.mongodb.com/python/current/examples/high_availability.html

简介:

Read preference:

Read preference is configured using one of the classes from read_preferences (Primary, PrimaryPreferred, Secondary, SecondaryPreferred, or Nearest). For convenience, we also provide ReadPreference with the following attributes:

PRIMARY: Read from the primary. This is the default read preference, and provides the strongest consistency. If no primary is available, raise AutoReconnect.
PRIMARY_PREFERRED: Read from the primary if available, otherwise read from a secondary.
SECONDARY: Read from a secondary. If no matching secondary is available, raise AutoReconnect.
SECONDARY_PREFERRED: Read from a secondary if available, otherwise from the primary.
NEAREST: Read from any available member.

https://stackoverflow.com/questions/38762897/pymongo-unable-to-connect-to-primary/45616549#45616549
简介:
stackoverfow 上一个类似的问题。

pymongo unable to connect to primary

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 215,634评论 6 497
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,951评论 3 391
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 161,427评论 0 351
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,770评论 1 290
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,835评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,799评论 1 294
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,768评论 3 416
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,544评论 0 271
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,979评论 1 308
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,271评论 2 331
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,427评论 1 345
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,121评论 5 340
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,756评论 3 324
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,375评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,579评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,410评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,315评论 2 352

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,649评论 18 139
  • 观察自己的情绪和观察自己的思维一样重要! 这是情绪管理的一种,了解情绪,控制情绪,这我想也是我目前应该试着去做的事...
    和自己较个劲阅读 219评论 0 0
  • 这个故事很长,长到我不知道以什么样的方式来叙述,长到只要追忆到我的青春,就避不开你。 最早的相识是...
    一个西瓜啊阅读 236评论 0 0
  • 第七章 社区商务活动方式的兴起 第三节 摆脱困境的关键一环 1.控制成本主要驱动因素 2.“预测技术”难以控制存货...
    夜风微晨阅读 923评论 0 0