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

智能推荐

攻防世界_难度8_happy_puzzle_攻防世界困难模式攻略图文-程序员宅基地

文章浏览阅读645次。这个肯定是末尾的IDAT了,因为IDAT必须要满了才会开始一下个IDAT,这个明显就是末尾的IDAT了。,对应下面的create_head()代码。,对应下面的create_tail()代码。不要考虑爆破,我已经试了一下,太多情况了。题目来源:UNCTF。_攻防世界困难模式攻略图文

达梦数据库的导出(备份)、导入_达梦数据库导入导出-程序员宅基地

文章浏览阅读2.9k次,点赞3次,收藏10次。偶尔会用到,记录、分享。1. 数据库导出1.1 切换到dmdba用户su - dmdba1.2 进入达梦数据库安装路径的bin目录,执行导库操作  导出语句:./dexp cwy_init/[email protected]:5236 file=cwy_init.dmp log=cwy_init_exp.log 注释:   cwy_init/init_123..._达梦数据库导入导出

js引入kindeditor富文本编辑器的使用_kindeditor.js-程序员宅基地

文章浏览阅读1.9k次。1. 在官网上下载KindEditor文件,可以删掉不需要要到的jsp,asp,asp.net和php文件夹。接着把文件夹放到项目文件目录下。2. 修改html文件,在页面引入js文件:<script type="text/javascript" src="./kindeditor/kindeditor-all.js"></script><script type="text/javascript" src="./kindeditor/lang/zh-CN.js"_kindeditor.js

STM32学习过程记录11——基于STM32G431CBU6硬件SPI+DMA的高效WS2812B控制方法-程序员宅基地

文章浏览阅读2.3k次,点赞6次,收藏14次。SPI的详情简介不必赘述。假设我们通过SPI发送0xAA,我们的数据线就会变为10101010,通过修改不同的内容,即可修改SPI中0和1的持续时间。比如0xF0即为前半周期为高电平,后半周期为低电平的状态。在SPI的通信模式中,CPHA配置会影响该实验,下图展示了不同采样位置的SPI时序图[1]。CPOL = 0,CPHA = 1:CLK空闲状态 = 低电平,数据在下降沿采样,并在上升沿移出CPOL = 0,CPHA = 0:CLK空闲状态 = 低电平,数据在上升沿采样,并在下降沿移出。_stm32g431cbu6

计算机网络-数据链路层_接收方收到链路层数据后,使用crc检验后,余数为0,说明链路层的传输时可靠传输-程序员宅基地

文章浏览阅读1.2k次,点赞2次,收藏8次。数据链路层习题自测问题1.数据链路(即逻辑链路)与链路(即物理链路)有何区别?“电路接通了”与”数据链路接通了”的区别何在?2.数据链路层中的链路控制包括哪些功能?试讨论数据链路层做成可靠的链路层有哪些优点和缺点。3.网络适配器的作用是什么?网络适配器工作在哪一层?4.数据链路层的三个基本问题(帧定界、透明传输和差错检测)为什么都必须加以解决?5.如果在数据链路层不进行帧定界,会发生什么问题?6.PPP协议的主要特点是什么?为什么PPP不使用帧的编号?PPP适用于什么情况?为什么PPP协议不_接收方收到链路层数据后,使用crc检验后,余数为0,说明链路层的传输时可靠传输

软件测试工程师移民加拿大_无证移民,未受过软件工程师的教育(第1部分)-程序员宅基地

文章浏览阅读587次。软件测试工程师移民加拿大 无证移民,未受过软件工程师的教育(第1部分) (Undocumented Immigrant With No Education to Software Engineer(Part 1))Before I start, I want you to please bear with me on the way I write, I have very little gen...

随便推点

Thinkpad X250 secure boot failed 启动失败问题解决_安装完系统提示secureboot failure-程序员宅基地

文章浏览阅读304次。Thinkpad X250笔记本电脑,装的是FreeBSD,进入BIOS修改虚拟化配置(其后可能是误设置了安全开机),保存退出后系统无法启动,显示:secure boot failed ,把自己惊出一身冷汗,因为这台笔记本刚好还没开始做备份.....根据错误提示,到bios里面去找相关配置,在Security里面找到了Secure Boot选项,发现果然被设置为Enabled,将其修改为Disabled ,再开机,终于正常启动了。_安装完系统提示secureboot failure

C++如何做字符串分割(5种方法)_c++ 字符串分割-程序员宅基地

文章浏览阅读10w+次,点赞93次,收藏352次。1、用strtok函数进行字符串分割原型: char *strtok(char *str, const char *delim);功能:分解字符串为一组字符串。参数说明:str为要分解的字符串,delim为分隔符字符串。返回值:从str开头开始的一个个被分割的串。当没有被分割的串时则返回NULL。其它:strtok函数线程不安全,可以使用strtok_r替代。示例://借助strtok实现split#include <string.h>#include <stdio.h&_c++ 字符串分割

2013第四届蓝桥杯 C/C++本科A组 真题答案解析_2013年第四届c a组蓝桥杯省赛真题解答-程序员宅基地

文章浏览阅读2.3k次。1 .高斯日记 大数学家高斯有个好习惯:无论如何都要记日记。他的日记有个与众不同的地方,他从不注明年月日,而是用一个整数代替,比如:4210后来人们知道,那个整数就是日期,它表示那一天是高斯出生后的第几天。这或许也是个好习惯,它时时刻刻提醒着主人:日子又过去一天,还有多少时光可以用于浪费呢?高斯出生于:1777年4月30日。在高斯发现的一个重要定理的日记_2013年第四届c a组蓝桥杯省赛真题解答

基于供需算法优化的核极限学习机(KELM)分类算法-程序员宅基地

文章浏览阅读851次,点赞17次,收藏22次。摘要:本文利用供需算法对核极限学习机(KELM)进行优化,并用于分类。

metasploitable2渗透测试_metasploitable2怎么进入-程序员宅基地

文章浏览阅读1.1k次。一、系统弱密码登录1、在kali上执行命令行telnet 192.168.26.1292、Login和password都输入msfadmin3、登录成功,进入系统4、测试如下:二、MySQL弱密码登录:1、在kali上执行mysql –h 192.168.26.129 –u root2、登录成功,进入MySQL系统3、测试效果:三、PostgreSQL弱密码登录1、在Kali上执行psql -h 192.168.26.129 –U post..._metasploitable2怎么进入

Python学习之路:从入门到精通的指南_python人工智能开发从入门到精通pdf-程序员宅基地

文章浏览阅读257次。本文将为初学者提供Python学习的详细指南,从Python的历史、基础语法和数据类型到面向对象编程、模块和库的使用。通过本文,您将能够掌握Python编程的核心概念,为今后的编程学习和实践打下坚实基础。_python人工智能开发从入门到精通pdf

推荐文章

热门文章

相关标签