여섯번 째 시간이네요.

이번은 납기 보다 조금 빨리 올려서 맘이 편합니다.

엉덩이와 허리는 아프지만...

ㅡ.ㅡ;;

 

http://www.looah.com/article/view/1640

 

 

 

  • 14.4. nginx Internals

  • 14.4. nginx의 내부

  • As was mentioned before, the nginx codebase consists of a core and a number of modules. The core of nginx is responsible for providing the foundation of the web server, web and mail reverse proxy functionalities; it enables the use of underlying network protocols, builds the necessary run-time environment, and ensures seamless interaction between different modules. However, most of the protocol- and application-specific features are done by nginx modules, not the core.
  • 이전에 언급 한 것처럼, nginx의 코드베이스는 코어와 다수의 모듈로 구성되어 있다. nginx의 코어는 웹과 메일 리버스 프록시 기능과 같은 웹 서버의 기반을 제공하는 역할을 하는데, 그것은 내부 네트웍 프로토콜을 사용할 수 있게 하고, 필요한 런타임 환경을 구성하고, 다름 모듈간에 원활한 상호작용을 보장한다. 그러나, 프로토콜 및 응용 프로그램에 특정한 기능의 대부분은 코어가 아닌 nginx 모듈에 의해 수행된다.

  • Internally, nginx processes connections through a pipeline, or chain, of modules. In other words, for every operation there's a module which is doing the relevant work; e.g., compression, modifying content, executing server-side includes, communicating to the upstream application servers through FastCGI or uwsgi protocols, or talking to memcached.
  • 내부적으로, nginx 프로세스는 모듈의 파이프 라인, 또는 체인을 통해 연결한다. 다시 말하면, 모든 작업에 대하여 관련 작업을 수행하는 모듈이 있다. 예을 들면, 압축, 컨텐츠 수정, 서버-사이드 실챙을 포함하여, FastCGI 나 uwsgi 프로토콜, 또는 memcached와의 연계를 통한 업스트림 응용 서버와의 통신이 있다.

  • There are a couple of nginx modules that sit somewhere between the core and the real "functional" modules. These modules arehttp and mail. These two modules provide an additional level of abstraction between the core and lower-level components. In these modules, the handling of the sequence of events associated with a respective application layer protocol like HTTP, SMTP or IMAP is implemented. In combination with the nginx core, these upper-level modules are responsible for maintaining the right order of calls to the respective functional modules. While the HTTP protocol is currently implemented as part of the http module, there are plans to separate it into a functional module in the future, due to the need to support other protocols like SPDY (see "SPDY: An experimental protocol for a faster web").
  • 코어와 실제 "기능" 모듈 사이의 어딘가에 위치한 nginx 모듈 몇 가지가 있다. 이 모듈들은 http와 mail 이다. 이 두 모듈은 코어와 낮은 수준의 구성요소 사이의 추상화 수준을 추가로 제공한다. 이러한 모듈에서, HTTP, SMTP 또는 IMAP과 같은 각각의 애플리케이션 계층 프로토콜과 연관된 일련의 이벤트 처리가 구현된다. nginx 코어와의 조합에서는 이러한 상위 수준의 모듈은 각 기능 모듈 호출의 올바른 순서를 유지하기 위한 역할을 한다. HTTP 프로토콜은 현재 http 모듈의 일부로 구현되어 있으나, SPDY와 같은 다른 프로토콜을 지원해야 하는 필요성으로 인해, 향후에는 기능성 모듈로 분리하기 위한 계획이 있다. ("SPDY:빠른 웹에 대한 실험 프로토콜" 참조)

  • The functional modules can be divided into event modules, phase handlers, output filters, variable handlers, protocols, upstreams and load balancers. Most of these modules complement the HTTP functionality of nginx, though event modules and protocols are also used for mail. Event modules provide a particular OS-dependent event notification mechanism like kqueue or epoll. The event module that nginx uses depends on the operating system capabilities and build configuration. Protocol modules allow nginx to communicate through HTTPS, TLS/SSL, SMTP, POP3 and IMAP.
  • 기능성 모듈들은 이벤트 모듈, 위상 처리기, 출력 필터, 변수 처리기, 프로토콜, 업스트림 및 부하 분산 장치로 나눌 수 있다. 이벤트 모듈과 프로토콜은 메일에 사용 되기도 하지만, 이런 모듈들의 대부분은 nginx의 HTTP 기능을 보완하는 역할을 한다. 이벤트 모듈들은 kqueue 또는 epoll과 같은 특정 OS 의존적 이벤트 통지 메커니즘을 제공한다. nginx가 이용하는 이벤트 모듈은 운영 시스템의 기능과 설정 구성에 의존적이다. 프로토콜 모듈은 nginx에서 HTTPS, TLS/SSL, SMTP, POP3 및 IMAP 통신이 가능하도록 한다.

  • A typical HTTP request processing cycle looks like the following.
  • 전형적인 HTTP 요청 처리 주기는 다음과 같다.

  • - Client sends HTTP request.
  • 클라이언트가 HTTP request 를 보낸다.
  • - nginx core chooses the appropriate phase handler based on the configured location matching the request.
  • nginx 코어는 request 에 맞는 설정된 영역에 기반한 적절한 페이즈 핸들러를 선택한다.
  • - If configured to do so, a load balancer picks an upstream server for proxying.
  • 설정된 경우에는 로드밸런서가 프록시을 위한 업스트림 서버를 선택한다.
  • - Phase handler does its job and passes each output buffer to the first filter.
  • 페이즈 핸들러가 데이터 처리를 하고 첫번째 필터로 각각의 출력 버퍼를 보낸다.
  • - First filter passes the output to the second filter.
  • 첫번째 필터는 출력된 결과를 두번째 필터로 보낸다.
  • - Second filter passes the output to third (and so on).
  • 두번째 필터는 출력된 결과를 세번째 필터로 보낸다. (이하 필터로 반복된다.)
  • - Final response is sent to the client.
  • 최종 response 가 클라이언트로 전송된다.
  • nginx module invocation is extremely customizable. It is performed through a series of callbacks using pointers to the executable functions. However, the downside of this is that it may place a big burden on programmers who would like to write their own modules, because they must define exactly how and when the module should run. Both the nginx API and developers' documentation are being improved and made more available to alleviate this.
  • Nginx 모듈 호출은 매우 사용자 정의적이다. 이것은 실행 함수에 대한 포인터를 이용하는 일련의 콜백을 통해 수행된다. 그러나, 단점은 자신의 모듈을 작성하고 싶은 개발자에게 큰 부담이 될 수 있는데 왜냐하면, 개발자는 반드시 모듈이 어떻게 그리고 언제 실행되어야 하는지 정확하게 정의해야 하기 때문이다. nginx API와 개발자 문서는 이런 부담을 완화시키기 위해서 개선되고 더 사용하기 편하게 제공되고 있다.

  • Some examples of where a module can attach are:
  • 모듈을 장착 할 수 있는 위치의 몇 가지 예는 다음과 같다.

  • - Before the configuration file is read and processed
  • - 설정 파일을 읽고 처리되기 전

  • - For each configuration directive for the location and the server where it appears
  • - location과 server의 각 설정 지시어가 있는 곳

  • - When the main configuration is initialized
  • - 메인 설정이 초기화될 때

  • - When the server (i.e., host/port) is initialized
  • - host/port 등을 설정하는 server가 초기화될 때

  • - When the server configuration is merged with the main configuration
  • - server 설정이 메인 설정에 통합될 때

  • - When the location configuration is initialized or merged with its parent server configuration
  • - location 설정이 시작되거나 그것의 상위 server 설정과 통합될 때

  • - When the master process starts or exits
  • - 마스터 프로세스가 시작되거나 끝날 때

  • - When a new worker process starts or exits
  • - 새로운 worker 프로세스가 시작하거나 끝날 때

  • - When handling a request
  • - 요청을 처리할 때

  • - When filtering the response header and the body
  • - 응답 헤더와 바디를 필터링할 때

  • - When picking, initiating and re-initiating a request to an upstream server
  • - 업스트립 서버로의 요청을 선별하고 시작하고 재시작할 때

  • - When processing the response from an upstream server
  • - 업스트립 서버로부터의 응답을 처리할 때

  • - When finishing an interaction with an upstream server
  • - 업스트림 서버와의 연동을 종료할 때

  • Inside a worker, the sequence of actions leading to the run-loop where the response is generated looks like the following:
  • worker 내부에서, 응답이 생성될 때 실행-루프로 이어지는 동작의 순서는 다음과 같다.

  • - Begin ngx_worker_process_cycle().
  • - ngx_worker_process_cycle() 시작

  • - Process events with OS specific mechanisms (such as epoll or kqueue).
  • - OS 특정 메커니즘에 따른 이벤트 처리 (epoll 또는 kqueue와 같은)

  • - Accept events and dispatch the relevant actions.
  • - 이벤트 접수 및 관련 작업 디스패치

  • - Process/proxy request header and body.
  • - 요청 헤더와 바디에 대한 처리/프록시

  • - Generate response content (header, body) and stream it to the client.
  • - 응답 컨텐츠(헤더, 바디) 생성과 클라이언트로 전송

  • - Finalize request.
  • - 요청 마감

  • - Re-initialize timers and events.
  • - 타이머와 이벤트의 재 초기화

  • The run-loop itself (steps 5 and 6) ensures incremental generation of a response and streaming it to the client.
  • 런-루프 자체는 (5단계 ​​및 6단계) 응답의 증분 생성 및 클라이언트로 스트리밍을 보장
    * 5단계 : 응답 컨텐츠(헤더, 바디) 생성과 클라이언트로 전송
    * 6단계 : 요청 마감

  • A more detailed view of processing an HTTP request might look like this:
  • HTTP 요청 처리의 더욱 상세한 내용은 다음과 같다.

  • - Initialize request processing.
  • - 요청 처리 초기화

  • - Process header.
  • - 헤더 처리

  • - Process body.
  • - 바디 처리

  • - Call the associated handler.
  • - 관련 핸들러 호출

  • - Run through the processing phases.
  • - 처리 단계를 거쳐 실행

  • Which brings us to the phases. When nginx handles an HTTP request, it passes it through a number of processing phases. At each phase there are handlers to call. In general, phase handlers process a request and produce the relevant output. Phase handlers are attached to the locations defined in the configuration file.
  • 이런 것들은 우리에게 단계를 제공한다. nginx는 HTTP 요청을 처리 할 때, 다수의 처리 단계의 통해 수행된다. 각 단계에는 호출하는 핸들러가 있다. 일반적으로, 위상 처리기는 요청을 처리하고 해당 출력을 생성한다. 위상 처리기는 설정 파일에 정의된 위치에서 사용된다.

  • Phase handlers typically do four things: get the location configuration, generate an appropriate response, send the header, and send the body. A handler has one argument: a specific structure describing the request. A request structure has a lot of useful information about the client request, such as the request method, URI, and header.
  • 위상 처리기는 일반적으로 4가지 일을 한다. 위치 설정을 가져오고, 적정한 응답을 생성하고, 헤더를 전송하고, 바디를 전송한다. 처리기는 요청을 설명하는 구체적인 구조를 하나의 아규먼트로 갖는다. 요청 구조는 요청 방법, URI, 헤더와 같이 클라이언트의 요청에 대한 많은 유용한 정보를 제공한다.

  • When the HTTP request header is read, nginx does a lookup of the associated virtual server configuration. If the virtual server is found, the request goes through six phases:
  • HTTP 요청 헤더를 읽을 때, nginx는 관련된 가상 서버 설정을 조회하고, 가상 서버가 발견되면, 요청은 6 단계를 통해 수행된다.

  • - server rewrite phase
  • - 서버 rewrite 단계

  • - location phase
  • - 위치 단계

  • - location rewrite phase (which can bring the request back to the previous phase)
  • - 위치 rewrite 단계 (이 단계에서 요청은 이전 단계로 갈 수도 있다.)

  • - access control phase
  • - 접근 제어 단계

  • - try_files phase
  • - try_files 단계

  • - log phase
  • - 로깅 단계

  • In an attempt to generate the necessary content in response to the request, nginx passes the request to a suitable content handler. Depending on the exact location configuration, nginx may try so-called unconditional handlers first, like perl, proxy_pass,flv, mp4, etc. If the request does not match any of the above content handlers, it is picked by one of the following handlers, in this exact order: random index, index, autoindex, gzip_static, static.
  • 요청에 대한 응답에 필요한 컨텐츠를 생성하는 시도에서, nginx는 요청을 적당한 컨텐츠 핸들러에게 전달한다. 정확한 위치 설정에 따라, nginx는 perl, proxy_pass, flv, mp4 등과 같이 소위 말하는 무조건 핸들러에게 가장 먼저 시도할 수도 있다. 만약 요청이 이전의 컨텐츠 핸들러와 맞는게 없으면, 정확한 순서에 따라 랜덤 인덱스, 인덱스, 오토인덱스, gzip_static, static 중 하나의 핸들러로 선별된다.