python+gevent+threadpool+cx_Oracle高并发时空指针问题-程序员宅基地

技术标签: python  网络  数据库  

手头有个python项目,该项目是一个数据库中间件,用于集中处理各个业务系统对Oracle数据库的增删改查操作。

项目采用gevent的WSGISever启动:

application = tornado.wsgi.WSGIApplication([
    (r"/healthcheck", HealthCheck)])
...
server = gevent.wsgi.WSGIServer(('', args.port), application, log=None)
server.serve_forever()

该项目自我接手以来,一直在找系统性能瓶颈,经过长时间的测试、调查,发现,cx_Oracle的OCI不支持异步,导致gevent在协程处理请求时,如果数据库长时间不返回,系统就会被阻塞,从而使后续请求得不到处理,最终系统崩溃。

关于cx_Oracle的OCI不支持异步,请参考:

https://bitbucket.org/anthony_tuininga/cx_oracle/issues/8/gevent-eventlet-support

Takehiro Kubo

IMO, it is impossible with cx_Oracle.

Psycopg2 uses libpq (PostgreSQL client library), which provides asynchronous functions. Psycopg2 supports async I/O calls with the aid of the asynchronous functions. (Well, I have not confirmed it... I'm not a python user.)

On the other hand, cx_Oracle uses OCI(Oracle Call Interface), which doesn't provide asynchronous functions. Strictly speaking it provides an asynchronous function which makes a connection non-blocking. But there is no way to detect the status of the connection: whether it is readable or so. If OCI provided a function which exposed underneath TCP/IP sockets, pipe descriptors (local connections on Unix) or named pipe handles (local connections on Windows) to caller such as cx_Oracle, Gevent/Eventlet might use the sockets/descriptors/handles to support async I/O calls. However OCI doesn't provide such functions as mentioned.

 所以为了解决阻塞的问题,我在访问数据库的地方开辟线程去访问数据库,代码如下:

class BaseServices:
    def __init__(self, db_pool, wap_db_pool):
        self.wap_db_pool = wap_db_pool
        self._db_pool = db_pool
        self._db_handle_pool = ThreadPool(1000)
        self._logger = logging.getLogger('default')
        self.db_ops = {}
        Logger.debug(self._logger, 'BaseDataQueryService created')

    def do_db_operation(self, op_id, conn, c, procedure_name, procedure_params):
        self._logger.debug('inside, parent thread is %s ,thread is %s' % (op_id, thread.get_ident()))
        try:
            p = c.callproc(procedure_name, procedure_params)
            self._logger.debug('inside after, parent thread is %s ,thread is %s, p is %s, db_pool_maxsize is %s, db_pool_size is %s'
                               % (op_id, thread.get_ident(), str(p), conn._pool._maxconnections, conn._pool._connections))

        except Exception as ex:
            self._logger.error(ex)
            msg = traceback.format_exc()
            self._logger.error('\n' + 'inside exception, parent thread is %s ,thread is %s'
                               % (op_id, thread.get_ident()) + ' ' + msg)
        self._logger.debug('inside end ,parent thread is %s , thread is %s, thread_pool_maxsize is %s, thread_pool_size is %s'
                           % (op_id, thread.get_ident(), str(self._db_handle_pool._get_maxsize()),
                              str(self._db_handle_pool._get_size())))
        # self.db_ops.get(op_id).set(p)
        return p

   def query_force_db(self, data):
        """
        强查数据库
        :param data: post报文
        :return:
        """
        ...
        try:
                ....
                conn, c = None, None
                try:
                    conn = self._db_pool.connection()
                    c = conn.cursor()
                    procedure_result_list = []
                    self._logger.debug('before, thread is %s , thread_pool_maxsize is %s, thread_pool_size is %s'% (thread.get_ident(), str(self._db_handle_pool._get_maxsize()),
                                          str(self._db_handle_pool._get_size())))
                    self._logger.debug('before, thread is %s, db_pool_maxsize is %s, db_pool_size is %s'% (thread.get_ident(), conn._pool._maxconnections, conn._pool._connections))
                    #   调用存储过程 参数使用      procedure_name和procedure_params   return p
                    # 改进后采用线程访问数据库
                    p = self._db_handle_pool.apply(self.do_db_operation, (str(thread.get_ident()),conn,c, procedure_name, procedure_params))
                    # 改进前直接访问数据库,会阻塞
                    # p = c.callproc(procedure_name, procedure_params)
                    ...                   
                    self._logger.debug('after, p = %s ,thread = %s, thread_pool_maxsize is %s, thread_pool_size is %s'% (p, thread.get_ident(), str(self._db_handle_pool._get_maxsize()),
                                       str(self._db_handle_pool._get_size())))
                    self._logger.debug('after, thread = %s, db_pool_maxsize is %s, db_pool_size is %s'% (thread.get_ident(), conn._pool._maxconnections, conn._pool._connections))
                    for out_value in p[len(procedure_in_params):]:
                        ...
                except Exception as ex:
                    self._logger.error(ex)
                    msg = traceback.format_exc()
                    self._logger.error('\n' + msg)
                    ...
                finally:
                    if conn is not None:
                        conn.close()
                    self._logger.debug('finally, thread = %s, db_pool_maxsize is %s, db_pool_size is %s'
                                       % (thread.get_ident(), conn._pool._maxconnections, conn._pool._connections))
                ...
        except Exception as ex:
            self._logger.error(ex)
            msg = traceback.format_exc()
            self._logger.error('\n' + msg)
            ...
        finally:
            pass
        return res_model
 

改进后的代码,解决了阻塞的问题,当一个请求在数据库里长时间不能返回时,别的请求依然能正常被处理。本以为如此就解决了该系统性能不高的问题,结果压测的时候发现并不然,该系统的性能依然不高。

数据库连接池大小是1000:

db_pool = PooledDB(cx_Oracle, threaded=True, user=xx,password=xx,dsn='dsn'
                   mincached=1, maxcached=1, maxconnections=1000)

线程池大小是1000,代码如上述BaseService里所示。

采用siege压测5分钟,并发量是600:

$siege/bin/siege -c 600 -t 5M -f url.txt 

 压测结果:

很明显,这个结果很不理想。按理说,数据库连接池1000,线程池1000,每个请求在数据库里的执行时间1秒(实际上,压测的URL最终都是在数据库里sleep了1秒然后返回'success'),那么并发量应该在1000左右时能表现良好,命中率令人满意才对。但是,理想是美好的,现实是骨感的,600的并发量的命中率只有23.76% 。进一步压测,并发量为400时的命中率也只有46.77%。

为了追踪内部运行情况,加了一些跟线程池、数据库连接池相关的log,如上述代码。发现,数据库连接池基本是正常的,1000的连接池,能用到300+ ,而线程池,不对劲,1000的线程池,只用到23,通篇日志文件里,线程池的只能到23,感觉如同到此为止了样。

日志文件里主要有以下问题:

2种错误输出

[2016-09-09 17:50:35,766] DEBUG::(1676 46912773723152)::BaseServices[line:126] - before, thread is 46912773723152 
[2016-09-09 17:50:35,766] DEBUG::(1676 46912773723792)::BaseServices[line:34] - inside, parent thread is 46912773723152 ,thread is 46912773723792
[2016-09-09 17:50:40,854] DEBUG::(1676 46912773723152)::BaseServices[line:133] - after, p = None ,thread = 46912773723152
[2016-09-09 17:50:40,854] ERROR::(1676 46912773723152)::BaseServices[line:151] - 'NoneType' object has no attribute '__getitem__'
[2016-09-09 17:50:40,854] ERROR::(1676 46912773723152)::BaseServices[line:153] - 
Traceback (most recent call last):
  File "/home/was/python_apps/lcy_test/AsyncQueryProject/Services/BaseServices.py", line 134, in query_force_db
    for out_value in p[len(procedure_in_params):]:
TypeError: 'NoneType' object has no attribute '__getitem__'


[2016-09-09 17:50:33,476] DEBUG::(1676 46912773633360)::BaseServices[line:126] - before, thread is 46912773633360 
[2016-09-09 17:50:36,296] DEBUG::(1676 46912773633360)::BaseServices[line:133] - after, p = None ,thread = 46912773633360
[2016-09-09 17:50:36,296] ERROR::(1676 46912773633360)::BaseServices[line:151] - 'NoneType' object has no attribute '__getitem__'
[2016-09-09 17:50:36,297] ERROR::(1676 46912773633360)::BaseServices[line:153] - 
Traceback (most recent call last):
  File "/home/was/python_apps/lcy_test/AsyncQueryProject/Services/BaseServices.py", line 134, in query_force_db
    for out_value in p[len(procedure_in_params):]:
TypeError: 'NoneType' object has no attribute '__getitem__'

这个,主要是数据库返回结果变量p为空导致,至于为啥它会为空,我也没搞明白,分析日志文件,貌似:

1. 数据库没返回结果,导致主线程对空p进行处理;

2. 子线程没有进入,导致主线程“跳过”子线程直接对空p进行处理。

but,为什么会这样呢?有大神能指导一下么

 

 [2016-09-14 15:33:42,970] ERROR::(12505 46912619885904)::BaseServices[line:41] - This operation would block forever
[2016-09-14 15:33:42,971] ERROR::(12505 46912619885904)::BaseServices[line:44] - 
inside exception, parent thread is 46912622501712 ,thread is 46912619885904 Traceback (most recent call last):
  File "/home/was/python_apps/lcy_test/AsyncQueryProject/Services/BaseServices.py", line 38, in do_db_operation
    % (op_id, thread.get_ident(), str(p), conn._pool._maxconnections, conn._pool._connections))
  File "/home/was/software/python2.7.8/lib/python2.7/logging/__init__.py", line 1148, in debug
    self._log(DEBUG, msg, args, **kwargs)
  File "/home/was/software/python2.7.8/lib/python2.7/logging/__init__.py", line 1279, in _log
    self.handle(record)
  File "/home/was/software/python2.7.8/lib/python2.7/logging/__init__.py", line 1289, in handle
    self.callHandlers(record)
  File "/home/was/software/python2.7.8/lib/python2.7/logging/__init__.py", line 1329, in callHandlers
    hdlr.handle(record)
  File "/home/was/software/python2.7.8/lib/python2.7/logging/__init__.py", line 755, in handle
    self.acquire()
  File "/home/was/software/python2.7.8/lib/python2.7/logging/__init__.py", line 706, in acquire
    self.lock.acquire()
  File "/home/was/software/python2.7.8/lib/python2.7/threading.py", line 173, in acquire
    rc = self.__block.acquire(blocking)
  File "_semaphore.pyx", line 112, in gevent._semaphore.Semaphore.acquire (gevent/gevent._semaphore.c:3004)
  File "/home/was/software/python2.7.8/lib/python2.7/site-packages/gevent-1.0.1-py2.7-linux-x86_64.egg/gevent/hub.py", line 331, in switch
    return greenlet.switch(self)
LoopExit: This operation would block forever

我在网上看了很多这个错误的分析,没得到什么有用的启示。我狠郁闷。究竟为什么会block forever,在什么情况下如此,这个异常是不是就是我的系统性能上不去的原因?各位走过路过的大神,谁能指点一下我

转载于:https://my.oschina.net/kaxifa/blog/746826

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/chuzhuanbo7093/article/details/100983954

智能推荐

vue js 监听页面滚动触底 && 监听iframe滚动及触底 && 带你搞清 offsetHeight,scrollTop,scrollHeight区别_vue scrollheight-程序员宅基地

文章浏览阅读3.7k次。想要监听页面滚动是否触底,你要先搞清offsetHeight,scrollTop,scrollHeight区别,以及如何让应用,话不多说上代码????????offsetHeight: 它是包括padding、border、水平滚动条,但不包括margin的元素的高度。️:对于行内元素这个属性值一直是0,单位px,是只读元素。scrollTop:表示在有滚动条时,滚动条向下滚动的距离也就是元素顶部被遮住部分的高度即“卷”起来的高度。️:在无滚动条时scrollTop==0恒成立,单位_vue scrollheight

LOAD_TEMP - Unable to get database metadata from this database connection-程序员宅基地

文章浏览阅读1w次。关于kettle 写入mysql 遇到一个问题:LOAD_TEMP - Unable to get database metadata from this database connection,报错大致如下:2021/11/26 14:05:12 - LOAD_TEMP - ERROR (version 5.3.0.0-213, build 1 from 2015-02-02_12-17-08 by buildguy) : org.pentaho.di.core.exception.KettleDa_unable to get database metadata from this database connection

XPath详解_如何定义xpath-程序员宅基地

文章浏览阅读935次。XPath简介XPath 是一门在 XML 文档中查找信息的语言。XPath 用于在 XML 文档中通过元素和属性进行导航什么是 XPath?XPath 使用路径表达式在 XML 文档中进行导航XPath 包含一个标准函数库XPath 是 XSLT 中的主要元素XPath 是一个 W3C 标准XPath 路径表达式XPath 使用路径表达式来选取 XML 文档中的节点或者节点集。这些路径表达式和我们在常规的电脑文件系统中看到的表达式非常相似。XPath 标准函数XPath 含有超过 _如何定义xpath

pppoe远程计算机错误,PPPoE宽带拨号连接常见错误代码是什么意思-程序员宅基地

文章浏览阅读828次。原标题:"PPPoE宽带拨号连接常见错误代码的解决办法 错误769的处理方法"的相关路由器设置教程资料分享。- 来源:191路由网。当我们家的网络出现问题时,网络管理员一般会问你电脑的宽带连接错误代码是什么。其实我们自己也可以通过这些错误代码,自行解决问题。下边我说下怎么看错误代码和解决办法。家里有接路由器的,请把WAN口的线拔出,插到任意LAN口上,然后宽带连接。注意,测试完毕后,记得恢复原状。..._pppoe不能建立到远程计算机的连接,因此用于此链接的端口已关闭

单元测试之Mockito+Junit使用和总结(完整)_junit mockito-程序员宅基地

文章浏览阅读1.1w次,点赞10次,收藏90次。一、什么是MOCK测试Mock 测试就是在测试过程中,对于某些不容易构造(如 HttpServletRequest 必须在Servlet 容器中才能构造出来)或者不容易获取比较复杂的对象(如 JDBC 中的ResultSet 对象),用一个虚拟的对象(Mock 对象)来创建以便测试的测试方法。Mock 最大的功能是帮你把单元测试的耦合分解开,如果你的代码对另一个类或者接口有依赖,它能够帮你模拟这些依赖,并帮你验证所调用的依赖的行为。mock中的必知概念:打桩(存根):模拟要调用的函数(打桩对象),_junit mockito

集合 List、Set、Map 的区别和实现原理_容器map和set,list和set 对比和底层实现-程序员宅基地

文章浏览阅读2.3k次,点赞5次,收藏17次。集合 List、Set、Map 的区别和实现原理Java中的集合包括三大类,它们是Set、List和Map,它们都处于java.util包中,Set、List和Map都是接口,它们有各自的实现类。Set的实现类主要有HashSet和TreeSet,List的实现类主要有ArrayList,Map的实现类主要有HashMap和TreeMap。_容器map和set,list和set 对比和底层实现

随便推点

最强PostMan使用教程(1)-程序员宅基地

文章浏览阅读10w+次,点赞235次,收藏993次。最近需要测试产品中的REST API,无意中发现了PostMan这个chrome插件,把玩了一下,发现postman秉承了一贯以来google工具强大,易用的特质。独乐乐不如众乐乐,特此共享出来给大伙。Postman介绍Postman是google开发的一款功能强大的网页调试与发送网页HTTP请求,并能运行测试用例的的Chrome插件。其主要功能包括:模拟各种HTTP requests从常用的_postman

PTA 单链表结点删除_pta带头结点的有序单链表插入及删除。-程序员宅基地

文章浏览阅读2.4k次。本题要求实现两个函数,分别将读入的数据存储为单链表、将链表中所有存储了某给定值的结点删除。链表结点定义如下:struct ListNode { int data; ListNode *next;};函数接口定义:struct ListNode *readlist();struct ListNode *deletem( struct ListNode *L, i..._pta带头结点的有序单链表插入及删除。

"session marked for kill " 处理杀不掉的锁,立即释放会话资源-程序员宅基地

文章浏览阅读7.9k次,点赞4次,收藏12次。ORA-00031: session marked for kill 处理Oracle中杀不掉的锁最近遇到,ORACLE中的进程被杀掉后,状态被置为"killed",但是锁定的资源很长时间不释放 现在提供一种方法解决这种问题,那就是在ORACLE中杀不掉的,在OS一级再杀。 1.下面的语句用来查询哪些对象被锁: SELECT S.USERNAME,S.OSUSER,S._session marked for kill

git命令-笔记_git show current-程序员宅基地

文章浏览阅读205次。1 下载地址Windows版本:https://git-scm.com/download/winGit-2.29.1-64-bit.exe 2.29.12 相关命令2.1 基本git init 初始化代码仓库git status 查询仓库索引状态git add <文件名/目录> 添加文件到仓库git config --global user.email “[email protected]” 配置全局的提交者邮箱git config --global user.name “Y_git show current

unity3d UnityScript to C# Convertor 1.4 扩展 下载-程序员宅基地

文章浏览阅读538次。资源名称:UnityScript to C# Convertor  资源版本:1.4  资源类型:.unitypackage  资源大小:293K  更新时间:2014-01-13  资源图片: unity3d下载地址:http://www.unitymanual.com/thread-10680-1-1.html

STM32 磁场传感器HMC5883-程序员宅基地

文章浏览阅读1.7k次。一、IIC协议默认(出厂) HMC5883LL 7 位从机地址为0x3C 的写入操作,或0x3D 的读出操作。要改变测量模式到连续测量模式,在通电时间后传送三个字节:0x3C 0x02 0x00将00写入第二寄存器或模式寄存器以完成从单一模式切换到连续测量模式的设置。随着数据速率在出厂默认的15Hz更新,在查询HMC5883L数据寄存器进行新的测量之前,I2C主机允许产生一个..._hmc5883l 从机地址地址位

推荐文章

热门文章

相关标签