nginx源碼分析--master和worker進程模型

1、Nginx總體架構nginx

正常執行中的nginx會有多個進程,最基本的有master process(監控進程,也叫作主進程)和woker process(工做進程),還可能有cache相關進程。後端

一個較爲完整的總體框架結構如圖所示:數組

2、核心進程模型服務器

啓動nginx的主進程將充當監控進程,而由主進程fork()出來的子進程則充當工做進程。網絡

nginx也能夠單進程模型執行,在這種進程模型下,主進程就是工做進程,沒有監控進程。多線程

Nginx的核心進程模型框圖以下:架構

master進程框架

監控進程充當整個進程組與用戶的交互接口,同時對進程進行監護。它不須要處理網絡事件,不負責業務的執行,只會經過管理worker進程來實現重啓服務、平滑升級、更換日誌文件、配置文件實時生效等功能。socket

master進程全貌圖(來自阿里集團數據平臺博客):函數

master進程中for(::)無限循環內有一個關鍵的sigsuspend()函數調用,該函數調用是的master進程的大部分時間都處於掛起狀態,直到master進程收到信號爲止。

master進程經過檢查一下7個標誌位來決定ngx_master_process_cycle方法的運行:

sig_atomic_t ngx_reap;

sig_atomic_t ngx_terminate;

sig_atomic_t ngx_quit;

sig_atomic_t ngx_reconfigure;

sig_atomic_t ngx_reopen;

sig_atomic_t ngx_change_binary;

sig_atomic_t ngx_noaccept;

進程中接收到的信號對Nginx框架的意義:

信號 對應進程中的全局標誌位變量 意義
QUIT ngx_quit 優雅地關閉整個服務
TERM或INT ngx_terminate 強制關閉整個服務
USR1 ngx_reopen 從新打開服務中的全部文件
WINCH ngx_noaccept 全部子進程再也不接受處理新的鏈接,實際至關於對全部子進程發送QUIT信號
USR2 ngx_change_binary 平滑升級到新版本的Nginx程序
HUP ng_reconfigure 重讀配置文件
CHLD ngx_reap 有子進程之外結束,須要監控全部子進程

還有一個標誌位會用到:ngx_restart,它僅僅是在master工做流程中做爲標誌位使用,與信號無關。

核心代碼(ngx_process_cycle.c):

 

void
ngx_master_process_cycle(ngx_cycle_t *cycle)
{
  char			  *title;
  u_char			*p;
  size_t			 size;
  ngx_int_t		  i;
  ngx_uint_t		 n, sigio;
  sigset_t		   set;
  struct itimerval   itv;
  ngx_uint_t		 live;
  ngx_msec_t		 delay;
  ngx_listening_t   *ls;
  ngx_core_conf_t   *ccf;

  //信號處理設置工做
  sigemptyset(&set);
  sigaddset(&set, SIGCHLD);
  sigaddset(&set, SIGALRM);
  sigaddset(&set, SIGIO);
  sigaddset(&set, SIGINT);
  sigaddset(&set, ngx_signal_value(NGX_RECONFIGURE_SIGNAL));
  sigaddset(&set, ngx_signal_value(NGX_REOPEN_SIGNAL));
  sigaddset(&set, ngx_signal_value(NGX_NOACCEPT_SIGNAL));
  sigaddset(&set, ngx_signal_value(NGX_TERMINATE_SIGNAL));
  sigaddset(&set, ngx_signal_value(NGX_SHUTDOWN_SIGNAL));
  sigaddset(&set, ngx_signal_value(NGX_CHANGEBIN_SIGNAL));

  if (sigprocmask(SIG_BLOCK, &set, NULL) == -1) {
    ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
            "sigprocmask() failed");
  }

  sigemptyset(&set);


  size = sizeof(master_process);

  for (i = 0; i < ngx_argc; i++) {
    size += ngx_strlen(ngx_argv[i]) + 1;
  }

  title = ngx_pnalloc(cycle->pool, size);

  p = ngx_cpymem(title, master_process, sizeof(master_process) - 1);
  for (i = 0; i < ngx_argc; i++) {
    *p++ = ' ';
    p = ngx_cpystrn(p, (u_char *) ngx_argv[i], size);
  }

  ngx_setproctitle(title);


  ccf = (ngx_core_conf_t *) ngx_get_conf(cycle->conf_ctx, ngx_core_module);

  //其中包含了fork產生子進程的內容
  ngx_start_worker_processes(cycle, ccf->worker_processes,
                 NGX_PROCESS_RESPAWN);
  //Cache管理進程與cache加載進程的主流程
  ngx_start_cache_manager_processes(cycle, 0);

  ngx_new_binary = 0;
  delay = 0;
  sigio = 0;
  live = 1;

  for ( ;; ) {//循環
    if (delay) {
      if (ngx_sigalrm) {
        sigio = 0;
        delay *= 2;
        ngx_sigalrm = 0;
      }

      ngx_log_debug1(NGX_LOG_DEBUG_EVENT, cycle->log, 0,
               "termination cycle: %d", delay);

      itv.it_interval.tv_sec = 0;
      itv.it_interval.tv_usec = 0;
      itv.it_value.tv_sec = delay / 1000;
      itv.it_value.tv_usec = (delay % 1000 ) * 1000;

      if (setitimer(ITIMER_REAL, &itv, NULL) == -1) {
        ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                "setitimer() failed");
      }
    }

    ngx_log_debug0(NGX_LOG_DEBUG_EVENT, cycle->log, 0, "sigsuspend");

    sigsuspend(&set);//master進程休眠,等待接受信號被激活

    ngx_time_update();

    ngx_log_debug1(NGX_LOG_DEBUG_EVENT, cycle->log, 0,
             "wake up, sigio %i", sigio);

    //標誌位爲1表示須要監控全部子進程
    if (ngx_reap) {
      ngx_reap = 0;
      ngx_log_debug0(NGX_LOG_DEBUG_EVENT, cycle->log, 0, "reap children");

      live = ngx_reap_children(cycle);//管理子進程
    }

    //當live標誌位爲0(表示全部子進程已經退出)、ngx_terminate標誌位爲1或者ngx_quit標誌位爲1表示要退出master進程
    if (!live && (ngx_terminate || ngx_quit)) {
      ngx_master_process_exit(cycle);//退出master進程
    }

    //ngx_terminate標誌位爲1,強制關閉服務,發送TERM信號到全部子進程
    if (ngx_terminate) {
      if (delay == 0) {
        delay = 50;
      }

      if (sigio) {
        sigio--;
        continue;
      }

      sigio = ccf->worker_processes + 2 /* cache processes */;

      if (delay > 1000) {
        ngx_signal_worker_processes(cycle, SIGKILL);
      } else {
        ngx_signal_worker_processes(cycle,
                     ngx_signal_value(NGX_TERMINATE_SIGNAL));
      }

      continue;
    }

    //ngx_quit標誌位爲1,優雅的關閉服務
    if (ngx_quit) {
      ngx_signal_worker_processes(cycle,
                    ngx_signal_value(NGX_SHUTDOWN_SIGNAL));//向全部子進程發送quit信號

      ls = cycle->listening.elts;
      for (n = 0; n < cycle->listening.nelts; n++) {//關閉監聽端口
        if (ngx_close_socket(ls[n].fd) == -1) {
          ngx_log_error(NGX_LOG_EMERG, cycle->log, ngx_socket_errno,
                  ngx_close_socket_n " %V failed",
                  &ls[n].addr_text);
        }
      }
      cycle->listening.nelts = 0;

      continue;
    }

    //ngx_reconfigure標誌位爲1,從新讀取配置文件
    //nginx不會讓原來的worker子進程再從新讀取配置文件,其策略是從新初始化ngx_cycle_t結構體,用它來讀取新的額配置文件
    //再建立新的額worker子進程,銷燬舊的worker子進程
    if (ngx_reconfigure) {
      ngx_reconfigure = 0;

      //ngx_new_binary標誌位爲1,平滑升級Nginx
      if (ngx_new_binary) {
        ngx_start_worker_processes(cycle, ccf->worker_processes,
                       NGX_PROCESS_RESPAWN);
        ngx_start_cache_manager_processes(cycle, 0);
        ngx_noaccepting = 0;

        continue;
      }

      ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0, "reconfiguring");

      //初始化ngx_cycle_t結構體
      cycle = ngx_init_cycle(cycle);
      if (cycle == NULL) {
        cycle = (ngx_cycle_t *) ngx_cycle;
        continue;
      }

      ngx_cycle = cycle;
      ccf = (ngx_core_conf_t *) ngx_get_conf(cycle->conf_ctx,
                           ngx_core_module);
      //建立新的worker子進程
      ngx_start_worker_processes(cycle, ccf->worker_processes,
                     NGX_PROCESS_JUST_RESPAWN);
      ngx_start_cache_manager_processes(cycle, 1);

      /* allow new processes to start */
      ngx_msleep(100);

      live = 1;
      //向全部子進程發送QUIT信號
      ngx_signal_worker_processes(cycle,
                    ngx_signal_value(NGX_SHUTDOWN_SIGNAL));
    }
    //ngx_restart標誌位在ngx_noaccepting(表示正在中止接受新的鏈接)爲1的時候被設置爲1.
    //重啓子進程
    if (ngx_restart) {
      ngx_restart = 0;
      ngx_start_worker_processes(cycle, ccf->worker_processes,
                     NGX_PROCESS_RESPAWN);
      ngx_start_cache_manager_processes(cycle, 0);
      live = 1;
    }

    //ngx_reopen標誌位爲1,從新打開全部文件
    if (ngx_reopen) {
      ngx_reopen = 0;
      ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0, "reopening logs");
      ngx_reopen_files(cycle, ccf->user);
      ngx_signal_worker_processes(cycle,
                    ngx_signal_value(NGX_REOPEN_SIGNAL));
    }

    //平滑升級Nginx
    if (ngx_change_binary) {
      ngx_change_binary = 0;
      ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0, "changing binary");
      ngx_new_binary = ngx_exec_new_binary(cycle, ngx_argv);
    }

    //ngx_noaccept爲1,表示全部子進程再也不處理新的鏈接
    if (ngx_noaccept) {
      ngx_noaccept = 0;
      ngx_noaccepting = 1;
      ngx_signal_worker_processes(cycle,
                    ngx_signal_value(NGX_SHUTDOWN_SIGNAL));
    }
  }
}

ngx_start_worker_processes函數:

static void
ngx_start_worker_processes(ngx_cycle_t *cycle, ngx_int_t n, ngx_int_t type)
{
  ngx_int_t	  i;
  ngx_channel_t  ch;

  ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0, "start worker processes");

  ch.command = NGX_CMD_OPEN_CHANNEL;

  //循環建立n個worker子進程
  for (i = 0; i < n; i++) {
    //完成fok新進程的具體工做
    ngx_spawn_process(cycle, ngx_worker_process_cycle,
              (void *) (intptr_t) i, "worker process", type);

    //全局數組ngx_processes就是用來存儲每一個子進程的相關信息,如:pid,channel,進程作具體事情的接口指針等等,這些信息就是用結構體ngx_process_t來描述的。
    ch.pid = ngx_processes[ngx_process_slot].pid;
    ch.slot = ngx_process_slot;
    ch.fd = ngx_processes[ngx_process_slot].channel[0];

    /*在ngx_spawn_process建立好一個worker進程返回後,master進程就將worker進程的pid、worker進程在ngx_processes數組中的位置及channel[0]傳遞給前面已經建立好的worker進程,而後繼續循環開始建立下一個worker進程。剛提到一個channel[0],這裏簡單說明一下:channel就是一個可以存儲2個整型元素的數組而已,這個channel數組就是用於socketpair函數建立一個進程間通道之用的。master和worker進程以及worker進程之間均可以經過這樣的一個通道進行通訊,這個通道就是在ngx_spawn_process函數中fork以前調用socketpair建立的。*/
    ngx_pass_open_channel(cycle, &ch);
  }
}

ngx_spawn_process函數:

//參數解釋:
//cycle:nginx框架所圍繞的核心結構體
//proc:子進程中將要執行的工做循環
//data:參數
//name:子進程名字
ngx_pid_t
ngx_spawn_process(ngx_cycle_t *cycle, ngx_spawn_proc_pt proc, void *data,
  char *name, ngx_int_t respawn)
{
  u_long	 on;
  ngx_pid_t  pid;
  ngx_int_t  s;

  if (respawn >= 0) {
    s = respawn;

  } else {
    for (s = 0; s < ngx_last_process; s++) {
      if (ngx_processes[s].pid == -1) {
        break;
      }
    }

    if (s == NGX_MAX_PROCESSES) {
      ngx_log_error(NGX_LOG_ALERT, cycle->log, 0,
              "no more than %d processes can be spawned",
              NGX_MAX_PROCESSES);
      return NGX_INVALID_PID;
    }
  }


  if (respawn != NGX_PROCESS_DETACHED) {

    /* Solaris 9 still has no AF_LOCAL */
    //建立父子進程間通訊的套接字對(基於TCP)
    if (socketpair(AF_UNIX, SOCK_STREAM, 0, ngx_processes[s].channel) == -1)
    {
      ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
              "socketpair() failed while spawning \"%s\"", name);
      return NGX_INVALID_PID;
    }

    ngx_log_debug2(NGX_LOG_DEBUG_CORE, cycle->log, 0,
             "channel %d:%d",
             ngx_processes[s].channel[0],
             ngx_processes[s].channel[1]);

    //設置爲非阻塞模式
    if (ngx_nonblocking(ngx_processes[s].channel[0]) == -1) {
      ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
              ngx_nonblocking_n " failed while spawning \"%s\"",
              name);
      ngx_close_channel(ngx_processes[s].channel, cycle->log);
      return NGX_INVALID_PID;
    }

    if (ngx_nonblocking(ngx_processes[s].channel[1]) == -1) {
      ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
              ngx_nonblocking_n " failed while spawning \"%s\"",
              name);
      ngx_close_channel(ngx_processes[s].channel, cycle->log);
      return NGX_INVALID_PID;
    }

    on = 1;
    if (ioctl(ngx_processes[s].channel[0], FIOASYNC, &on) == -1) {
      ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
              "ioctl(FIOASYNC) failed while spawning \"%s\"", name);
      ngx_close_channel(ngx_processes[s].channel, cycle->log);
      return NGX_INVALID_PID;
    }

    if (fcntl(ngx_processes[s].channel[0], F_SETOWN, ngx_pid) == -1) {
      ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
              "fcntl(F_SETOWN) failed while spawning \"%s\"", name);
      ngx_close_channel(ngx_processes[s].channel, cycle->log);
      return NGX_INVALID_PID;
    }

    if (fcntl(ngx_processes[s].channel[0], F_SETFD, FD_CLOEXEC) == -1) {
      ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
              "fcntl(FD_CLOEXEC) failed while spawning \"%s\"",
               name);
      ngx_close_channel(ngx_processes[s].channel, cycle->log);
      return NGX_INVALID_PID;
    }

    if (fcntl(ngx_processes[s].channel[1], F_SETFD, FD_CLOEXEC) == -1) {
      ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
              "fcntl(FD_CLOEXEC) failed while spawning \"%s\"",
               name);
      ngx_close_channel(ngx_processes[s].channel, cycle->log);
      return NGX_INVALID_PID;
    }

    ngx_channel = ngx_processes[s].channel[1];

  } else {
    ngx_processes[s].channel[0] = -1;
    ngx_processes[s].channel[1] = -1;
  }

  ngx_process_slot = s;

  //建立子進程
  pid = fork();

  switch (pid) {

  case -1:
    ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
            "fork() failed while spawning \"%s\"", name);
    ngx_close_channel(ngx_processes[s].channel, cycle->log);
    return NGX_INVALID_PID;

  case 0:
    ngx_pid = ngx_getpid();
    proc(cycle, data);
    break;

  default:
    break;
  }

  ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0, "start %s %P", name, pid);

  ngx_processes[s].pid = pid;
  ngx_processes[s].exited = 0;

  if (respawn >= 0) {
    return pid;
  }

  ngx_processes[s].proc = proc;
  ngx_processes[s].data = data;
  ngx_processes[s].name = name;
  ngx_processes[s].exiting = 0;

  switch (respawn) {

  case NGX_PROCESS_NORESPAWN:
    ngx_processes[s].respawn = 0;
    ngx_processes[s].just_spawn = 0;
    ngx_processes[s].detached = 0;
    break;

  case NGX_PROCESS_JUST_SPAWN:
    ngx_processes[s].respawn = 0;
    ngx_processes[s].just_spawn = 1;
    ngx_processes[s].detached = 0;
    break;

  case NGX_PROCESS_RESPAWN:
    ngx_processes[s].respawn = 1;
    ngx_processes[s].just_spawn = 0;
    ngx_processes[s].detached = 0;
    break;

  case NGX_PROCESS_JUST_RESPAWN:
    ngx_processes[s].respawn = 1;
    ngx_processes[s].just_spawn = 1;
    ngx_processes[s].detached = 0;
    break;

  case NGX_PROCESS_DETACHED:
    ngx_processes[s].respawn = 0;
    ngx_processes[s].just_spawn = 0;
    ngx_processes[s].detached = 1;
    break;
  }

  if (s == ngx_last_process) {
    ngx_last_process++;
  }

  return pid;
}

worker進程

worker進程的主要任務是完成具體的任務邏輯。其主要關注點是與客戶端或後端真實服務器(此時nginx做爲中間代理)之間的數據可讀/可寫 等I/O交互事件,因此工做進程的阻塞點是在像select()、epoll_wait()等這樣的I/O多路複用函數調用處,以等待發生數據可讀/寫事 件。固然也可能被新收到的進程信號中斷。

master進程如何統統知worker進程去作某些工做呢?採用的是信號。

當收到信號時,信號處理函數ngx_signal_handler()就會執行。

對於worker進程的工做方法ngx_worker_process_cycle來講,它主要關注4個全局標誌位:

sig_atomic_t ngx_terminate;//強制關閉進程

sig_atomic_t ngx_quit;//優雅地關閉進程(有惟一一段代碼會設置它,就是接受到QUIT信號。ngx_quit只有在首次設置爲1,時,纔會將ngx_exiting置爲1)

ngx_uint_t ngx_exiting;//退出進程標誌位

sig_atomic_t ngx_reopen;//從新打開全部文件

其中ngx_terminate、ngx_quit 、ngx_reopen都將由ngx_signal_handler根據接受到的信號來設置。ngx_exiting標誌位僅由ngx_worker_cycle方法在退出時做爲標誌位使用。

核心代碼(ngx_process_cycle.c):

static void
ngx_worker_process_cycle(ngx_cycle_t *cycle, void *data)
{
  ngx_int_t worker = (intptr_t) data;

  ngx_uint_t		 i;
  ngx_connection_t  *c;

  ngx_process = NGX_PROCESS_WORKER;

  //子進程初始化
  ngx_worker_process_init(cycle, worker);

  ngx_setproctitle("worker process");

//這裏有一段多線程條件下的代碼。因爲nginx並不支持多線程,所以刪除掉了

  //循環
  for ( ;; ) {
    
    //ngx_exiting標誌位爲1,進程退出
    if (ngx_exiting) {
      c = cycle->connections;
      for (i = 0; i < cycle->connection_n; i++) {
        if (c[i].fd != -1 && c[i].idle) {
          c[i].close = 1;
          c[i].read->handler(c[i].read);
        }
      }

      if (ngx_event_timer_rbtree.root == ngx_event_timer_rbtree.sentinel)
      {
        ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0, "exiting");
        ngx_worker_process_exit(cycle);
      }
    }

    ngx_log_debug0(NGX_LOG_DEBUG_EVENT, cycle->log, 0, "worker cycle");

    ngx_process_events_and_timers(cycle);//處理事件的方法

    //強制結束進程
    if (ngx_terminate) {
      ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0, "exiting");
      ngx_worker_process_exit(cycle);
    }

    //優雅地退出進程
    if (ngx_quit) {
      ngx_quit = 0;
      ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0,
              "gracefully shutting down");
      ngx_setproctitle("worker process is shutting down");

      if (!ngx_exiting) {
        ngx_close_listening_sockets(cycle);
        //設置ngx_exiting 標誌位
        ngx_exiting = 1;
      }
    }

    //從新打開全部文件
    if (ngx_reopen) {
      ngx_reopen = 0;
      ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0, "reopening logs");
      ngx_reopen_files(cycle, -1);
    }
  }
}
相關文章
相關標籤/搜索