1.概述
nginx有兩類進程,一類稱為master進程(相當於管理進程),另一類稱為worker進程(實際工作進程)。啟動方式有兩種:
(1)單進程啟動:此時系統中僅有一個進程,該進程既充當master進程的角色,也充當worker進程的角色。
(2)多進程啟動:此時系統有且僅有一個master進程,至少有一個worker進程工作。
master進程主要進行一些全局性的初始化工作和管理worker的工作;事件處理是在worker中進行的。
首先簡要的瀏覽一下nginx的啟動過程,如下圖:
2.實現原理
這里只分析多進程下的工作原理。
nginx的進程啟動過程是在ngx_master_process_cycle(src/os/unix/ngx_process_cycle.c)中完成的,在ngx_master_process_cycle中,會根據配置文件的worker_processes值創建多個子進程,即一個master進程和多個worker進程。進程之間、進程與外部之間保持通信。如下圖所示:圖中w1表示worker進程1,以此類推。虛線表示信號通信,實現表示socketpair通信。
nginx 的進程模型采用的是prefork方式,預先分配的worker子進程數量由配置文件指定,默認為1。master主進程創建監聽套接口,fork子進程以后,由worker進程監聽客戶連接,每個worker子進程獨自嘗試accept已連接套接口,accept是否上鎖可以配置,默認會上鎖,如果操作系統支持原子整型,才會使用共享內存實現原子上鎖,否則使用文件上鎖。如果不使用鎖,當多個進程同時accept,當一個連接來的時候多個進程同時被喚起,會導致驚群問題。使用鎖的時候,只會有一個worker阻塞在accept上,其他的進程則會不能獲取鎖而阻塞,這樣就解決了驚群的問題。master進程通過socketpair向worker子進程發送命令,終端也可以向master發送各種命令,子進程通過發送信號給master進程的方式與其通信,worker之間通過unix套接口通信。
當master接收到worker發回的SIGCHLD信號時,(worker進程的退出信號),它會逐個檢查每一個worker進程,如果發現有worker進程是異常退出,就會重新啟動這個worker進程。另外nginx還有兩個用於管理cache的進程,一個是cache manager process,另外一個是cache loader process,它們是專門服務於文件cache的進程,也服從master進程的管理,類似於worker進程,后面的分析將略去它們。下面從代碼的角度,詳細分析實現細節。
master啟動的時候,有一些重要的全局數據會被設置,最重要的是進程表ngx_processes,master每創建一個worker都會把一個設置好的ngx_process_t結構變量放入ngx_processes中,新創建的進程存放在ngx_process_slot位置,ngx_last_process是進程表中最后一個存量進程的下一個位置,ngx_process_t是進程在nginx中的抽象:
1 typedef struct { 2 ngx_pid_t pid; //進程的ID 3 int status; //進程的退出狀態 4 ngx_socket_t channel[2]; //用於socketpair通信的一對socket句柄 5 ngx_spawn_proc_pt proc; //進程的執行函數 6 void *data; //proc的參數 7 char *name; //進程的title標識 8 unsigned respawn:1; //進程的狀態:重新創建的 9 unsigned just_spawn:1; //進程的狀態: 第一次創建的 10 unsigned detached:1; //進程的狀態: 分離的,獨立的 11 unsigned exiting:1; //進程的狀態: 正在退出的 12 unsigned exited:1; //進程的狀態: 已經退出的 13 } ngx_process_t;(src/os/unix/ngx_process.h)
master進程向worker子進程發送命令是通過socketpair創建的一對socket實現的,之間傳輸的是ngx_channel_t結構變量:
1 typedef struct { 2 ngx_uint_t command; //發送的命令 3 ngx_pid_t pid; //發送方進程的進程id 4 ngx_int_t slot; //發送方進程在進程表中偏移位置 5 ngx_fd_t fd; //發送給對方的文件句柄 6 } ngx_channel_t;(src/os/unix/ngx_channel.h)
command是要發送的命令,有5種:
1 #define NGX_CMD_OPEN_CHANNEL 1 2 #define NGX_CMD_CLOSE_CHANNEL 2 3 #define NGX_CMD_QUIT 3 4 #define NGX_CMD_TERMINATE 4 5 #define NGX_CMD_REOPEN 5
1).首先分析master進程的代碼的功能,(Ngx_process_cycle.c中):
main()函數首先做一系列的初始化工作調用各模塊的初始化代碼(例如創建監聽套接口等)然后就會調用ngx_master_process_cycle代碼(多進程啟動情況下),cycle是一個全局結構體變量,存儲有系統運行的所需要的一些信息。在分析進程關系的的時候可以先忽略它。
1 void ngx_master_process_cycle(ngx_cycle_t *cycle) 2 { 3 1.master設置一些需要處理的信號,信號包括: 4 SIGCHLD, //子進程退出時發送給父進程的 5 SIGALRM, //計時器信號 6 SIGIO, //描述符上可以進行I/O時發出的信號 7 SIGINT, //中斷信號 8 NGX_RECONFIGURE_SIGNAL(SIGHUP), //終端線路掛斷 9 NGX_REOPEN_SIGNAL(SIGUSR1), //用戶自定義usr1信號 10 NGX_NOACCEPT_SIGNAL(SIGWINCH), //控制中斷大小改變 11 NGX_TERMINATE_SIGNAL(SIGTERM), //請求終端 12 NGX_SHUTDOWN_SIGNAL(SIGQUIT), //終端發送的quit信號 13 NGX_CHANGEBIN_SIGNAL(SIGUSR2);//用戶自定義usr1信號 14 15 2.調用ngx_setproctilte設置進程標題; 16 17 3. 調用ngx_start_worker_processes()啟動worker進程; 18 19 //有些模塊需要文件cache,比如fastcgi模塊,這些模塊會把文件cache路徑添加到//cycle->paths中,文件cache管理進程會定期調用這些模塊的文件cache處理鈎子處//理一下文件cache,其實一共會啟動兩個進程,這些進程的detached會被設置為1 20 4.調用ngx_start_cache_manager_processes()啟動文件cache管理進程; 21 22 5.master循環處理信號量。 23 ngx_new_binary = 0; 24 delay = 0; 25 live = 1; 26 27 for ( ;; ) { 28 // delay用來設置等待worker退出的時間,master接收了退出信號后首先發送 //退出信號給worker,而worker退出需要一些時間 29 if (delay) { 30 delay *= 2; 31 ngx_log_debug1(NGX_LOG_DEBUG_EVENT, cycle->log, 0, 32 "temination cycle: %d", delay); 33 itv.it_interval.tv_sec = 0; 34 itv.it_interval.tv_usec = 0; 35 itv.it_value.tv_sec = delay / 1000; 36 itv.it_value.tv_usec = (delay % 1000 ) * 1000; 37 38 // 設置定時器 39 if (setitimer(ITIMER_REAL, &itv, NULL) == -1) { 40 ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno, 41 "setitimer() failed"); 42 } 43 } 44 45 ngx_log_debug0(NGX_LOG_DEBUG_EVENT, cycle->log, 0, "sigsuspend"); 46 47 // 掛起信號量,等待定時器 48 sigsuspend(&set); 49 ngx_time_update(0, 0); 50 ngx_log_debug0(NGX_LOG_DEBUG_EVENT, cycle->log, 0, "wake up"); 51 52 // 收到了SIGCHLD信號,有worker退出(ngx_reap==1) 53 if (ngx_reap) { 54 ngx_reap = 0; 55 ngx_log_debug0(NGX_LOG_DEBUG_EVENT, cycle->log, 0, "reap children"); 56 57 // 處理所有worker,如果有worker異常退出則重啟這個worker,如果所有 58 // worker都退出,返回0賦值給live 59 live = ngx_reap_children(cycle); 60 } 61 62 // 如果worker都已經退出,並且收到了NGX_CMD_TERMINATE命令或者 //SIGTERM信號或者SIGINT信號(ngx_terminate=1) 63 // 或者NGX_CMD_QUIT命令或者SIGQUIT信號(ngx_quit=1),則master退出 64 if (!live && (ngx_terminate || ngx_quit)) { 65 ngx_master_process_exit(cycle); 66 } 67 68 // 收到了NGX_CMD_TERMINATE命令或者SIGTERM信號或者SIGINT信號, 69 // 通知所有worker退出,並且等待worker退出 70 if (ngx_terminate) { 71 if (delay == 0) { 72 delay = 50; 73 } 74 75 // 給所有worker發送SIGTERM,通知worker退出 76 if (delay > 1000) { 77 ngx_signal_worker_processes(cycle, SIGKILL); 78 } else { 79 80 ngx_signal_worker_processes(cycle, 81 ngx_signal_value(NGX_TERMINATE_SIGNAL)); 82 } 83 84 continue; 85 } 86 87 // 收到了NGX_CMD_QUIT命令或者SIGQUIT信號 88 if (ngx_quit) { 89 // 給所有worker發送SIGQUIT信號 90 ngx_signal_worker_processes(cycle, 91 ngx_signal_value(NGX_SHUTDOWN_SIGNAL)); 92 93 // 關閉所有監聽的socket 94 ls = cycle->listening.elts; 95 for (n = 0; n < cycle->listening.nelts; n++) { 96 if (ngx_close_socket(ls[n].fd) == -1) { 97 ngx_log_error(NGX_LOG_EMERG, cycle->log, ngx_socket_errno, 98 ngx_close_socket_n " %V failed", 99 &ls[n].addr_text); 100 } 101 } 102 cycle->listening.nelts = 0; 103 104 continue; 105 } 106 107 // 收到了SIGHUP信號 108 if (ngx_reconfigure) { 109 ngx_reconfigure = 0; 110 111 // 代碼已經被替換,重啟worker,不需要重新初始化配置 112 if (ngx_new_binary) { 113 ngx_start_worker_processes(cycle, ccf->worker_processes, 114 NGX_PROCESS_RESPAWN); 115 ngx_start_cache_manager_processes(cycle, 0); 116 ngx_noaccepting = 0; 117 118 continue; 119 } 120 121 ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0, "reconfiguring"); 122 123 // 重新初始化配置 124 cycle = ngx_init_cycle(cycle); 125 if (cycle == NULL) { 126 cycle = (ngx_cycle_t *) ngx_cycle; 127 continue; 128 } 129 130 // 重啟worker 131 ngx_cycle = cycle; 132 ccf = (ngx_core_conf_t *) ngx_get_conf(cycle->conf_ctx, 133 ngx_core_module); 134 ngx_start_worker_processes(cycle, ccf->worker_processes, 135 NGX_PROCESS_JUST_RESPAWN); 136 ngx_start_cache_manager_processes(cycle, 1); 137 live = 1; 138 ngx_signal_worker_processes(cycle, 139 ngx_signal_value(NGX_SHUTDOWN_SIGNAL)); 140 } 141 142 // 當ngx_noaccepting=1的時候會把ngx_restart設為1,重啟worker 143 if (ngx_restart) { 144 ngx_restart = 0; 145 ngx_start_worker_processes(cycle, ccf->worker_processes, 146 NGX_PROCESS_RESPAWN); 147 ngx_start_cache_manager_processes(cycle, 0); 148 live = 1; 149 } 150 151 // 收到SIGUSR1信號,重新打開log文件 152 if (ngx_reopen) { 153 ngx_reopen = 0; 154 ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0, "reopening logs"); 155 ngx_reopen_files(cycle, ccf->user); 156 ngx_signal_worker_processes(cycle, 157 ngx_signal_value(NGX_REOPEN_SIGNAL)); 158 } 159 160 // 收到SIGUSR2信號,熱代碼替換 161 if (ngx_change_binary) { 162 ngx_change_binary = 0; 163 ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0, "changing binary"); 164 // 調用execve執行新的代碼 165 ngx_new_binary = ngx_exec_new_binary(cycle, ngx_argv); 166 } 167 168 // 收到SIGWINCH信號,不再接收請求,worker退出,master不退出 169 if (ngx_noaccept) { 170 ngx_noaccept = 0; 171 ngx_noaccepting = 1; 172 ngx_signal_worker_processes(cycle, 173 ngx_signal_value(NGX_SHUTDOWN_SIGNAL)); 174 } 175 } 176 }
從代碼中可以看書master主進程的邏輯是非常清晰的,如下圖:
2)接下來分析worker進程啟動的代碼ngx_start_worker_processes(),由於使用了socketpair通信,這里也包過了對socket設置的一些代碼:
1 static void ngx_start_worker_processes(ngx_cycle_t *cycle, ngx_int_t n, ngx_int_t type) 2 { 3 ngx_int_t i; 4 ngx_channel_t ch;//用於socketpair通信的數據 5 ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0, "start worker processes"); 6 // 傳遞給其他worker子進程的命令:打開通信管道 7 ch.command = NGX_CMD_OPEN_CHANNEL; 8 for (i = 0; i < n; i++) { 9 cpu_affinity = ngx_get_cpu_affinity(i); 10 ngx_spawn_process(cycle, ngx_worker_process_cycle, NULL, 11 "worker process", type); 12 // 向之前已經創建的所有worker廣播當前創建的worker進程的信息 13 ch.pid = ngx_processes[ngx_process_slot].pid;//當前進程的pid 14 ch.slot = ngx_process_slot; //當前進程在進程表中的位置 15 //fd是發送給對方的句柄 16 ch.fd = ngx_processes[ngx_process_slot].channel[0]; ngx_pass_open_channel(cycle, &ch); 17 } 18 }
循環體中使用ngx_spawn_process來生成worker進程,這個后面說明。每次創建一個新的worker進程之后,都需要向之前創建的所有worker進程廣播新創建的worker進程的信息。
ngx_pass_open_channel()會利用一個循環,將ch信息發送給其他的worker進程的channel[0]的socket上,worker收到以后就會將ch的信息添加到自己的進程表中,這樣每個worker進程自己的進程表和master進程的進程表就會保持一致。在子進程創建的過程中,后面會有代碼來設置各自的進程表項的ngx_socket_t字段。
3).第2個函數中新建了一個進程以后,然后調用ngx_pass_open_channel(cycle,&ch)將ch數據對其他進程進行廣播處理,下面分析它的實現。
1 static void ngx_pass_open_channel(ngx_cycle_t *cycle, ngx_channel_t *ch) 2 { //ch是要向其他的worker進程廣播的消息 3 ngx_int_t i; 4 //逐個遍歷所有的worker進程關聯的ngx_process 5 for (i = 0; i < ngx_last_process; i++) { 6 // 跳過自己和異常的進程 7 if (i == ngx_process_slot|| ngx_processes[i].pid == -1 8 || ngx_processes[i].channel[0] == -1) 9 { 10 continue; 11 } 12 ngx_log_debug6(NGX_LOG_DEBUG_CORE, cycle->log, 0, 13 "pass channel s:%d pid:%P fd:%d to s:%i pid:%P fd:%d", 14 ch->slot, ch->pid, ch->fd, 15 i, ngx_processes[i].pid, 16 ngx_processes[i].channel[0]); 17 /* TODO: NGX_AGAIN */ 18 // 發送消息給其他的worker,發送到每個進程的 19 //ngx_processes[i].channel[0]的socket上 20 ngx_write_channel(ngx_processes[i].channel[0], 21 ch, sizeof(ngx_channel_t), cycle->log); 22 } 23 }
從代碼中可以看出函數發送給除自己外而且正常工作的worker進程發送自己的進程信息,worker進程收到以后會將它添加到自己的進程表中。
4).接下來分析ngx_pid_t ngx_spawn_process(ngx_cycle_t *cycle, ngx_spawn_proc_pt proc, void *data, char *name, ngx_int_t respawn)函
1 ngx_pid_t ngx_spawn_process(ngx_cycle_t *cycle, ngx_spawn_proc_pt proc, void *data,char *name, ngx_int_t respawn) 2 { //proc是子進程的執行函數,data是其參數,name是子進程的名字 3 u_long on; 4 ngx_pid_t pid; 5 ngx_int_t s; //將要創建的子進程在進程表中的位置 6 7 if (respawn >= 0) { 8 // 替換進程ngx_processes[respawn],可安全重用該進程表項 9 s = respawn; 10 } else { 11 // 先找到一個被回收的進程表項 12 for (s = 0; s < ngx_last_process; s++) { 13 if (ngx_processes[s].pid == -1) { 14 break; 15 } 16 } 17 // 進程表已滿 18 if (s == NGX_MAX_PROCESSES) { 19 ngx_log_error(NGX_LOG_ALERT, cycle->log, 0, 20 "no more than %d processes can be spawned", 21 NGX_MAX_PROCESSES); 22 return NGX_INVALID_PID; 23 } 24 } 25 26 27 28 // 不是分離的子進程,指的就是worker進程,cache進程是分離出去的進程 29 //cache進程不等同於worker進程,系統把它看成額外的獨立進程 30 if (respawn != NGX_PROCESS_DETACHED) { 31 /* Solaris 9 still has no AF_LOCAL */ 32 // 創建一對已經連接的無名socket,用於socketpair通信的 33 if (socketpair(AF_UNIX, SOCK_STREAM, 0, ngx_processes[s].channel) == -1) 34 { 35 ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno, 36 "socketpair() failed while spawning \"%s\"", name); 37 return NGX_INVALID_PID; 38 } 39 ngx_log_debug2(NGX_LOG_DEBUG_CORE, cycle->log, 0, 40 "channel %d:%d", 41 ngx_processes[s].channel[0], 42 ngx_processes[s].channel[1]); 43 44 // 設置socket為非阻塞模式 45 if (ngx_nonblocking(ngx_processes[s].channel[0]) == -1) { 46 ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno, 47 ngx_nonblocking_n " failed while spawning \"%s\"", 48 name); 49 ngx_close_channel(ngx_processes[s].channel, cycle->log); 50 return NGX_INVALID_PID; 51 } 52 // 設置socket為非阻塞模式 53 if (ngx_nonblocking(ngx_processes[s].channel[1]) == -1) { 54 ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno, 55 ngx_nonblocking_n " failed while spawning \"%s\"", 56 name); 57 ngx_close_channel(ngx_processes[s].channel, cycle->log); 58 return NGX_INVALID_PID; 59 } 60 61 // 設置channel[0]的信號驅動異步I/O 標志 62 on = 1; 63 if (ioctl(ngx_processes[s].channel[0], FIOASYNC, &on) == -1) { 64 ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno, 65 "ioctl(FIOASYNC) failed while spawning \"%s\"", name); 66 ngx_close_channel(ngx_processes[s].channel, cycle->log); 67 return NGX_INVALID_PID; 68 } 69 70 71 // 設置channel[0]的屬主,控制channel[0]的SIGIO信號只發給master進程,//ngx_pid為全局變量,指的是master主進程,因為master與worker進程通//信時通過將數據發送到進程的channel[0]上通知的,因此channel[0]的屬主是//manster進程 72 if (fcntl(ngx_processes[s].channel[0], F_SETOWN, ngx_pid) == -1) { 73 ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno, 74 "fcntl(F_SETOWN) failed while spawning \"%s\"", name); 75 ngx_close_channel(ngx_processes[s].channel, cycle->log); 76 return NGX_INVALID_PID; 77 } 78 79 // 設置channel[0]的close-on-exec標識,失敗則關閉channel 80 if (fcntl(ngx_processes[s].channel[0], F_SETFD, FD_CLOEXEC) == -1) { 81 ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno, 82 "fcntl(FD_CLOEXEC) failed while spawning \"%s\"",name); 83 ngx_close_channel(ngx_processes[s].channel, cycle->log); 84 return NGX_INVALID_PID; 85 } 86 87 // 設置channel[1]的close-on-exec標識,失敗則關閉channel 88 if (fcntl(ngx_processes[s].channel[1], F_SETFD, FD_CLOEXEC) == -1) { 89 ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno, 90 "fcntl(FD_CLOEXEC) failed while spawning \"%s\"",name); 91 ngx_close_channel(ngx_processes[s].channel, cycle->log); 92 return NGX_INVALID_PID; 93 } 94 95 // 用於監聽可讀事件的socket,ngx_channel是全局變量 96 ngx_channel = ngx_processes[s].channel[1]; 97 } else { 98 //說明是分離的獨立進程,則不需要socket進行通信,都設置成無效的 99 ngx_processes[s].channel[0] = -1; 100 ngx_processes[s].channel[1] = -1; 101 } 102 103 //新建進程在進程表中的實際位置 104 ngx_process_slot = s; 105 pid = fork(); 106 switch (pid) { 107 case -1: 108 ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno, 109 "fork() failed while spawning \"%s\"", name); 110 ngx_close_channel(ngx_processes[s].channel, cycle->log); 111 return NGX_INVALID_PID; 112 113 case 0: 114 //子進程在這里運行 115 ngx_pid = ngx_getpid(); 116 //調用子進程需要執行的函數,即ngx_worker_process_cycle 117 proc(cycle, data); 118 break; 119 default: 120 break; 121 } 122 ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0, "start %s %P", name, pid); 123 ngx_processes[s].pid = pid;//設置子進程的pid 124 ngx_processes[s].exited = 0;//子進程沒有退出 125 126 // 如果替換進程ngx_processes[respawn],不用設置其他進程表項字段了 127 if (respawn >= 0) { 128 return pid; 129 } 130 131 // 設置其他的進程表項字段 132 ngx_processes[s].proc = proc; 133 ngx_processes[s].data = data; 134 ngx_processes[s].name = name; 135 ngx_processes[s].exiting = 0; 136 137 // 設置進程表項的一些狀態字段 138 switch (respawn) { 139 case NGX_PROCESS_NORESPAWN: 140 ngx_processes[s].respawn = 0; 141 ngx_processes[s].just_spawn = 0; 142 ngx_processes[s].detached = 0; 143 break; 144 145 case NGX_PROCESS_JUST_SPAWN: 146 ngx_processes[s].respawn = 0; 147 ngx_processes[s].just_spawn = 1; 148 ngx_processes[s].detached = 0; 149 break; 150 151 case NGX_PROCESS_RESPAWN: 152 ngx_processes[s].respawn = 1; 153 ngx_processes[s].just_spawn = 0; 154 ngx_processes[s].detached = 0; 155 break; 156 157 case NGX_PROCESS_JUST_RESPAWN: 158 ngx_processes[s].respawn = 1; 159 ngx_processes[s].just_spawn = 1; 160 ngx_processes[s].detached = 0; 161 break; 162 163 case NGX_PROCESS_DETACHED:// 164 ngx_processes[s].respawn = 0; 165 ngx_processes[s].just_spawn = 0; 166 ngx_processes[s].detached = 1; 167 break; 168 } 169 //檢查是否需要更新ngx_last_process 170 if (s == ngx_last_process) { 171 ngx_last_process++; 172 } 173 return pid; 174 }
5)下面分析worker工作進程執行的函數:static voidngx_worker_process_cycle(ngx_cycle_t *cycle, void *data)。
1 static void ngx_worker_process_cycle(ngx_cycle_t *cycle, void *data) 2 { 3 ngx_uint_t i; 4 ngx_connection_t *c;//用於連接的 5 ngx_process = NGX_PROCESS_WORKER; 6 7 //初始化工作,這個工作很重要,后面會詳細說明它 8 ngx_worker_process_init(cycle, 1); 9 //設置進程標題 10 ngx_setproctitle("worker process"); 11 12 //使用線程時,則會執行的代碼,線程相關的代碼不影響分析系統的進程結構,主//要是做一些創建線程之前的初始化和准備,然后創建線程,執行線程函數,處理//用戶請求 13 #if (NGX_THREADS) 14 { 15 ngx_int_t n; 16 ngx_err_t err; 17 ngx_core_conf_t *ccf; 18 ccf = (ngx_core_conf_t *) ngx_get_conf(cycle->conf_ctx, ngx_core_module); 19 if (ngx_threads_n) 20 if (ngx_init_threads(ngx_threads_n, ccf->thread_stack_size, cycle) 21 == NGX_ERROR) 22 { 23 /* fatal */ 24 exit(2); 25 } 26 27 err = ngx_thread_key_create(&ngx_core_tls_key); 28 if (err != 0) { 29 ngx_log_error(NGX_LOG_ALERT, cycle->log, err, 30 ngx_thread_key_create_n " failed"); 31 /* fatal */ 32 exit(2); 33 } 34 35 for (n = 0; n < ngx_threads_n; n++) { 36 ngx_threads[n].cv = ngx_cond_init(cycle->log); 37 if (ngx_threads[n].cv == NULL) { 38 /* fatal */ 39 exit(2); 40 } 41 if (ngx_create_thread((ngx_tid_t *) &ngx_threads[n].tid, 42 ngx_worker_thread_cycle, 43 (void *) &ngx_threads[n], cycle->log) 44 != 0) 45 { 46 /* fatal */ 47 exit(2); 48 } 49 } 50 } 51 } 52 #endif 53 54 //worker進程工作的主循環 55 for ( ;; ) { 56 // 如果退出狀態已設置,關閉所有連接 57 if (ngx_exiting) { 58 c = cycle->connections; 59 for (i = 0; i < cycle->connection_n; i++) { 60 /* THREAD: lock */ 61 //鏈接存在,而且連接是空閑的,就將它關閉 62 if (c[i].fd != -1 && c[i].idle) { 63 c[i].close = 1; 64 c[i].read->handler(c[i].read); 65 } 66 } 67 68 if (ngx_event_timer_rbtree.root == ngx_event_timer_rbtree.sentinel) 69 { 70 ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0, "exiting"); 71 ngx_worker_process_exit(cycle); 72 } 73 } 74 75 ngx_log_debug0(NGX_LOG_DEBUG_EVENT, cycle->log, 0, "worker cycle"); 76 77 // 處理事件和計時 78 ngx_process_events_and_timers(cycle); 79 80 // 收到NGX_CMD_TERMINATE命令 81 if (ngx_terminate) { 82 ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0, "exiting"); 83 // 清理后進程退出,會調用所有模塊的鈎子exit_process 84 ngx_worker_process_exit(cycle); 85 } 86 87 // 收到NGX_CMD_QUIT命令 88 if (ngx_quit) { 89 ngx_quit = 0; 90 ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0, 91 "gracefully shutting down"); 92 ngx_setproctitle("worker process is shutting down"); 93 if (!ngx_exiting) { 94 // 關閉監聽socket,設置退出狀態 95 ngx_close_listening_sockets(cycle); 96 ngx_exiting = 1; 97 } 98 } 99 100 // 收到NGX_CMD_REOPEN命令,重新打開log 101 if (ngx_reopen) { 102 ngx_reopen = 0; 103 ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0, "reopening logs"); 104 ngx_reopen_files(cycle, -1); 105 } 106 } 107 }
6).接下來分析static void ngx_worker_process_init(ngx_cycle_t *cycle, ngx_uint_t priority),主要做的是work進程創建之前的初始化操作。
1 static void ngx_worker_process_init(ngx_cycle_t *cycle, ngx_uint_t priority) 2 { 3 1、設置ngx_process = NGX_PROCESS_WORKER,在master進程中這個變量被設置為NGX_PROCESS_MASTER; 4 5 2、全局性的設置,根據全局的配置信息設置執行環境、優先級、限制、setgid、setuid、信號初始化等; 6 7 3、調用所有模塊的鈎子init_process; 8 9 4、關閉不使用的socket,關閉當前worker的channel[0]句柄和其他worker的channel[1]句柄,當前worker會使用其他worker的channel[0]句柄發送消息,使用當前worker的channel[1]句柄監聽可讀事件: 10 11 for (n = 0; n < ngx_last_process; n++) { 12 //跳過無效進程 13 if (ngx_processes[n].pid == -1) { 14 continue; 15 } 16 //跳過自己 17 if (n == ngx_process_slot) { 18 continue; 19 } 20 //跳過獨立的進程,因為獨立的進程的channel句柄別設置為-1, 21 //或者是關閉channel的進程 22 23 if (ngx_processes[n].channel[1] == -1) { 24 continue; 25 } 26 //關閉其他進程的channel[1]句柄 27 if (close(ngx_processes[n].channel[1]) == -1) { 28 ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno, 29 "close() channel failed"); 30 } 31 } 32 //關閉自己進程的channel[0]句柄 33 if (close(ngx_processes[ngx_process_slot].channel[0]) == -1) { 34 ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno, 35 "close() channel failed"); 36 } 37 38 5、在當前worker的channel[1]句柄監聽可讀事件: 39 if (ngx_add_channel_event(cycle, ngx_channel, NGX_READ_EVENT, 40 ngx_channel_handler) 41 == NGX_ERROR) 42 { 43 exit(2); 44 } 45 }
可以看出,通過第4步的操作,worker進程就可以再channel[1]上監聽事件了,而master進程正好是將命令發往worker進程對應的channel[0]上,因此便實現了socketpair通信。當前worker還可以使用其他進程的channel[0]句柄發送消息,使用很少,但主要是監聽channel[1]句柄上的事件消息。
7) ngx_add_channel_event()把句柄ngx_channel(當前worker的channel[1])上建立的連接的可讀事件加入事件監控隊列,事件處理函數為ngx_channel_hanlder(ngx_event_t *ev)。當有可讀事件的時候,ngx_channel_handler負責處理消息,下面分析其實現:
1 static voidngx_channel_handler(ngx_event_t *ev) 2 { 3 ngx_int_t n; 4 ngx_channel_t ch; 5 ngx_connection_t *c; 6 7 if (ev->timedout) { 8 ev->timedout = 0; 9 return; 10 } 11 12 c = ev->data; 13 14 ngx_log_debug0(NGX_LOG_DEBUG_CORE, ev->log, 0, "channel handler"); 15 16 for ( ;; ) { 17 //從channel[1]中讀取消息 18 n = ngx_read_channel(c->fd, &ch, sizeof(ngx_channel_t), ev->log); 19 ngx_log_debug1(NGX_LOG_DEBUG_CORE, ev->log, 0, "channel: %i", n); 20 21 if (n == NGX_ERROR) { 22 if (ngx_event_flags & NGX_USE_EPOLL_EVENT) { 23 ngx_del_conn(c, 0); 24 } 25 ngx_close_connection(c); 26 return; 27 } 28 29 if (ngx_event_flags & NGX_USE_EVENTPORT_EVENT) { 30 if (ngx_add_event(ev, NGX_READ_EVENT, 0) == NGX_ERROR) { 31 return; 32 } 33 } 34 35 if (n == NGX_AGAIN) { 36 return; 37 } 38 39 ngx_log_debug1(NGX_LOG_DEBUG_CORE, ev->log, 0, 40 "channel command: %d", ch.command); 41 //處理消息命令 42 switch (ch.command) { 43 case NGX_CMD_QUIT: 44 ngx_quit = 1; 45 break; 46 47 case NGX_CMD_TERMINATE: 48 ngx_terminate = 1; 49 break; 50 51 case NGX_CMD_REOPEN: 52 ngx_reopen = 1; 53 break; 54 55 case NGX_CMD_OPEN_CHANNEL: 56 57 ngx_log_debug3(NGX_LOG_DEBUG_CORE, ev->log, 0, 58 "get channel s:%i pid:%P fd:%d", 59 ch.slot, ch.pid, ch.fd); 60 61 ngx_processes[ch.slot].pid = ch.pid; 62 ngx_processes[ch.slot].channel[0] = ch.fd; 63 break; 64 65 case NGX_CMD_CLOSE_CHANNEL: 66 67 ngx_log_debug4(NGX_LOG_DEBUG_CORE, ev->log, 0, 68 "close channel s:%i pid:%P our:%P fd:%d", 69 ch.slot, ch.pid, ngx_processes[ch.slot].pid, 70 ngx_processes[ch.slot].channel[0]); 71 72 if (close(ngx_processes[ch.slot].channel[0]) == -1) { 73 ngx_log_error(NGX_LOG_ALERT, ev->log, ngx_errno, 74 "close() channel failed"); 75 } 76 ngx_processes[ch.slot].channel[0] = -1; 77 break; 78 } 79 } 80 }
以上分析了nginx進程的通信機制以及工作邏輯模型,下面以圖表的形式做個總結:
本文檔也是以前研究分析的,難免會有不准確之處,希望大家一起研究探討。