zoukankan      html  css  js  c++  java
  • 【转载】Nginx-Lua模块的执行顺序

    【原文链接】https://www.bbsmax.com/A/o75NjMEx5W/ 

    一、nginx执行步骤

    nginx在处理每一个用户请求时,都是按照若干个不同的阶段依次处理的,与配置文件上的顺序没有关系,详细内容可以阅读《深入理解nginx:模块开发与架构解析》这本书,这里只做简单介绍;

    1、post-read

    读取请求内容阶段,nginx读取并解析完请求头之后就立即开始运行;

    2、server-rewrite

    server请求地址重写阶段;

    3、find-config

    配置查找阶段,用来完成当前请求与location配重块之间的配对工作;

    4、rewrite

    location请求地址重写阶段,当ngx_rewrite指令用于location中,就是再这个阶段运行的;

    5、post-rewrite

    请求地址重写提交阶段,当nginx完成rewrite阶段所要求的内部跳转动作,如果rewrite阶段有这个要求的话;

    6、preaccess

    访问权限检查准备阶段,ngx_limit_req和ngx_limit_zone在这个阶段运行,ngx_limit_req可以控制请求的访问频率,ngx_limit_zone可以控制访问的并发度;

    7、access

    权限检查阶段,ngx_access在这个阶段运行,配置指令多是执行访问控制相关的任务,如检查用户的访问权限,检查用户的来源IP是否合法;

    8、post-access

    访问权限检查提交阶段;

    9、try-files

    配置项try_files处理阶段;

    10、content

    内容产生阶段,是所有请求处理阶段中最为重要的阶段,因为这个阶段的指令通常是用来生成HTTP响应内容的;

    11、log

    日志模块处理阶段;

    二、ngx_lua运行指令

    ngx_lua属于nginx的一部分,它的执行指令都包含在nginx的11个步骤之中了,不过ngx_lua并不是所有阶段都会运行的;

    1、init_by_lua、init_by_lua_file

    语法:init_by_lua <lua-script-str>
    语境:http
    阶段:loading-config
    当nginx master进程在加载nginx配置文件时运行指定的lua脚本,通常用来注册lua的全局变量或在服务器启动时预加载lua模块:
    1. init_by_lua 'cjson = require "cjson"';
    2.  
    3. server {
    4. location = /api {
    5. content_by_lua '
    6. ngx.say(cjson.encode({dog = 5, cat = 6}))
    7. '
    8. }
    9. }

    或者初始化lua_shared_dict共享数据:

    1. lua_shared_dict dogs 1m;
    2. init_by_lua '
    3. local dogs = ngx.shared.dogs;
    4. dogs:set("Tom", 50)
    5. '
    6. server {
    7. location = /api {
    8. content_by_lua '
    9. local dogs = ngx.shared.dogs;
    10. ngx.say(dogs:get("Tom"))
    11. '
    12. }
    13. }

    但是,lua_shared_dict的内容不会在nginx reload时被清除。所以如果你不想在你的init_by_lua中重新初始化共享数据,那么你需要在你的共享内存中设置一个标志位并在init_by_lua中进行检查。

    因为这个阶段的lua代码是在nginx forks出任何worker进程之前运行,数据和代码的加载将享受由操作系统提供的copy-on-write的特性,从而节约了大量的内存。
    不要在这个阶段初始化你的私有lua全局变量,因为使用lua全局变量会照成性能损失,并且可能导致全局命名空间被污染。
    这个阶段只支持一些小的LUA Nginx API设置:ngx.log和print、ngx.shared.DICT;

    2、init_worker_by_lua、init_worker_by_lua_file

    语法:init_worker_by_lua <lua-script-str>
    语境:http
    阶段:starting-worker

    在每个nginx worker进程启动时调用指定的lua代码。如果master 进程不允许,则只会在init_by_lua之后调用。

    这个hook通常用来创建每个工作进程的计时器(通过lua的ngx.timer API),进行后端健康检查或者其它日常工作:
    1. init_worker_by_lua:
    2. local delay = 3 -- in seconds
    3. local new_timer = ngx.timer.at
    4. local log = ngx.log
    5. local ERR = ngx.ERR
    6. local check
    7. check = function(premature)
    8. if not premature then
    9. -- do the health check other routine work
    10. local ok, err = new_timer(delay, check)
    11. if not ok then
    12. log(ERR, "failed to create timer: ", err)
    13. return
    14. end
    15. end
    16. end
    17. local ok, err = new_timer(delay, check)
    18. if not ok then
    19. log(ERR, "failed to create timer: ", err)
    20. end

    3、set_by_lua、set_by_lua_file

    语法:set_by_lua $res <lua-script-str> [$arg1 $arg2 …]

    语境:server、server if、location、location if

    阶段:rewrite

    传入参数到指定的lua脚本代码中执行,并得到返回值到res中。<lua-script-str>中的代码可以使从ngx.arg表中取得输入参数(顺序索引从1开始)。

    这个指令是为了执行短期、快速运行的代码因为运行过程中nginx的事件处理循环是处于阻塞状态的。耗费时间的代码应该被避免。

    禁止在这个阶段使用下面的API:1、output api(ngx.say和ngx.send_headers);2、control api(ngx.exit);3、subrequest api(ngx.location.capture和ngx.location.capture_multi);4、cosocket api(ngx.socket.tcp和ngx.req.socket);5、sleep api(ngx.sleep)

    此外注意,这个指令只能一次写出一个nginx变量,但是使用ngx.var接口可以解决这个问题:

    1. location /foo {
    2. set $diff '';
    3. set_by_lua $num '
    4. local a = 32
    5. local b = 56
    6. ngx.var.diff = a - b; --写入$diff中
    7. return a + b; --返回到$sum中
    8. '
    9. echo "sum = $sum, diff = $diff";
    10. }

    这个指令可以自由的使用HttpRewriteModule、HttpSetMiscModule和HttpArrayVarModule所有的方法。所有的这些指令都将按他们出现在配置文件中的顺序进行执行。

    4、rewrite_by_lua、rewrite_by_lua_file

    语法:rewrite_by_lua <lua-script-str>
    语境:http、server、location、location if
    阶段:rewrite tail

    作为rewrite阶段的处理,为每个请求执行指定的lua代码。注意这个处理是在标准HtpRewriteModule之后进行的:

    1. location /foo {
    2. set $a 12;
    3. set $b "";
    4. rewrite_by_lua 'ngx.var.b = tonumber(ngx.var.a) + 1';
    5. echo "res = $b";
    6. }
    如果这样的话将不会按预期进行工作:
    1. location /foo {
    2. set $a 12;
    3. set $b '';
    4. rewrite_by_lua 'ngx.var.b = tonumber(ngx.var.a) + 1';
    5. if($b = '13') {
    6. rewrite ^ /bar redirect;
    7. break;
    8. }
    9. echo "res = $b"
    10. }

    因为if会在rewrite_by_lua之前运行,所以判断将不成立。正确的写法应该是这样:

    1. location /foo {
    2. set $a 12;
    3. set $b '';
    4. rewrite_by_lua '
    5. ngx.var.b = tonumber(ngx.var.a) + 1
    6. if tonumber(ngx.var.b) == 13 then
    7. return ngx.redirect("/bar");
    8. end
    9. '
    10. echo "res = $b";
    11. }

    注意ngx_eval模块可以近似于使用rewite_by_lua,例如:

    1. location / {
    2. eval $res {
    3. proxy_pass http://foo,com/check-spam;
    4. }
    5. if($res = 'spam') {
    6. rewrite ^ /terms-of-use.html redirect;
    7. }
    8. fastcgi_pass .......
    9. }

    可以被ngx_lua这样实现:

    1. location = /check-spam {
    2. internal;
    3. proxy_pass http://foo.com/check-spam;
    4. }
    5. location / {
    6. rewrite_by_lua '
    7. local res = ngx.location.capture("/check-spam")
    8. if res.body == "spam" then
    9. return ngx.redirect("terms-of-use.html")
    10. '
    11. fastcgi_pass .......
    12. }

    和其它的rewrite阶段的处理程序一样,rewrite_by_lua在subrequests中一样可以运行。

    请注意在rewrite_by_lua内调用ngx.exit(ngx.OK),nginx的请求处理流程将继续进行content阶段的处理。从rewrite_by_lua终止当前的请求,要调用ngx.exit返回status大于200并小于300的成功状态或ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)的失败状态。

    如果HttpRewriteModule的重写指令被用来改写URI和重定向,那么任何rewrite_by_lua和rewrite_by_lua_file的代码将不会执行,例如:

    1. location /foo {
    2. rewrite ^ /bar;
    3. rewrite_by_lua 'ngx.exit(503)'
    4. }
    5. location /bar {
    6. .......
    7. }

    在这个例子中ngx.exit(503)将永远不会被执行,因为rewrite修改了location,请求已经跳入其它location中了。

    5、access_by_lua,access_by_lua_file

    语法:access_by_lua <lua-script-str>
    语境:http,server,location,location if
    阶段:access tail

    为每个请求在访问阶段的调用lua脚本进行处理。主要用于访问控制,能收集到大部分的变量。

    注意access_by_lua和rewrite_by_lua类似是在标准HttpAccessModule之后才会运行,看一个例子:

    1. location / {
    2. deny 192.168.1.1;
    3. allow 192.168.1.0/24;
    4. allow 10.1.1.0/16;
    5. deny all;
    6. access_by_lua '
    7. local res = ngx.location.capture("/mysql", {...})
    8. ....
    9. '
    10. }

    如果client ip在黑名单之内,那么这次连接会在进入access_by_lua调用的mysql之前被丢弃掉。

    ngx_auth_request模块和access_by_lua的用法类似:

    1. location / {
    2. auth_request /auth;
    3. }

    可以用ngx_lua这么实现:

    1. location / {
    2. access_by_lua '
    3. local res = ngx.location.capture("/auth")
    4. if res.status == ngx.HTTP_OK then
    5. return
    6. end
    7. if res.status == ngx.HTTP_FORBIDDEN then
    8. ngx.exit(res.status)
    9. end
    10. ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
    11. '
    12. }
    和其它access阶段的模块一样,access_by_lua不会在subrequest中运行。
    请注意在access_by_lua内调用ngx.exit(ngx.OK),nginx的请求处理流程将继续进行后面阶段的处理。从rewrite_by_lua终止当前的请求,要调用ngx.exit返回status大于200并小于300的成功状态或ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)的失败状态。

    6、content_by_lua,content_by_lua_file

    语法:content_by_lua <lua-script-str>
    语境:location,location if
    阶段:content

    作为“content handler”为每个请求执行lua代码,为请求者输出响应内容。

    不要将它和其它的内容处理指令在同一个location内使用如proxy_pass。

    7、header_filter_by_lua,header_filter_by_lua_file

    语法:header_filter_by_lua <lua-script-str>
    语境:http,server,location,location if
    阶段:output-header-filter

    一般用来设置cookie和headers,在该阶段不能使用如下几个API:

    1、output API(ngx.say和ngx.send_headers)
    2、control API(ngx.exit和ngx.exec)
    3、subrequest API(ngx.location.capture和ngx.location.capture_multi)
    4、cosocket API(ngx.socket.tcp和ngx.req.socket)
    有一个例子是 在你的lua header filter里添加一个响应头标头:
    1. location / {
    2. proxy_pass http://mybackend;
    3. header_filter_by_lua 'ngx.header.Foo = "blah"';
    4. }

    8、body_filter_by_lua,body_filter_by_lua_file

    语法:body_filter_by_lua <lua-script-str>
    语境:http,server,location,location if
    阶段:output-body-filter

    输入的数据时通过ngx.arg[1](作为lua的string值),通过ngx.arg[2]这个bool类型表示响应数据流的结尾。

    基于这个原因,‘eof’只是nginx的链接缓冲区的last_buf(对主requests)或last_in_chain(对subrequests)的标记。
    运行以下命令可以立即终止运行接下来的lua代码:
    return ngx.ERROR
    这会将响应体截断导致无效的响应。lua代码可以通过修改ngx.arg[1]的内容将数据传输到下游的nginx output body filter阶段的其它模块中去。例如,将response body中的小写字母进行反转,我们可以这么写:
    1. location / {
    2. proxy_pass http://mybackend;
    3. body_filter_by_lua 'ngx.arg[1] = string.upper(ngx.arg[1])'
    4. }

    当将ngx.arg[1]设置为nil或者一个空的lua string时,下游的模块将不会收到数据了。

    同样可以通过修改ngx.arg[2]来设置新的”eof“标记,例如:

    1. location /t {
    2. echo hello world;
    3. echo hiya globe;
    4. body_filter_by_lua '
    5. local chunk = ngx.arg[1]
    6. if string.match(chunk, "hello") then
    7. ngx.arg[2] = true --new eof
    8. return
    9. end
    10. --just throw away any remaining chunk data
    11. ngx.arg[1] = nil
    12. '
    13. }

    那么GET /t的请求只会回复:hello world

    这是因为,当body filter看到了一块包含”hello“的字符块后立即将”eof“标记设置为了true,从而导致响应被截断了但仍然是有效的回复。
    当lua代码中改变了响应体的长度时,应该要清除content-length响应头部的值,例如:
    1. location /foo {
    2. header_filter_by_lua 'ngx.header.content_length = nil'
    3. body_filter_by_lua 'ngx.arg[1] = string.len(ngx.arg[1]) .. "\n"'
    4. }
    在该阶段不能使用如下几个API:
    1、output API(ngx.say和ngx.send_headers)
    2、control API(ngx.exit和ngx.exec)
    3、subrequest API(ngx.location.capture和ngx.location.capture_multi)
    4、cosocket API(ngx.socket.tcp和ngx.req.socket)
    nginx output filters可能会在一次请求中被多次调用,因为响应体可能是以chunks方式传输的。因此这个指令一般会在一次请求中被调用多次。

    9、log_by_lua,log_by_lua_file

    语法:log_by_lua <lua-script-str>
    语境:http,server,location,location if
    阶段:log

    在log阶段调用指定的lua脚本,并不会替换access log,而是在那之后进行调用。

    在该阶段不能使用如下几个API:
    1、output API(ngx.say和ngx.send_headers)
    2、control API(ngx.exit和ngx.exec)
    3、subrequest API(ngx.location.capture和ngx.location.capture_multi)
    4、cosocket API(ngx.socket.tcp和ngx.req.socket)

    一个收集upstream_response_time的平均数据的例子:

      1. lua_shared_dict log_dict 5M
      2.  
      3. server{
      4. location / {
      5. proxy_pass http;//mybackend
      6. log_by_lua '
      7. local log_dict = ngx.shared.log_dict
      8. local upstream_time = tonumber(ngx.var.upstream_response_time)
      9. local sum = log_dict:get("upstream_time-sum") or 0
      10. sum = sum + upstream_time
      11. log_dict:set("upsteam_time-sum", sum)
      12. local newval, err = log_dict:incr("upstream_time-nb", 1)
      13. if not newval and err == "not found" then
      14. log_dict:add("upstream_time-nb", 0)
      15. log_dict:incr("upstream_time-nb", 1)
      16. end
      17. '
      18. }
      19. location = /status {
      20. content_by_lua '
      21. local log_dict = ngx.shared.log_dict
      22. local sum = log_dict:get("upstream_time-sum")
      23. local nb = log_dict:get("upstream_time-nb")
      24.  
      25. if nb and sum then
      26. ngx.say("average upstream response time: ", sum/nb, " (", nb, " reqs)")
      27. else
      28. ngx.say("no data yet")
      29. end
      30. '
      31. }
      32. }

        转自:http://www.mrhaoting.com/?p=157
  • 相关阅读:
    php总结4——数组的定义及函数、冒泡排序
    php总结3——基本函数、流程控制中的循环
    php总结2——php中的变量、数据类型及转换、运算符、流程控制中的分支结构
    php总结1 ——php简介、工作原理、运行环境、文件构成、语法结构、注释
    php中$t=date()函数参数意义及时间更改
    80端口未被占用,apache无法启动,命令行运行httpd.exe提示文档内容有错
    创建node.js一个简单的应用实例
    windows系统下nodejs、npm、express的下载和安装教程——2016.11.09
    前端工程师必备技能
    用于string对象中字符截取的几种函数总结——语法、参数意义及用途举例
  • 原文地址:https://www.cnblogs.com/zhonghuahero/p/9513858.html
Copyright © 2011-2022 走看看