From 39e77fd086734863b6f23e2fc3e1d51eb68bfc3e Mon Sep 17 00:00:00 2001 From: spacewander Date: Sat, 20 Apr 2019 11:35:31 +0800 Subject: [PATCH] feature: closed unused listening fds in worker processes. When 'reuseport' is enabled in the 'listen' directive, Nginx will create a listening fd for each worker process in the master process. These fds will be inherited by the worker processes, but most of them are unused. For eaxmple, considered we have 32 listening ip:port configurations and 64 worker processes, each worker process will inherit 2048 (32 * 64) listening fds, but only 32 fds are used. By closing the unused fds, this change could save up to 2016 (32 * 63) fds in a worker process. It doesn't affect the listening socket, since there is only one used fd which associates to the socket with or without this change. --- ...inx-1.15.8-close_unused_listening_fd.patch | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 patches/nginx-1.15.8-close_unused_listening_fd.patch diff --git a/patches/nginx-1.15.8-close_unused_listening_fd.patch b/patches/nginx-1.15.8-close_unused_listening_fd.patch new file mode 100644 index 0000000..cf1f3b0 --- /dev/null +++ b/patches/nginx-1.15.8-close_unused_listening_fd.patch @@ -0,0 +1,40 @@ +diff --git a/src/core/ngx_connection.c b/src/core/ngx_connection.c +--- a/src/core/ngx_connection.c ++++ b/src/core/ngx_connection.c +@@ -1118,6 +1118,14 @@ ngx_close_listening_sockets(ngx_cycle_t *cycle) + ls = cycle->listening.elts; + for (i = 0; i < cycle->listening.nelts; i++) { + ++#if (NGX_HAVE_REUSEPORT) ++ ++ if (ls[i].fd == (ngx_socket_t) -1) { ++ continue; ++ } ++ ++#endif ++ + c = ls[i].connection; + + if (c) { +diff --git a/src/event/ngx_event.c b/src/event/ngx_event.c +--- a/src/event/ngx_event.c ++++ b/src/event/ngx_event.c +@@ -775,6 +775,18 @@ ngx_event_process_init(ngx_cycle_t *cycle) + + #if (NGX_HAVE_REUSEPORT) + if (ls[i].reuseport && ls[i].worker != ngx_worker) { ++ ngx_log_debug2(NGX_LOG_DEBUG_CORE, cycle->log, 0, ++ "close unused listening %V #%d ", ++ &ls[i].addr_text, ls[i].fd); ++ ++ if (ngx_close_socket(ls[i].fd) == -1) { ++ ngx_log_error(NGX_LOG_EMERG, cycle->log, ngx_socket_errno, ++ ngx_close_socket_n " %V failed", ++ &ls[i].addr_text); ++ } ++ ++ ls[i].fd = (ngx_socket_t) -1; ++ + continue; + } + #endif