有网友反馈py-mongo-sync同步异常,检查发现curosr[0]取查询结果第一个文档时报错”no such item for Cursor instance”。

这里的逻辑是,根据timestamp查询oplog起始位置,cursor类型是TAILABLE,然后取出第一条oplog,验证timestamp是否一致。

对方mongo版本是v3.4,同步工具在v3.2及更早版本的MongoDB上还没出过类似问题。
使用pymongo 3.5.1(最新版本)分别用v3.2和v3.4跑同步测试,在query结果非空的情况下,v3.2正常,v3.4报错,怀疑是不是v3.4做了什么改动,导致dirver不兼容。

进一步排查,cursor[0]读取文档,db端返回了一个错误,意思说tailable和singleBatch两个选项冲突。

{'number_returned': 1, 'data': [SON([(u'ok', 0.0), (u'errmsg', u"cannot use tailable option with the 'singleBatch' option"), (u'code', 2), (u'codeName', u'BadValue')])], 'starting_from': 0, 'cursor_id': 0}

cursor.__getitem__(self, index)方法,如果取单个文档,首先对当前cursor进行clone,将limit设置为-1(db返回一条文档并关闭cursor,可参考ntoreturn vs batchSize),表示只读取一条文档。

 577         if isinstance(index, integer_types):
578 if index < 0:
579 raise IndexError("Cursor instances do not support negative "
580 "indices")
581 clone = self.clone()
582 clone.skip(index + self.__skip)
583 clone.limit(-1) # use a hard limit
584 for doc in clone: 大专栏  pymongo bugfix后记
585 return doc
586 raise IndexError("no such item for Cursor instance")
587 raise TypeError("index %r cannot be applied to Cursor "
588 "instances" % index)

cursor类型是TAILABLE或TAILABLE_AWAIT,所以query的tailable选项为True;
cursor.limit设置为-1,导致query的singleBatch选项为True;
二者皆为True,引发冲突。

因为只读取一条文档,limit必须为-1,所以需要把TAILABLE和TAILABLE_AWAIT设置为0,避免选项冲突。

clone.limit(-1)  # use a hard limit
clone.__query_flags &= ~CursorType.TAILABLE_AWAIT # PYTHON-1371

至此,问题解决,说说几点收获:

  1. 尽量不要使用cursor索引访问文档,除非是一次性操作

     # 以下是原代码逻辑
    coll = self._src_mc['local'].get_collection('oplog.rs', codec_options=bson.codec_options.CodecOptions(document_class=bson.son.SON))
    cursor = coll.find({'ts': {'$gte': oplog_start}}, cursor_type=pymongo.cursor.CursorType.TAILABLE_AWAIT, no_cursor_timeout=True) if cursor[0]['ts'] == oplog_start: # 这里对原始cursor进行clone,执行查询(第一次),然后关闭cursor_cloned # 之前在跑同步时,时间戳一致,但此处可能仍有时间长短不一的等待,始终不明所以
    # 原因是下面在调用cursor.next()时会重新执行查询 while True:
    oplog = cursor.next() # 这里使用原始cursor,执行查询(第二次)
    # handle oplog
  2. 提交PR前,确保本地跑通test case,当时仅考虑到TAILABLE的情况,而忽略了TAILABLE_AWAIT
  3. 掌握PR流程:提交PR后,如果review未通过,需要修改代码,在你的local分支下继续commit并push到GitHub,新commit会自动追加到该PR,最后由项目维护者完成merge,可以参考collaborating-with-issues-and-pull-requests
  4. 最后,很高兴PR能被官方merge :)

pymongo bugfix后记的更多相关文章

  1. pymongo "ServerSelectionTimeoutError: No servers found yet" 错误的解决

    系统转移过程中,擅自把aptitude安装的mongoengine换成了pip安装,系统启动以后,报这个错误 报错提示: File "/usr/local/lib/python2.7/dis ...

  2. 使用PyMongo访问需要认证的MongoDB

    Windows 10家庭中文版,Python 3.6.4,PyMongo 3.7.0,MongoDB 3.6.3,Scrapy 1.5.0, 前言 在Python中,使用PyMongo访问Mongod ...

  3. 《C编译器剖析》后记

    这本书的序言.后记写的都让我很有感触!mark: 后 记 总有曲终人散时,不知不觉我们已经完成了对UCC 编译器的剖析,一路走来,最深的体会仍然是“纸上得来终觉浅,绝知此事要躬行”.按这个道理,理解U ...

  4. Python: Windows 7 64位 安装、使用 pymongo 3.2

    官网tutorial:  http://api.mongodb.com/python/current/tutorial.html 本教程将要告诉你如何使用pymongo模块来操作MongoDB数据库. ...

  5. 2.0 (2)测试pymongo

    在数据库中创建数据库.表,插入数据. from pymongo import MongoClient host = "localhost" port = 27017 client ...

  6. Windows平台下为Python添加MongoDB支持PyMongo

    到Python官网下载pymongo-2.6.3.win-amd64-py2.7.exe 安装pymongo-2.6.3.win-amd64-py2.7.exe 参照官方的用例进行测试 打开命令提示符 ...

  7. 【Python】pymongo使用

    官方文档:http://api.mongodb.com/python/current/index.html MongoReplicaSetClient:http://api.mongodb.com/p ...

  8. SpringMVC学习系列-后记 解决GET请求时中文乱码的问题

    SpringMVC学习系列-后记 解决GET请求时中文乱码的问题 之前项目中的web.xml中的编码设置: <filter> <filter-name>CharacterEnc ...

  9. 【mongo】pymongo通过_id删除数据

    来源:http://www.educity.cn/wenda/361741.html pymongo 根据 objectId _id 来删除数据想要删除数据,根据_id ,是最靠谱的,具体方法因为 _ ...

随机推荐

  1. Kaggle——NFL Big Data Bowl

    neural networks + feature engineering for the win 导入需要的库 import numpy as np import pandas as pd impo ...

  2. rsync配置文件模板

    用脚本实现服务端rsyncd的部署cat /server/scripts/rsync_install.sh #!/bin/bash #安装包 yum install -y rsync &> ...

  3. TPO3-2Deletion of Ogallala Aquifer

    In the face of the upcoming water supply crisis, a number of grandiose schemes have been developed t ...

  4. 在Orcl中通过SQL语句修改创建表

    1.创建表时定义唯一性约束 CREATE TABLE table_name ( column1 datatype null/not null, column2 datatype null/not nu ...

  5. kubernetes flannel 网卡绑定错误,故障排查

    kubernetes 新加了个node,状态Ready,但调度过去的任务,都执行异常 查看异常节点日志 `Error adding net work: open run/flannel/subnet. ...

  6. logstash nested内嵌字段 field protobuf解码 codec 的解决办法

    logstash nested内嵌字段 field protobuf解码 codec 的解决办法 主要需求 logstash-codec 下https://www.elastic.co/guide/e ...

  7. 非线程安全的HashMap 和 线程安全的ConcurrentHashMap

    在平时开发中,我们经常采用HashMap来作为本地缓存的一种实现方式,将一些如系统变量等数据量比较少的参数保存在HashMap中,并将其作为单例类的一个属性.在系统运行中,使用到这些缓存数据,都可以直 ...

  8. VBA/VB6/VBS/VB.NET/C#/Python/PowerShell都能调用的API封装库

    API函数很强大,但是声明的时候比较繁琐. 我开发的封装库,包括窗口.键盘.鼠标.消息等常用功能.用户不需要添加API函数的声明,就可以用到API的功能. 在VBA.VB6的引用对话框中引用API.t ...

  9. [LC] 161. One Edit Distance

    Given two strings s and t, determine if they are both one edit distance apart. Note: There are 3 pos ...

  10. Linux SSH 使用密钥登陆

    Linux SSH 使用密钥登陆 通常我们登录 Linux 服务器,我们需要使用密码进行登录,但是密码存在被暴力破解的可能. 可以将默认服务端口 22 改成其他不常用的端口. 可以设置非常复杂的密码. ...