• apache后台cgi挂掉之后现场还原


    一、apache的实现
    对于apache的实现,默认配置的时候是不支持cgi模式的,这里的cgi模式就是cgid_mod的加载。如果没有加载该模块,当把该文件放入cgi_bin文件之后,从浏览器获得该文件的时候,httpd并不是执行该文件并将文件的输出返回,有意思的是,浏览器将会直接将请求的cgi文件整个下载下来。这里只是描述了现象,具体的细节分析还是比较周折的,所以暂时就不展开了。
    二、cgid的模式
    等待操作
    (gdb) bt
    #0  0x0095a424 in __kernel_vsyscall ()
    #1  0x003990d1 in accept () from /lib/libpthread.so.0
    #2  0x0016a41b in cgid_server (data=0x80f3ea8) at mod_cgid.c:686
    #3  0x0016ad46 in cgid_start (p=0x80cf0a8, main_server=0x80f3ea8, 
        procnew=0x80eebe8) at mod_cgid.c:876
    #4  0x0016b06c in cgid_init (p=0x80cf0a8, plog=0x812faa0, ptemp=0x8133ab0, 
        main_server=0x80f3ea8) at mod_cgid.c:939
    #5  0x0808ab6f in ap_run_post_config (pconf=0x80cf0a8, plog=0x812faa0, 
        ptemp=0x8133ab0, s=0x80f3ea8) at config.c:105
    #6  0x08068e41 in main (argc=2, argv=0xbffff3b4) at main.c:765
    (gdb) 
      │   │   └─gdb,23680 -p 23597
      │   │       └─httpd,23903 -X 整个是主进程,也就是在命令行中启动的 httpd进程
      │   │           ├─httpd,23904 -X 整个就是我们所熟悉的cgid进程,大家看cgid模块的代码可以知道,cgid是会以单独的进程形式存在的,或者更加形而上的说,它是通过fork创建的新进程
      │   │           │   ├─first.pl,23951 /usr/local/apache2/cgi-bin/first.pl
      │   │           │   ├─first.pl,23959 /usr/local/apache2/cgi-bin/first.pl
      │   │           │   ├─first.pl,23976 /usr/local/apache2/cgi-bin/first.pl
      │   │           │   └─mysleeper,23975

    (gdb) bt
    #0  0x0095a424 in __kernel_vsyscall ()
    #1  0x003990d1 in accept () from /lib/libpthread.so.0 cgid成为单独进程之后,它在一个和主进程预定好的unix socket上执行accept操作,等待不同的worker 进程connect过来,connect过来的进程将请求的内容发送给cgid,cgid然后fork出一个子进程,该进程就是cgi中指定的可执行文件,然后此时cgid的接入功能就算完成了,此时worker进程和新创建的cgi进程之间就可以通过socket来交互了,因为此时worker线程的socket端经过cgid的accept已经转给了真正的cgi进程,它们已经联通,此时从cgid从整个事件中退出
    #2  0x0016a41b in cgid_server (data=0x80f3ea8) at mod_cgid.c:686
    #3  0x0016ad46 in cgid_start (p=0x80cf0a8, main_server=0x80f3ea8, 
        procnew=0x80eebe8) at mod_cgid.c:876
    #4  0x0016b06c in cgid_init (p=0x80cf0a8, plog=0x812faa0, ptemp=0x8133ab0, 
        main_server=0x80f3ea8) at mod_cgid.c:939
    #5  0x0808ab6f in ap_run_post_config (pconf=0x80cf0a8, plog=0x812faa0, 
        ptemp=0x8133ab0, s=0x80f3ea8) at config.c:105
    #6  0x08068e41 in main (argc=2, argv=0xbffff3b4) at main.c:765
    (gdb) 
    (gdb) info thread
    * 1 Thread 0xb7fe79c0 (LWP 23904)  0x0095a424 in __kernel_vsyscall ()
    (gdb) 

    cgi的操作
    (gdb) bt
    #0  0x0039b514 in fork () from /lib/libpthread.so.0
    #1  0x0028bef4 in apr_proc_create (new=0x81aff60, 
        progname=0x81b00b0 "/usr/local/apache2/cgi-bin/mysleeper", args=0x81b0a20, 
        env=0x81b00f8, attr=0x81b06b0, pool=0x81afd68)
        at threadproc/unix/proc.c:391
    #2  0x0016ab3c in cgid_server (data=0x80f3ea8) at mod_cgid.c:817
    #3  0x0016ad46 in cgid_start (p=0x80cf0a8, main_server=0x80f3ea8, 
        procnew=0x80eebe8) at mod_cgid.c:876
    #4  0x0016b06c in cgid_init (p=0x80cf0a8, plog=0x812faa0, ptemp=0x8133ab0, 
        main_server=0x80f3ea8) at mod_cgid.c:939
    #5  0x0808ab6f in ap_run_post_config (pconf=0x80cf0a8, plog=0x812faa0, 
        ptemp=0x8133ab0, s=0x80f3ea8) at config.c:105
    #6  0x08068e41 in main (argc=2, argv=0xbffff3b4) at main.c:765
    (gdb) 
    httpd-2.4.2modulesgeneratorsmod_cgid.c
    static apr_status_t handle_exec(include_ctx_t *ctx, ap_filter_t *f,
                                    apr_bucket_brigade *bb)
    static int cgid_handler(request_rec *r)
    {
        int retval, nph, dbpos;
    三、cgi进程退出之后谁来执行子进程的waitpid操作
    例如说,cgi不小心自己挂掉了,比方说coredump了,此时前台将会如何处理呢?行为未定义不是答案。
    SigQ:    0/8192
    SigPnd:    0000000000000000
    ShdPnd:    0000000000000000
    SigBlk:    0000000000000000
    SigIgn:    0000000001011000 这里父进程是直接忽略了子进程的退出
    SigCgt:    0000000180000001
    CapInh:    0000000000000000
    CapPrm:    0000000000000000
    CapEff:    0000000000000000
    CapBnd:    ffffffffffffffff
    Cpus_allowed:    1
    Cpus_allowed_list:    0
    Mems_allowed:    1
    Mems_allowed_list:    0
    voluntary_ctxt_switches:    199
    nonvoluntary_ctxt_switches:    15
    [root@Harry ~]# kill -l
     1) SIGHUP     2) SIGINT     3) SIGQUIT     4) SIGILL     5) SIGTRAP
     6) SIGABRT     7) SIGBUS     8) SIGFPE     9) SIGKILL    10) SIGUSR1
    11) SIGSEGV    12) SIGUSR2    13) SIGPIPE    14) SIGALRM    15) SIGTERM
    16) SIGSTKFLT    17) SIGCHLD    18) SIGCONT    19) SIGSTOP    20) SIGTSTP
    21) SIGTTIN    22) SIGTTOU    23) SIGURG    24) SIGXCPU    25) SIGXFSZ
    26) SIGVTALRM    27) SIGPROF    28) SIGWINCH    29) SIGIO    30) SIGPWR
    31) SIGSYS    34) SIGRTMIN    35) SIGRTMIN+1    36) SIGRTMIN+2    37) SIGRTMIN+3
    38) SIGRTMIN+4    39) SIGRTMIN+5    40) SIGRTMIN+6    41) SIGRTMIN+7    42) SIGRTMIN+8
    43) SIGRTMIN+9    44) SIGRTMIN+10    45) SIGRTMIN+11    46) SIGRTMIN+12    47) SIGRTMIN+13
    48) SIGRTMIN+14    49) SIGRTMIN+15    50) SIGRTMAX-14    51) SIGRTMAX-13    52) SIGRTMAX-12
    53) SIGRTMAX-11    54) SIGRTMAX-10    55) SIGRTMAX-9    56) SIGRTMAX-8    57) SIGRTMAX-7
    58) SIGRTMAX-6    59) SIGRTMAX-5    60) SIGRTMAX-4    61) SIGRTMAX-3    62) SIGRTMAX-2
    63) SIGRTMAX-1    64) SIGRTMAX    
    [root@Harry ~]# 
    也就是cgid直接忽略了子进程的退出,从而由内核直接回收掉进程,而不用等待子进程被用户态回收。当然此时我可以找到内核的相关代码证明给大家看,就像《加州招待所》中所唱的:light up the candle and she show me the way,但是这个太平常了所以就不摘录了。
    四、cgi 不行coredump之后如何处理
    从上面可以看到,子进程的生死是没有人介意的,但是用户在意,因为用户在等待这个cgi的返回,并且worker线程也在等待这个cgi的返回。等待者如何被唤醒呢?这个比较简单,因为进程退出之后,内核会关闭进程打开的所有文件,而对于socket来说,如果有人在该socket上执行read操作,那么此时这个痴情者将会被唤醒,所以它不用等待子进程的SIGCHILD的唤醒就可以醒过来。
    此时进程被唤醒之后,它一定还处于非常懵懂的状态,就好像你早上正睡得很香,突然在你窗口放一个铁桶,然后在里面放一串1W响的鞭炮一样,从震惊中醒来。此时worker像正常的被唤醒一样去检测cgi的返回,就像你被吵醒了之后依然正常去上班一样。此时扫描cgi输出的直接接口为httpd-2.4.2serverutil_script.c
    AP_DECLARE(int) ap_scan_script_header_err_core_ex(request_rec *r, char *buffer,
                                           int (*getsfunc) (char *, int, void *),
                                           void *getsfunc_data,
                                           int module_index)
        while (1) {

            int rv = (*getsfunc) (w, MAX_STRING_LEN - 1, getsfunc_data); 此时虽然文件关闭,但是cgi没有输出,此时扫描cgi输出的脚本长度为零,走到下面的输出就会返回HTTP_INTERNAL_SERVER_ERROR错误,这个错误在httpd中对应的内容为
    #define HTTP_INTERNAL_SERVER_ERROR         500

            if (rv == 0) {
                const char *msg = "Premature end of script headers";
                if (first_header)
                    msg = "End of script output before headers";
                ap_log_rerror(SCRIPT_LOG_MARK, APLOG_ERR|APLOG_TOCLIENT, 0, r,
                              "%s: %s", msg,
                              apr_filepath_name_get(r->filename));
                return HTTP_INTERNAL_SERVER_ERROR;
            }
            else if (rv == -1) {
                ap_log_rerror(SCRIPT_LOG_MARK, APLOG_ERR|APLOG_TOCLIENT, 0, r,
                              "Script timed out before returning headers: %s",
                              apr_filepath_name_get(r->filename));
                return HTTP_GATEWAY_TIME_OUT;
            }
    此时apache server的配置中给出了这种情况发生了之后你可以执行的操作,但是这个配置默认是被注释掉的,其内容为
        409 # Some examples:
        410 #ErrorDocument 500 "The server made a boo boo."
        411 #ErrorDocument 404 /missing.html
        412 #ErrorDocument 404 "/cgi-bin/missing_handler.pl"

    展示一下默认的错误提示

    Internal Server Error

    The server encountered an internal error or misconfiguration and was unable to complete your request.

    Please contact the server administrator at you@example.com to inform them of the time this error occurred, and the actions you performed just before this error.

    More information about this error may be available in the server error log.
    系统错误日志中内容
         34 [Sat Jan 26 00:50:33.845682 2013] [cgid:error] [pid 24329:tid 2822667120        ] [client 192.168.203.1:4076] End of script output before headers: segv
         35 [Sat Jan 26 00:51:08.433898 2013] [cgid:error] [pid 24329:tid 2843646832        ] [client 192.168.203.1:4091] End of script output before headers: segv
         36 [Sat Jan 26 00:58:40.453014 2013] [cgid:error] [pid 24329:tid 2864626544        ] [client 192.168.203.1:4254] End of script output before headers: segv


    五、apache中默认错误提示
    httpd-2.4.2moduleshttphttp_protocol.c
    由于个人对于错误非常敏感和感兴趣,所以整个摘录过来了,希望你们也会喜欢啊,亲,so,enjoy。

    /* construct and return the default error message for a given
     * HTTP defined error code
     */
    static const char *get_canned_error_string(int status,
                                               request_rec *r,
                                               const char *location)
    {
        apr_pool_t *p = r->pool;
        const char *error_notes, *h1, *s1;

        switch (status) {
        case HTTP_MOVED_PERMANENTLY:
        case HTTP_MOVED_TEMPORARILY:
        case HTTP_TEMPORARY_REDIRECT:
            return(apr_pstrcat(p,
                               "<p>The document has moved <a href="",
                               ap_escape_html(r->pool, location),
                               "">here</a>.</p> ",
                               NULL));
        case HTTP_SEE_OTHER:
            return(apr_pstrcat(p,
                               "<p>The answer to your request is located "
                               "<a href="",
                               ap_escape_html(r->pool, location),
                               "">here</a>.</p> ",
                               NULL));
        case HTTP_USE_PROXY:
            return(apr_pstrcat(p,
                               "<p>This resource is only accessible "
                               "through the proxy ",
                               ap_escape_html(r->pool, location),
                               "<br /> You will need to configure "
                               "your client to use that proxy.</p> ",
                               NULL));
        case HTTP_PROXY_AUTHENTICATION_REQUIRED:
        case HTTP_UNAUTHORIZED:
            return("<p>This server could not verify that you "
                   "are authorized to access the document "
                   "requested.  Either you supplied the wrong "
                   "credentials (e.g., bad password), or your "
                   "browser doesn't understand how to supply "
                   "the credentials required.</p> ");
        case HTTP_BAD_REQUEST:
            return(add_optional_notes(r,
                                      "<p>Your browser sent a request that "
                                      "this server could not understand.<br /> ",
                                      "error-notes",
                                      "</p> "));
        case HTTP_FORBIDDEN:
            return(apr_pstrcat(p,
                               "<p>You don't have permission to access ",
                               ap_escape_html(r->pool, r->uri),
                               " on this server.</p> ",
                               NULL));
        case HTTP_NOT_FOUND:
            return(apr_pstrcat(p,
                               "<p>The requested URL ",
                               ap_escape_html(r->pool, r->uri),
                               " was not found on this server.</p> ",
                               NULL));
        case HTTP_METHOD_NOT_ALLOWED:
            return(apr_pstrcat(p,
                               "<p>The requested method ",
                               ap_escape_html(r->pool, r->method),
                               " is not allowed for the URL ",
                               ap_escape_html(r->pool, r->uri),
                               ".</p> ",
                               NULL));
        case HTTP_NOT_ACCEPTABLE:
            s1 = apr_pstrcat(p,
                             "<p>An appropriate representation of the "
                             "requested resource ",
                             ap_escape_html(r->pool, r->uri),
                             " could not be found on this server.</p> ",
                             NULL);
            return(add_optional_notes(r, s1, "variant-list", ""));
        case HTTP_MULTIPLE_CHOICES:
            return(add_optional_notes(r, "", "variant-list", ""));
        case HTTP_LENGTH_REQUIRED:
            s1 = apr_pstrcat(p,
                             "<p>A request of the requested method ",
                             ap_escape_html(r->pool, r->method),
                             " requires a valid Content-length.<br /> ",
                             NULL);
            return(add_optional_notes(r, s1, "error-notes", "</p> "));
        case HTTP_PRECONDITION_FAILED:
            return(apr_pstrcat(p,
                               "<p>The precondition on the request "
                               "for the URL ",
                               ap_escape_html(r->pool, r->uri),
                               " evaluated to false.</p> ",
                               NULL));
        case HTTP_NOT_IMPLEMENTED:
            s1 = apr_pstrcat(p,
                             "<p>",
                             ap_escape_html(r->pool, r->method), " to ",
                             ap_escape_html(r->pool, r->uri),
                             " not supported.<br /> ",
                             NULL);
            return(add_optional_notes(r, s1, "error-notes", "</p> "));
        case HTTP_BAD_GATEWAY:
            s1 = "<p>The proxy server received an invalid" CRLF
                "response from an upstream server.<br />" CRLF;
            return(add_optional_notes(r, s1, "error-notes", "</p> "));
        case HTTP_VARIANT_ALSO_VARIES:
            return(apr_pstrcat(p,
                               "<p>A variant for the requested "
                               "resource <pre> ",
                               ap_escape_html(r->pool, r->uri),
                               " </pre> is itself a negotiable resource. "
                               "This indicates a configuration error.</p> ",
                               NULL));
        case HTTP_REQUEST_TIME_OUT:
            return("<p>Server timeout waiting for the HTTP request from the client.</p> ");
        case HTTP_GONE:
            return(apr_pstrcat(p,
                               "<p>The requested resource<br />",
                               ap_escape_html(r->pool, r->uri),
                               "<br /> is no longer available on this server "
                               "and there is no forwarding address. "
                               "Please remove all references to this "
                               "resource.</p> ",
                               NULL));
        case HTTP_REQUEST_ENTITY_TOO_LARGE:
            return(apr_pstrcat(p,
                               "The requested resource<br />",
                               ap_escape_html(r->pool, r->uri), "<br /> ",
                               "does not allow request data with ",
                               ap_escape_html(r->pool, r->method),
                               " requests, or the amount of data provided in "
                               "the request exceeds the capacity limit. ",
                               NULL));
        case HTTP_REQUEST_URI_TOO_LARGE:
            s1 = "<p>The requested URL's length exceeds the capacity "
                 "limit for this server.<br /> ";
            return(add_optional_notes(r, s1, "error-notes", "</p> "));
        case HTTP_UNSUPPORTED_MEDIA_TYPE:
            return("<p>The supplied request data is not in a format "
                   "acceptable for processing by this resource.</p> ");
        case HTTP_RANGE_NOT_SATISFIABLE:
            return("<p>None of the range-specifier values in the Range "
                   "request-header field overlap the current extent "
                   "of the selected resource.</p> ");
        case HTTP_EXPECTATION_FAILED:
            s1 = apr_table_get(r->headers_in, "Expect");
            if (s1)
                s1 = apr_pstrcat(p,
                         "<p>The expectation given in the Expect request-header "
                         "field could not be met by this server. "
                         "The client sent<pre>     Expect: ",
                         ap_escape_html(r->pool, s1), " </pre> ",
                         NULL);
            else
                s1 = "<p>No expectation was seen, the Expect request-header "
                     "field was not presented by the client. ";
            return add_optional_notes(r, s1, "error-notes", "</p>"
                       "<p>Only the 100-continue expectation is supported.</p> ");
        case HTTP_UNPROCESSABLE_ENTITY:
            return("<p>The server understands the media type of the "
                   "request entity, but was unable to process the "
                   "contained instructions.</p> ");
        case HTTP_LOCKED:
            return("<p>The requested resource is currently locked. "
                   "The lock must be released or proper identification "
                   "given before the method can be applied.</p> ");
        case HTTP_FAILED_DEPENDENCY:
            return("<p>The method could not be performed on the resource "
                   "because the requested action depended on another "
                   "action and that other action failed.</p> ");
        case HTTP_UPGRADE_REQUIRED:
            return("<p>The requested resource can only be retrieved "
                   "using SSL.  The server is willing to upgrade the current "
                   "connection to SSL, but your client doesn't support it. "
                   "Either upgrade your client, or try requesting the page "
                   "using https:// ");
        case HTTP_INSUFFICIENT_STORAGE:
            return("<p>The method could not be performed on the resource "
                   "because the server is unable to store the "
                   "representation needed to successfully complete the "
                   "request.  There is insufficient free space left in "
                   "your storage allocation.</p> ");
        case HTTP_SERVICE_UNAVAILABLE:
            return("<p>The server is temporarily unable to service your "
                   "request due to maintenance downtime or capacity "
                   "problems. Please try again later.</p> ");
        case HTTP_GATEWAY_TIME_OUT:
            return("<p>The gateway did not receive a timely response "
                   "from the upstream server or application.</p> ");
        case HTTP_NOT_EXTENDED:
            return("<p>A mandatory extension policy in the request is not "
                   "accepted by the server for this resource.</p> ");
        default:                    /* HTTP_INTERNAL_SERVER_ERROR */
            /*
             * This comparison to expose error-notes could be modified to
             * use a configuration directive and export based on that
             * directive.  For now "*" is used to designate an error-notes
             * that is totally safe for any user to see (ie lacks paths,
             * database passwords, etc.)
             */
            if (((error_notes = apr_table_get(r->notes,
                                              "error-notes")) != NULL)
                && (h1 = apr_table_get(r->notes, "verbose-error-to")) != NULL
                && (strcmp(h1, "*") == 0)) {
                return(apr_pstrcat(p, error_notes, "<p /> ", NULL));
            }
            else {
                return(apr_pstrcat(p,
                                   "<p>The server encountered an internal "
                                   "error or "
                                   "misconfiguration and was unable to complete "
                                   "your request.</p> "
                                   "<p>Please contact the server "
                                   "administrator at ",
                                   ap_escape_html(r->pool,
                                                  r->server->server_admin),
                                   " to inform them of the time this "
                                   "error occurred, "
                                   " and the actions you performed just before "
                                   "this error.</p> "
                                   "<p>More information about this error "
                                   "may be available "
                                   "in the server error log.</p> ",
                                   NULL));
            }
            /*
             * It would be nice to give the user the information they need to
             * fix the problem directly since many users don't have access to
             * the error_log (think University sites) even though they can easily
             * get this error by misconfiguring an htaccess file.  However, the
             * e error notes tend to include the real file pathname in this case,
             * which some people consider to be a breach of privacy.  Until we
             * can figure out a way to remove the pathname, leave this commented.
             *
             * if ((error_notes = apr_table_get(r->notes,
             *                                  "error-notes")) != NULL) {
             *     return(apr_pstrcat(p, error_notes, "<p /> ", NULL);
             * }
             * else {
             *     return "";
             * }
             */
        }
    }
  • 相关阅读:
    ab命令做压测测试
    用js两张图片合并成一张图片
    Web全景图的原理及实现
    深入理解Java中的IO
    Spring AOP详解
    spring @Transactional注解参数详解
    优化MyBatis配置文件中的配置
    使用MyBatis对表执行CRUD操作
    @requestBody注解的使用
    url 拼接的一个模块furl
  • 原文地址:https://www.cnblogs.com/tsecer/p/10487848.html
Copyright © 2020-2023  润新知