Four: In-depth nginx events and connections (one)

Source: Internet
Author: User
Tags epoll
Nginx is essentially an event-driven Web server, and the event processing framework solves the problem of how to collect, manage, and distribute events.
The events were mainly

    • Network Events (TCP network events are primarily)
    • Timer events

Nginx defines a core module Ngx_event_module, refer to the blog a deep understanding of Nginx Modular, global view, Nginx will call the Ngx_init_cycle method when the configuration file is started, once found in nginx.conf is interested in "Events {}" configuration item, the Ngx_event_module module has started to work. The Ngx_event_core_module module in the core module Ngx_event_module defines which event-driven mechanism this module will use and how to manage events.

The event module is a new type of module, nginx_module_t represents the Nginx module interface, and for each of the different types of modules, there is a structure to describe the common interface of this class of modules, which is stored in the CTX member of the ngx_module_t structure. The universal interface of the core module is ngx_core_module_t, the event common interface is the ngx_event_module_t struct:

typedefstruct {//位于文件 ngx_event.h//事件模块 的名字    ngx_str_t              *name;    //在解析 配置前,这个回调 方法用于创建存储配置选项参数的结构体void                 *(*create_conf)(ngx_cycle_t *cycle);    // 在解析配置项完成 之后,init_conf方法会被调用,用以综合处理当前事件模块感兴趣的全部配置项char                 void *conf);    // 对于事件驱动机制,每个事件模块需要实现10个抽象方法     ngx_event_actions_t     actions;} ngx_event_module_t;

ngx_event_module_tis the actions core method of defining an event-driven module.

typedefstruct{/ * Add an event method that will be responsible for adding 1 events of interest to the event-driven mechanism provided by the operating system * /ngx_int_t (*add) (ngx_event_t *ev, ngx_int_t event, ngx_uint_t flags);/ * Delete the event method, which removes 1 events that already exist in the event-driven mechanism * /ngx_int_t (*del) (ngx_event_t *ev, ngx_int_t event, ngx_uint_t flags);/* Enable 1 events, the current event framework does not call this method, most of the event-driven module implementation of this method is exactly the same as the above Add method */ngx_int_t (*enable) (ngx_event_t *ev, ngx_int_t event, ngx_uint_t flags);/* Disable 1 events, the current event framework does not call this method, most of the event drivers for this method implementation is exactly the same as the above Del method */ngx_int_t (*disable) (ngx_event_t *ev, ngx_int_t event, ngx_uint_t flags);/* Adds a new connection to the event-driven mechanism, which means that read-write events on the connection are added to the event-driven mechanism */ngx_int_t (*add_conn) (ngx_connection_t *c);/* Remove a connected read-write event from the event-driven mechanism */ngx_int_t (*del_conn) (ngx_connection_t *c, ngx_uint_t flags);/ * Only in multi-threaded environment will be called, at present Nginx in the product environment will not run in multi-threaded mode * *ngx_int_t (*notify) (ngx_event_handler_pt handler);/ * In a normal work cycle, the Process_events method is called to handle the event * /ngx_int_t (*process_events) (ngx_cycle_t *cycle, ngx_msec_t timer, ngx_uint_t flags);/ * Initialize the event driver module * /ngx_int_t (*init) (ngx_cycle_t *cycle, ngx_msec_t timer);///method to be called before exiting the event driver modulevoid(*done) (ngx_cycle_t *cycle);} ngx_event_actions_t;

Both the Ngx_event_core_module and the 9 event-driven modules must implement NGX_EVENT_MODULE_T interfaces ngx_module_t the CTX members of the struct

structngx_event_s {/ * Event-related object, usually data points to the Ngx_connection_t connection object. When you turn on file asynchronous I/O, it may point to */void*data;/ * Flag bit, which identifies the event writable, meaning that the corresponding TCP connection is writable, that is, the connection is in the sending network packet status * /unsignedWrite1;/ * Flag bit, identifies a new connection to be established, usually marked in the corresponding read event of the ngx_listening_t * /unsignedAccept1;/ * Detects if the current event is out-of-date, it is only for the driver module, and the event consumption module can not care about * */ * Used to detect the stale events in Kqueue and Epoll * *unsignedInstance1;/ * * The event was passed or would is passed to a kernel;     * In Aio Mode-operation is posted. */unsignedActive1;unsignedDisabled1;/* The Ready event, in AIO mode 0 means, no operation can be posted * /unsignedReady1;unsignedOneShot1;/ * AIO Operation is complete */unsignedComplete1;unsignedEof:1;unsignedError1;unsignedTimedOut:1;unsignedTimer_set:1;unsignedDelayed1;unsignedDeferred_accept:1;/ * The pending EOF reported by Kqueue, Epoll or in AIO chain operation * /unsignedPending_eof:1;unsignedPosted1;unsignedClosed1;/ * To test on worker exit * /unsignedChannel1;unsignedResolver1;unsignedCancelable:1;#if (NGX_WIN32)/* setsockopt (So_update_accept_context) was successful */unsignedAccept_context_updated:1;#endif#if (ngx_have_kqueue)unsignedKq_vnode:1;/ * The Pending errno reported by Kqueue * /intKq_errno;#endif/* * Kqueue only: * Accept:number of sockets The wait to be accepted * read:bytes to read When event was ready * or Lowat when event was set with Ngx_lowat_event flag * WRITE:AVAILABL  "E Space in buffer" when event was ready * or Lowat when event was set with Ngx_lowat_event flag * * Epoll with Epollrdhup: * accept:1 If accept many, 0 otherwise * read:1 If there can is data to re AD, 0 otherwise * * Iocp:todo * * Otherwise: * accept:1 If accept many, 0 otherwise */#if (ngx_have_kqueue) | | (NGX_HAVE_IOCP)intAvailable#elseunsignedAvailable1;#endifNgx_event_handler_pt handler;#if (NGX_HAVE_IOCP)ngx_event_ovlp_t OVLP;#endifngx_uint_t index; ngx_log_t *Log; ngx_rbtree_node_t timer;/ * The posted queue * /ngx_queue_tQueue;#if 0/ * The Threads support * //* * The event thread context, we store it here * if $ (CC) does not understand __thread declaration * and Pthread_getspecific () is too costly */void*thr_ctx;#if (ngx_event_t_padding)/ * Event should not cross cache line in SMP */uint32_t padding[ngx_event_t_padding];#endif#endif};#if (Ngx_have_file_aio)structngx_event_aio_s {void*data;    Ngx_event_handler_pt handler; ngx_file_t *file;#if (ngx_have_aio_sendfile)ssize_t (*preload_handler) (ngx_buf_t *file);#endifngx_fd_t FD;#if (NGX_HAVE_EVENTFD)int64_t Res;#endif#if! (NGX_HAVE_EVENTFD) | | (Ngx_test_build_epoll)ngx_err_t err; size_t nbytes;#endifngx_aiocb_t AIOCB; ngx_event_t event;};#endif

Connection to Nginx

Passive connection

This connection refers to a client-initiated connection that the server passively accepts

//in file Ngx_connection.hstructngx_connection_s {/ * When the connection is not in use, the data member is used to act as the next pointer in the free list in the connection pool. When a connection is used, the meaning of data is determined by the Nginx module that uses it. In the HTTP module, data points to the ngx_http_request_t request * /void*data;//Connect the corresponding Read eventngx_event_t *read;//Connect the corresponding write eventsngx_event_t *write;//Socket handlengx_socket_t FD;//method of directly receiving network character streamNgx_recv_pt recv;//Direct transmission of network character streamsNgx_send_pt send;//The method of receiving network character stream with ngx_chain_t list as parameterNgx_recv_chain_pt Recv_chain;//The method of sending network character stream with ngx_chain_t list as parameterNgx_send_chain_pt Send_chain;/ * This connection corresponds to the Ngx_listening_t listener object, which is established by the event of the Listening listener port * /ngx_listening_t *listening;//The number of bytes that have been sent on this connectionOff_t sent;//ngx_log_t object that can log logsngx_log_t *Log;/ * Memory pool. Typically when you accept a new connection, a memory pool is created, and the memory pool is destroyed at the end of the connection. All ngx_connectionn_t structures are pre-allocated, and the size of the memory pool will be determined by the pool_size members of the listening listener above.ngx_pool_t *pool;intType//SOCKADDR structure for connecting clientsstructSOCKADDR *sockaddr;//Connecting the length of the SOCKADDR structureSocklen_t Socklen;//Connect the IP address in the form of a client stringngx_str_t Addr_text;    ngx_str_t proxy_protocol_addr; in_port_t Proxy_protocol_port;#if (NGX_SSL)Ngx_ssl_connection_t *ssl;#endif/ * The SOCKADDR structure corresponding to the native listener port, which is the sock addr member in the Listening listener * /structSOCKADDR *local_sockaddr; Socklen_t Local_socklen;/* For receiving and caching the byte stream from the client, each event consumption module is free to decide how much space to allocate from the connection pool to buffer this cache field * /ngx_buf_t *buffer; ngx_queue_tQueue;//connection usage times. NGX_CONNECTION_T structure each time a connection from the client is established, or the active back-end server initiates a connection, number is added 1*/ngx_atomic_uint_t number;//number of processing requestsngx_uint_t requests;unsignedBuffered8;unsignedLog_error:3;/ * Ngx_connection_log_error_e * /unsignedTimedOut:1;unsignedError1;unsignedDestroyed:1;unsignedIdle1;unsignedReusable:1;unsignedClose1;unsignedShared1;unsignedSendfile1;unsignedSndlowat:1;unsignedTcp_nodelay:2;/ * Ngx_connection_tcp_nodelay_e * /unsignedTcp_nopush:2;/ * Ngx_connection_tcp_nopush_e * /unsignedNEED_LAST_BUF:1;#if (NGX_HAVE_IOCP)unsignedAccept_context_updated:1;#endif#if (ngx_have_aio_sendfile)unsignedBusy_count:2;#endif#if (ngx_threads)ngx_thread_task_t *sendfile_task;#endif};

Active connection

As a Web server, Nginx also needs to initiate connections to other servers, use ngx_peer_connection_t structs to represent active connections, and many of the features of a pending connection are defined in the passive connection ngx_connection_t, so Ngx_peer_connection_ The structure of the ngx_connection_t is referenced in the T structure body.

//When communicating with an upstream server using a long connection, you can obtain a new connection from the connection pool by this methodtypedefngx_int_t (*ngx_event_get_peer_pt) (ngx_peer_connection_t *pc,void*data);//When using a long connection to communicate with the upstream server, use this method to release the completed connection to the connection pooltypedefvoid(*NGX_EVENT_FREE_PEER_PT) (Ngx_peer_connection_t *pc,void*data, ngx_uint_t State);structngx_peer_connection_s {/ * An active connection actually needs to ngx_connection_t the majority of the members of the struct, and is considered for reuse and defines the connecion*/Ngx_connection_t *connection;//remote server SOCKETADDRstructSOCKADDR *sockaddr;//sockaddr address lengthSocklen_t Socklen;//The name of the remote serverngx_str_t *name;//Indicates the number of times that a remote server can be retried after an exception has failed on the current connection, that is, the maximum number of failures allowedNgx_uint_t tries;    ngx_msec_t start_time;    Ngx_event_get_peer_pt get; Ngx_event_free_peer_pt Free;void*data;#if (NGX_SSL)Ngx_event_set_peer_session_pt set_session; Ngx_event_save_peer_session_pt save_session;#endif//Native address informationngx_addr_t *local;intType//The receive buffer size of the socketintRcvbuf;//ngx_log_t object for loggingngx_log_t *Log;unsignedCached1;#if (ngx_have_transparent_proxy)unsignedTransparent1;#endif/ * Ngx_connection_log_error_e * /unsignedLog_error:2;};

'). addclass (' pre-numbering '). Hide (); $ (this). addclass (' has-numbering '). Parent (). append ($numbering); for (i = 1; i <= lines; i++) {$numbering. Append ($ ('
  • '). Text (i)); }; $numbering. FadeIn (1700); }); });

    The above describes four: in-depth nginx events and connections (one), including aspects of the content, I hope to be interested in PHP tutorial friends helpful.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.