深入理解nginx连接数限制模块[下]

60 篇文章 1 订阅
55 篇文章 0 订阅
本文详细解析了Nginx的limit_conn_module模块,涉及配置指令、共享内存初始化、红黑树查找以及请求处理中的连接数限制逻辑。重点介绍了limit_conn_zone指令、limit_conn配置、log_level和status_code设置,以及请求关闭时的析构函数实现。
摘要由CSDN通过智能技术生成

关注我的微信公众号:
描述

上接 深入理解nginx连接数限制模块

4 源码分析

   ngx_http_limit_con_module模块和ngx_http_limit_req_module的实现原理是很象的,甚至包括配置参数也几乎一致,但是相比于后者,本模块实现起来更简单,因为它不需要漏桶算法,只要统计某个key对应的连接数,如果超过限定的值就拒绝请求即可。下面先从配置指令开始分析。关于ngx_http_limit_req_module的实现原理可以查看深入理解nginx的请求限速模块

4.1 配置指令源码分析

4.1.1 limit_conn_zone

    { ngx_string("limit_conn_zone"),
      NGX_HTTP_MAIN_CONF|NGX_CONF_TAKE2,
      ngx_http_limit_conn_zone,
      0,
      0,
      NULL },

  本模块通过以上代码在nginx配置文件的http块中定义了一个limit_conn_zone的配置指令,由ngx_http_limit_conn_zone解析函数进行解析。

  ngx_http_limit_conn_zone的实现代码就是分析配置指令,解析出用于连接限速的查询key(动态变量),并且根据配置的zone信息来创建一个共享内存缓冲区,创建的贡共享内存缓冲区用来存储key值对应的连接数的统计值。

static char *
ngx_http_limit_conn_zone(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
    u_char                            *p;
    ssize_t                            size;
    ngx_str_t                         *value, name, s;
    ngx_uint_t                         i;
    ngx_shm_zone_t                    *shm_zone;
    ngx_http_limit_conn_ctx_t         *ctx;
    ngx_http_compile_complex_value_t   ccv;

    value = cf->args->elts;

	/* 创建配置上下文 */
    ctx = ngx_pcalloc(cf->pool, sizeof(ngx_http_limit_conn_ctx_t));
    if (ctx == NULL) {
        return NGX_CONF_ERROR;
    }

    ngx_memzero(&ccv, sizeof(ngx_http_compile_complex_value_t));

    ccv.cf = cf;
    ccv.value = &value[1];
    ccv.complex_value = &ctx->key;

    if (ngx_http_compile_complex_value(&ccv) != NGX_OK) {
        return NGX_CONF_ERROR;
    }

    ......

	/* 解析共享内存zone的配置 */
	
	/* 创建一个共享内存缓冲区 */
    shm_zone = ngx_shared_memory_add(cf, &name, size,
                                     &ngx_http_limit_conn_module);
    if (shm_zone == NULL) {
        return NGX_CONF_ERROR;
    }

    if (shm_zone->data) {
        ctx = shm_zone->data;

        ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
                           "%V \"%V\" is already bound to key \"%V\"",
                           &cmd->name, &name, &ctx->key.value);
        return NGX_CONF_ERROR;
    }

    shm_zone->init = ngx_http_limit_conn_init_zone;
    shm_zone->data = ctx;

    return NGX_CONF_OK;
}

4.1.2 limit_conn

    { ngx_string("limit_conn"),
      NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_TAKE2,
      ngx_http_limit_conn,
      NGX_HTTP_LOC_CONF_OFFSET,
      0,
      NULL },

  本模块通过以上代码在nginx配置文件的http/server/location块中定义了一个limit_conn的配置指令,由ngx_http_limit_conn解析函数进行解析。通过定义这个指令,最终在location级别开启连接数限制功能。
  本模块和ngx_http_limit_req_module一样,也允许配置多个limit_conn指令,这样子本模块在请求进来的时候,会依次遍历所有的限制规则进行连接数限制处理。
  以下是实现源码,里面进行了详细的注释:

static char *
ngx_http_limit_conn(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
    ngx_shm_zone_t               *shm_zone;
    ngx_http_limit_conn_conf_t   *lccf = conf;
    ngx_http_limit_conn_limit_t  *limit, *limits;

    ngx_str_t  *value;
    ngx_int_t   n;
    ngx_uint_t  i;

    value = cf->args->elts;
	
	/* 在ngx_http_limit_conn_zone里面已经添加了, 这里获取共享内存区对象 */
    shm_zone = ngx_shared_memory_add(cf, &value[1], 0,
                                     &ngx_http_limit_conn_module);
    if (shm_zone == NULL) {
        return NGX_CONF_ERROR;
    }
    
	/* 获取连接数限制规则数组,如果没有创建则重建一个新的 */
    limits = lccf->limits.elts;

    if (limits == NULL) {
        if (ngx_array_init(&lccf->limits, cf->pool, 1,
                           sizeof(ngx_http_limit_conn_limit_t))
            != NGX_OK)
        {
            return NGX_CONF_ERROR;
        }
    }

	/* 如果当前配置的规则的zone之前的规则已经用过了,则报配置重复错误 */
    for (i = 0; i < lccf->limits.nelts; i++) {
        if (shm_zone == limits[i].shm_zone) {
            return "is duplicate";
        }
    }

	/* 分析连接限制的数量,最大是65535  */
    n = ngx_atoi(value[2].data, value[2].len);
    if (n <= 0) {
        ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
                           "invalid number of connections \"%V\"", &value[2]);
        return NGX_CONF_ERROR;
    }

    if (n > 65535) {
        ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
                           "connection limit must be less 65536");
        return NGX_CONF_ERROR;
    }

	/* 将限制规则添加到规则数组中 */
    limit = ngx_array_push(&lccf->limits);
    if (limit == NULL) {
        return NGX_CONF_ERROR;
    }

    limit->conn = n;
    limit->shm_zone = shm_zone;

    return NGX_CONF_OK;
}

4.1.3 limit_conn_log_level

    { ngx_string("limit_conn_log_level"),
      NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_TAKE1,
      ngx_conf_set_enum_slot,
      NGX_HTTP_LOC_CONF_OFFSET,
      offsetof(ngx_http_limit_conn_conf_t, log_level),
      &ngx_http_limit_conn_log_levels },

   本模块通过limit_conn_log_level指令定义了写限制事件日志的日志级别。

4.1.4 limit_conn_status

    { ngx_string("limit_conn_status"),
      NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_TAKE1,
      ngx_conf_set_num_slot,
      NGX_HTTP_LOC_CONF_OFFSET,
      offsetof(ngx_http_limit_conn_conf_t, status_code),
      &ngx_http_limit_conn_status_bounds },

  本模块通过limit_conn_status指令定义了发生连接数限制事件的时候给客户端响应的错误码,默认是503。

4.1.5 limit_conn_dry_run

    { ngx_string("limit_conn_dry_run"),
      NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_FLAG,
      ngx_conf_set_flag_slot,
      NGX_HTTP_LOC_CONF_OFFSET,
      offsetof(ngx_http_limit_conn_conf_t, dry_run),
      NULL },

  本模块通过limit_conn_dry_run指令设置仅记录日志而不实际限制连接的标记。

4.2 共享内存初始化

  在4.1.1节中的ngx_http_limit_conn_zone函数中创建共享内存的时候设置了共享内存初始化回调函数ngx_http_limit_conn_init_zone,该函数的任务在共享内存池中初始化一棵红黑树,用来记录连接统计值。

static ngx_int_t
ngx_http_limit_conn_init_zone(ngx_shm_zone_t *shm_zone, void *data)
{
    ngx_http_limit_conn_ctx_t  *octx = data;

    size_t                      len;
    ngx_http_limit_conn_ctx_t  *ctx;

    ctx = shm_zone->data;

    if (octx) {
	    /* 这里的逻辑用来在reload的时候复用原来的共享内存池 */
        if (ctx->key.value.len != octx->key.value.len
            || ngx_strncmp(ctx->key.value.data, octx->key.value.data,
                           ctx->key.value.len)
               != 0)
        {
            ngx_log_error(NGX_LOG_EMERG, shm_zone->shm.log, 0,
                          "limit_conn_zone \"%V\" uses the \"%V\" key "
                          "while previously it used the \"%V\" key",
                          &shm_zone->shm.name, &ctx->key.value,
                          &octx->key.value);
            return NGX_ERROR;
        }

        ctx->sh = octx->sh;
        ctx->shpool = octx->shpool;

        return NGX_OK;
    }

	/* 获取共享内存池的地址 */
    ctx->shpool = (ngx_slab_pool_t *) shm_zone->shm.addr;

    if (shm_zone->shm.exists) {
		/* 这个似乎也只有windows的环境才会进入这个分支了 */
		ctx->sh = ctx->shpool->data;

        return NGX_OK;
    }

	/* 在共享内存池中分配 */
    ctx->sh = ngx_slab_alloc(ctx->shpool, sizeof(ngx_http_limit_conn_shctx_t));
    if (ctx->sh == NULL) {
        return NGX_ERROR;
    }

    ctx->shpool->data = ctx->sh;

	/* 初始化红黑树 */
    ngx_rbtree_init(&ctx->sh->rbtree, &ctx->sh->sentinel,
                    ngx_http_limit_conn_rbtree_insert_value);

    len = sizeof(" in limit_conn_zone \"\"") + shm_zone->shm.name.len;

    ctx->shpool->log_ctx = ngx_slab_alloc(ctx->shpool, len);
    if (ctx->shpool->log_ctx == NULL) {
        return NGX_ERROR;
    }

    ngx_sprintf(ctx->shpool->log_ctx, " in limit_conn_zone \"%V\"%Z",
                &shm_zone->shm.name);

    return NGX_OK;
}

4.3 模块初始化

  模块初始化是在配置文件解析结束后,pstconfiguration阶段由nginx回调的,本模块是由ngx_http_limit_conn_init来处理,实现如下:

static ngx_int_t
ngx_http_limit_conn_init(ngx_conf_t *cf)
{
    ngx_http_handler_pt        *h;
    ngx_http_core_main_conf_t  *cmcf;

    cmcf = ngx_http_conf_get_module_main_conf(cf, ngx_http_core_module);

    h = ngx_array_push(&cmcf->phases[NGX_HTTP_PREACCESS_PHASE].handlers);
    if (h == NULL) {
        return NGX_ERROR;
    }

    *h = ngx_http_limit_conn_handler;

    return NGX_OK;
}

  也和ngx_http_limit_req_module一样,在NGX_HTTP_PREACCESS_PHASE阶段配置了一个回调函数用来对请求进行拦截处理,设置的回调函数是:ngx_http_limit_conn_handler。

4.4 请求处理

  当nginx收到请求的时候,会在NGX_HTTP_PREACCESS_PHASE阶段调用ngx_http_limit_conn_handler函数,ngx_http_limit_conn_handler函数的实现比较直白,就是遍历配置好的限制规则,先计算得到配置的动态key值,然后用这个key值查找共享内存中的红黑树得到连接统计值,最后根据配置的连接限制数与统计值比较判断是否要进行限制操作。源码实现如下:

static ngx_int_t
ngx_http_limit_conn_handler(ngx_http_request_t *r)
{
    size_t                          n;
    uint32_t                        hash;
    ngx_str_t                       key;
    ngx_uint_t                      i;
    ngx_rbtree_node_t              *node;
    ngx_pool_cleanup_t             *cln;
    ngx_http_limit_conn_ctx_t      *ctx;
    ngx_http_limit_conn_node_t     *lc;
    ngx_http_limit_conn_conf_t     *lccf;
    ngx_http_limit_conn_limit_t    *limits;
    ngx_http_limit_conn_cleanup_t  *lccln;

    if (r->main->limit_conn_status) {
        return NGX_DECLINED;
    }

    lccf = ngx_http_get_module_loc_conf(r, ngx_http_limit_conn_module);
    limits = lccf->limits.elts;

    for (i = 0; i < lccf->limits.nelts; i++) {
        ctx = limits[i].shm_zone->data;

		/* 求解红黑树查找的关键字,照理是每次循环得到的是相同的值,感觉放在循环外面比较好 */
        if (ngx_http_complex_value(r, &ctx->key, &key) != NGX_OK) {
            return NGX_HTTP_INTERNAL_SERVER_ERROR;
        }

        if (key.len == 0) {
            continue;
        }

        if (key.len > 255) {
            ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
                          "the value of the \"%V\" key "
                          "is more than 255 bytes: \"%V\"",
                          &ctx->key.value, &key);
            continue;
        }

        r->main->limit_conn_status = NGX_HTTP_LIMIT_CONN_PASSED;

		/* 计算查找红黑树的哈希值 */*=
        hash = ngx_crc32_short(key.data, key.len);

        ngx_shmtx_lock(&ctx->shpool->mutex);

		/* 在红黑树中进行查找 */
        node = ngx_http_limit_conn_lookup(&ctx->sh->rbtree, &key, hash);

        if (node == NULL) {
        
			/* 红黑树中没有查到,则需要分配一个新的红黑树节点 */
            n = offsetof(ngx_rbtree_node_t, color)
                + offsetof(ngx_http_limit_conn_node_t, data)
                + key.len;

            node = ngx_slab_alloc_locked(ctx->shpool, n);

            if (node == NULL) {
                ngx_shmtx_unlock(&ctx->shpool->mutex);
                ngx_http_limit_conn_cleanup_all(r->pool);

                if (lccf->dry_run) {
                    r->main->limit_conn_status =
                                          NGX_HTTP_LIMIT_CONN_REJECTED_DRY_RUN;
                    return NGX_DECLINED;
                }

                r->main->limit_conn_status = NGX_HTTP_LIMIT_CONN_REJECTED;

                return lccf->status_code;
            }

            lc = (ngx_http_limit_conn_node_t *) &node->color;

            node->key = hash;
            lc->len = (u_char) key.len;
            lc->conn = 1;     /* 这是该key对应的第一个连接 */
            ngx_memcpy(lc->data, key.data, key.len);
            
			/* 将新的节点插入到红黑树中 */
            ngx_rbtree_insert(&ctx->sh->rbtree, node);

        } else {
        
			/* 如果红黑树中找到了对应的节点,则得到该节点设置好的连接统计信息 */
            lc = (ngx_http_limit_conn_node_t *) &node->color;

            if ((ngx_uint_t) lc->conn >= limits[i].conn) {

				/* 如果连接数超高了限制,那么需要打印日志
				   如果没有开启dry_run,那么就向客户端响应错误代码
				 */
                ngx_shmtx_unlock(&ctx->shpool->mutex);

                ngx_log_error(lccf->log_level, r->connection->log, 0,
                              "limiting connections%s by zone \"%V\"",
                              lccf->dry_run ? ", dry run," : "",
                              &limits[i].shm_zone->shm.name);

                ngx_http_limit_conn_cleanup_all(r->pool);

                if (lccf->dry_run) {
                    r->main->limit_conn_status =
                                          NGX_HTTP_LIMIT_CONN_REJECTED_DRY_RUN;
                    return NGX_DECLINED;
                }

                r->main->limit_conn_status = NGX_HTTP_LIMIT_CONN_REJECTED;

                return lccf->status_code;
            }

            lc->conn++;
        }

        ngx_log_debug2(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                       "limit conn: %08Xi %d", node->key, lc->conn);

        ngx_shmtx_unlock(&ctx->shpool->mutex);

		/* 这里设置一个析构函数,用来在当前的请求对象内存池被释放前,
		   将共享内存区中对应的该key节点的连接数减去1
		 */
        cln = ngx_pool_cleanup_add(r->pool,
                                   sizeof(ngx_http_limit_conn_cleanup_t));
        if (cln == NULL) {
            return NGX_HTTP_INTERNAL_SERVER_ERROR;
        }

        cln->handler = ngx_http_limit_conn_cleanup;
        lccln = cln->data;    /* 设置析构函数的上下文信息 */

        lccln->shm_zone = limits[i].shm_zone;
        lccln->node = node;
    }

    return NGX_DECLINED;
}

  在以上函数中,由于是对共享内存中的数据进行操作,所以需要使用加锁和解锁操作,即ngx_shmtx_lock和ngx_shmtx_unlock。这两个函数的具体解释可以查看:nginx读写锁的实现逻辑

4.5 红黑树的查找

  在4.4节中用到了ngx_http_limit_conn_lookup函数,用来在红黑树中查找当前的key对应的连接统计信息,红黑树的查找就是普通的二叉查找树的遍历,源码如下,不做过多解释:

static ngx_rbtree_node_t *
ngx_http_limit_conn_lookup(ngx_rbtree_t *rbtree, ngx_str_t *key, uint32_t hash)
{
    ngx_int_t                    rc;
    ngx_rbtree_node_t           *node, *sentinel;
    ngx_http_limit_conn_node_t  *lcn;

    node = rbtree->root;
    sentinel = rbtree->sentinel;

    while (node != sentinel) {

        if (hash < node->key) {
            node = node->left;
            continue;
        }

        if (hash > node->key) {
            node = node->right;
            continue;
        }

        /* hash == node->key */

        lcn = (ngx_http_limit_conn_node_t *) &node->color;

        rc = ngx_memn2cmp(key->data, lcn->data, key->len, (size_t) lcn->len);

        if (rc == 0) {
            return node;
        }

        node = (rc < 0) ? node->left : node->right;
    }

    return NULL;
}

4.6 请求关闭的析构函数

  在4.4节中,我们设置了一个析构函数ngx_http_limit_conn_cleanup,用来在当前的nginx请求对象内存池被释放之前,进行析构处理,确保连接数的增加和减少动作能够一一对应,实现代码如下:

static void
ngx_http_limit_conn_cleanup(void *data)
{
    ngx_http_limit_conn_cleanup_t  *lccln = data;

    ngx_rbtree_node_t           *node;
    ngx_http_limit_conn_ctx_t   *ctx;
    ngx_http_limit_conn_node_t  *lc;

    ctx = lccln->shm_zone->data;
    node = lccln->node;
    lc = (ngx_http_limit_conn_node_t *) &node->color;

    ngx_shmtx_lock(&ctx->shpool->mutex);

    ngx_log_debug2(NGX_LOG_DEBUG_HTTP, lccln->shm_zone->shm.log, 0,
                   "limit conn cleanup: %08Xi %d", node->key, lc->conn);

	/* 将连接数-1 */
    lc->conn--;

    if (lc->conn == 0) {
        ngx_rbtree_delete(&ctx->sh->rbtree, node);
        ngx_slab_free_locked(ctx->shpool, node);
    }

    ngx_shmtx_unlock(&ctx->shpool->mutex);
}
  • 26
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码农心语

您的鼓励是我写作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值