locust 源代码解析

Locust 是一个开源的python压力测试的框架,代码相对简单,涵盖的东西却不少。 修改起来挺方便,适合学习一个项目。

github: https://github.com/locustio/locust

OptionParser

OptionParser 是一个生成commandline 解析各个参数的库,并能自动生成帮助文件,很强大

基本用法

parser = OptionParser(usage="locust [options] [LocustClass [LocustClass2 ... ]]")
parser.add_option(
        '--loglevel', '-L',
        action='store',
        type='str',
        dest='loglevel',
        default='INFO',
        help="Choose between DEBUG/INFO/WARNING/ERROR/CRITICAL. Default is INFO.",
    )
    

其中action有一组固定的值可供选择,默认是’store ‘,表示将命令行参数值保存在 options 对象里。 store_true 和 store_false ,用于处理带命令行参数后面不 带值的情况。如 -v,-q 等命令行参数:

parser.add_option("-v", action="store_true", dest="verbose")  
parser.add_option("-q", action="store_false", dest="verbose") 

其它的 actions 值还有:store_constappendcountcallback

命令分组

如果程序有很多的命令行参数,你可能想为他们进行分组,这时可以使用 OptonGroup

group = OptionGroup(parser, ``Dangerous Options'',  
                    ``Caution: use these options at your own risk.  ``  
                    ``It is believed that some of them bite.'')  
group.add_option(``-g'', action=''store_true'', help=''Group option.'')  
parser.add_option_group(group)  

下面是将会打印出来的帮助信息:

usage:  [options] arg1 arg2  
  
options:  
  -h, --help           show this help message and exit  
  -v, --verbose        make lots of noise [default]  
  -q, --quiet          be vewwy quiet (I'm hunting wabbits)  
  -fFILE, --file=FILE  write output to FILE  
  -mMODE, --mode=MODE  interaction mode: one of 'novice', 'intermediate'  
                       [default], 'expert'  
  
  Dangerous Options:  
    Caution: use of these options is at your own risk.  It is believed that  
    some of them bite.  
    -g                 Group option. 

显示程序版本

象 usage message 一样,你可以在创建 OptionParser 对象时,指定其 version 参数,用于显示当前程序的版本信息:
parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")
这样,optparse 就会自动解释 –version 命令行参数:

$ /usr/bin/foo --version  
foo 1.0  

处理异常

包括程序异常和用户异常。这里主要讨论的是用户异常,是指因用户输入无效的、不完整的命令行参数而引发的异常。optparse 可以自动探测并处理一些用户异常:

$ /usr/bin/foo -n 4x  
usage: foo [options]  
  
foo: error: option -n: invalid integer value: '4x'  
  
$ /usr/bin/foo -n  
usage: foo [options]  
  
foo: error: -n option requires an argument  

用户也可以使用 parser.error() 方法来自定义部分异常的处理:

(options, args) = parser.parse_args()  
[...]  
if options.a and options.b:  
    parser.error("options -a and -b are mutually exclusive") 

上面的例子,当 -b 和 -b 命令行参数同时存在时,会打印出“options -a and -b are mutually exclusive“,以警告用户。
如果以上的异常处理方法还不能满足要求,你可能需要继承 OptionParser 类,并重载 exit() 和 erro() 方法。

load python 文件

locust 框架是load 你自己写的python 文件并解析的,这个也挺有意思的。 def load_locustfile(path)函数是实现这个目的的, 代码如下:

def load_locustfile(path):
    """
    Import given locustfile path and return (docstring, callables).
    Specifically, the locustfile's ``__doc__`` attribute (a string) and a
    dictionary of ``{'name': callable}`` containing all callables which pass
    the "is a Locust" test.
    """
    # Get directory and locustfile name
    directory, locustfile = os.path.split(path)
    # If the directory isn't in the PYTHONPATH, add it so our import will work
    added_to_path = False
    index = None
    if directory not in sys.path:
        sys.path.insert(0, directory)
        added_to_path = True
    # If the directory IS in the PYTHONPATH, move it to the front temporarily,
    # otherwise other locustfiles -- like Locusts's own -- may scoop the intended
    # one.
    else:
        i = sys.path.index(directory)
        if i != 0:
            # Store index for later restoration
            index = i
            # Add to front, then remove from original position
            sys.path.insert(0, directory)
            del sys.path[i + 1]
    # Perform the import (trimming off the .py)
    imported = __import__(os.path.splitext(locustfile)[0])
    # Remove directory from path if we added it ourselves (just to be neat)
    if added_to_path:
        del sys.path[0]
    # Put back in original index if we moved it
    if index is not None:
        sys.path.insert(index + 1, directory)
        del sys.path[0]
    # Return our two-tuple
    locusts = dict(filter(is_locust, vars(imported).items()))
    return imported.__doc__, locusts

要点是 imported = __import__(os.path.splitext(locustfile)[0]) 导入你写的python 文件, 然后用 locusts = dict(filter(is_locust, vars(imported).items()))进行解析。 导入这个很好理解,vars()函数是python 内置的一个函数,在输入是对象的时候和__dict__ 一致。 这里是用来获得导入模块里面的所有内容的。filter函数也是python 内置的一个函数,用来过滤列表的,很有用哦~

协程 gevent

可以看到locust有一个web端,他是用协程起的
main_greenlet = gevent.spawn(web.start, locust_classes, options)

gevent是第三方库,通过greenlet实现协程,其基本思想是:
当一个greenlet遇到IO操作时,比如访问网络,就自动切换到其他的greenlet,等到IO操作完成,再在适当的时候切换回来继续执行。由于IO操作非常耗时,经常使程序处于等待状态,有了gevent为我们自动切换协程,就保证总有greenlet在运行,而不是等待IO。

gevent 需要自己安装,底层用C写的。协程的概念类似于CPU的中断和轮询,看起来像是多线程,其实只有CPU的一个core 在跑。

协程的好处:

  • 跨平台
  • 跨体系架构
  • 无需线程上下文切换的开销
  • 无需原子操作锁定及同步的开销
  • 方便切换控制流,简化编程模型
  • 高并发+高扩展性+低成本:一个CPU支持上万的协程都不是问题。所以很适合用于高并发处理。

缺点:

  • 无法利用多核资源:协程的本质是个单线程,它不能同时将 单个CPU 的多个核用上,协程- 需要和进程配合才能运行在多CPU上.当然我们日常所编写的绝大部分应用都没有这个必要,除非是cpu密集型应用。
  • 进行阻塞(Blocking)操作(如IO时)会阻塞掉整个程序:这一点和事件驱动一样,可以使用异步IO操作来解决

Event

一个简单event实现,以后可以参考

class EventHook(object):
    """
    Simple event class used to provide hooks for different types of events in Locust.
    Here's how to use the EventHook class::
        my_event = EventHook()
        def on_my_event(a, b, **kw):
            print "Event was fired with arguments: %s, %s" % (a, b)
        my_event += on_my_event
        my_event.fire(a="foo", b="bar")
    """

    def __init__(self):
        self._handlers = []

    def __iadd__(self, handler):
        self._handlers.append(handler)
        return self

    def __isub__(self, handler):
        self._handlers.remove(handler)
        return self

    def fire(self, **kwargs):
        for handler in self._handlers:
            handler(**kwargs)

request_success = EventHook()

core

core.py 文件是locust 数据结构和核心

用decorate去给task加权重

def task(weight=1):
    """
    Used as a convenience decorator to be able to declare tasks for a TaskSet 
    inline in the class. Example::
    
        class ForumPage(TaskSet):
            @task(100)
            def read_thread(self):
                pass
            
            @task(7)
            def create_thread(self):
                pass
    """
    
    def decorator_func(func):
        func.locust_task_weight = weight
        return func
    
    """
    Check if task was used without parentheses (not called), like this::
    
        @task
        def my_task()
            pass
    """
    if callable(weight):
        func = weight
        weight = 1
        return decorator_func(func)
    else:
        return decorator_func

用元类去改造Locust类: 加了一个变量new_tasks,并fuzhi


class TaskSetMeta(type):
    """
    Meta class for the main Locust class. It's used to allow Locust classes to specify task execution 
    ratio using an {task:int} dict, or a [(task0,int), ..., (taskN,int)] list.
    """
    
    def __new__(mcs, classname, bases, classDict):
        new_tasks = []
        for base in bases:
            if hasattr(base, "tasks") and base.tasks:
                new_tasks += base.tasks
        
        if "tasks" in classDict and classDict["tasks"] is not None:
            tasks = classDict["tasks"]
            if isinstance(tasks, dict):
                tasks = six.iteritems(tasks)
            
            for task in tasks:
                if isinstance(task, tuple):
                    task, count = task
                    for i in xrange(0, count):
                        new_tasks.append(task)
                else:
                    new_tasks.append(task)
        
        for item in six.itervalues(classDict):
            if hasattr(item, "locust_task_weight"):
                for i in xrange(0, item.locust_task_weight):
                    new_tasks.append(item)
        
        classDict["tasks"] = new_tasks
        
        return type.__new__(mcs, classname, bases, classDict)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,761评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,953评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,998评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,248评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,130评论 4 356
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,145评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,550评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,236评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,510评论 1 291
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,601评论 2 310
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,376评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,247评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,613评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,911评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,191评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,532评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,739评论 2 335

推荐阅读更多精彩内容