当前位置: 首页 > 工具软件 > ngx-moment > 使用案例 >

nginx ngx_times

郦祯
2023-12-01


/*
 * Copyright (C) Igor Sysoev
 */




#ifndef _NGX_TIMES_H_INCLUDED_
#define _NGX_TIMES_H_INCLUDED_




#include <ngx_config.h>
#include <ngx_core.h>




typedef struct {
    time_t      sec;
    ngx_uint_t  msec;
    ngx_int_t   gmtoff;
} ngx_time_t;




void ngx_time_init(void);
void ngx_time_update(time_t sec, ngx_uint_t msec);
u_char *ngx_http_time(u_char *buf, time_t t);
u_char *ngx_http_cookie_time(u_char *buf, time_t t);
void ngx_gmtime(time_t t, ngx_tm_t *tp);


time_t ngx_next_time(time_t when);
#define ngx_next_time_n      "mktime()"




extern volatile ngx_time_t  *ngx_cached_time;


#define ngx_time()           ngx_cached_time->sec
#define ngx_timeofday()      (ngx_time_t *) ngx_cached_time


extern volatile ngx_str_t    ngx_cached_err_log_time;
extern volatile ngx_str_t    ngx_cached_http_time;
extern volatile ngx_str_t    ngx_cached_http_log_time;


/*
 * milliseconds elapsed since epoch and truncated to ngx_msec_t,
 * used in event timers
 */
extern volatile ngx_msec_t  ngx_current_msec;




#endif /* _NGX_TIMES_H_INCLUDED_ */




/*
 * Copyright (C) Igor Sysoev
 */




#include <ngx_config.h>
#include <ngx_core.h>




/*
 * The time may be updated by signal handler or by several threads.
 * The time update operations are rare and require to hold the ngx_time_lock.
 * The time read operations are frequent, so they are lock-free and get time
 * values and strings from the current slot.  Thus thread may get the corrupted
 * values only if it is preempted while copying and then it is not scheduled
 * to run more than NGX_TIME_SLOTS seconds.
 */


#define NGX_TIME_SLOTS   64


static ngx_uint_t        slot;
static ngx_atomic_t      ngx_time_lock;


volatile ngx_msec_t      ngx_current_msec;
volatile ngx_time_t     *ngx_cached_time;
volatile ngx_str_t       ngx_cached_err_log_time;
volatile ngx_str_t       ngx_cached_http_time;
volatile ngx_str_t       ngx_cached_http_log_time;


static ngx_time_t        cached_time[NGX_TIME_SLOTS];
static u_char            cached_err_log_time[NGX_TIME_SLOTS]
                                    [sizeof("1970/09/28 12:00:00")];
static u_char            cached_http_time[NGX_TIME_SLOTS]
                                    [sizeof("Mon, 28 Sep 1970 06:00:00 GMT")];
static u_char            cached_http_log_time[NGX_TIME_SLOTS]
                                    [sizeof("28/Sep/1970:12:00:00 +0600")];




static char  *week[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
static char  *months[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
                           "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };


void
ngx_time_init(void)
{
    ngx_cached_err_log_time.len = sizeof("1970/09/28 12:00:00") - 1;
    ngx_cached_http_time.len = sizeof("Mon, 28 Sep 1970 06:00:00 GMT") - 1;
    ngx_cached_http_log_time.len = sizeof("28/Sep/1970:12:00:00 +0600") - 1;


    ngx_cached_time = &cached_time[0];


    ngx_time_update(0, 0);
}




void
ngx_time_update(time_t sec, ngx_uint_t msec)
{
    u_char          *p0, *p1, *p2;
    ngx_tm_t         tm, gmt;
    ngx_time_t      *tp;
    struct timeval   tv;


    if ( !ngx_trylock( &ngx_time_lock ) ) 
{
        return;
    }


    if ( sec == 0 ) 
{
        ngx_gettimeofday( &tv );


        sec = tv.tv_sec;
        msec = tv.tv_usec / 1000;
    }


    ngx_current_msec = (ngx_msec_t) sec * 1000 + msec;


    tp = &cached_time[slot];


    if ( tp->sec == sec )
{
        tp->msec = msec;


        ngx_unlock(&ngx_time_lock);


        return;
    }


    if ( slot == NGX_TIME_SLOTS - 1 )
{
        slot = 0;
    } 
else 
{
        slot++;
    }


    tp = &cached_time[slot];


    tp->sec = sec;
    tp->msec = msec;


    ngx_gmtime(sec, &gmt);




    p0 = &cached_http_time[slot][0];


    (void) ngx_sprintf(p0, "%s, %02d %s %4d %02d:%02d:%02d GMT",
                       week[gmt.ngx_tm_wday], gmt.ngx_tm_mday,
                       months[gmt.ngx_tm_mon - 1], gmt.ngx_tm_year,
                       gmt.ngx_tm_hour, gmt.ngx_tm_min, gmt.ngx_tm_sec);


#if (NGX_HAVE_GETTIMEZONE)


    tp->gmtoff = ngx_gettimezone();
    ngx_gmtime(sec + tp->gmtoff * 60, &tm);


#elif (NGX_HAVE_GMTOFF)


    ngx_localtime(sec, &tm);
    tp->gmtoff = (ngx_int_t) (tm.ngx_tm_gmtoff / 60);


#else


    ngx_localtime(sec, &tm);
    tp->gmtoff = ngx_timezone(tm.ngx_tm_isdst);


#endif




    p1 = &cached_err_log_time[slot][0];


    (void) ngx_sprintf(p1, "%4d/%02d/%02d %02d:%02d:%02d",
                       tm.ngx_tm_year, tm.ngx_tm_mon,
                       tm.ngx_tm_mday, tm.ngx_tm_hour,
                       tm.ngx_tm_min, tm.ngx_tm_sec);




    p2 = &cached_http_log_time[slot][0];


    (void) ngx_sprintf(p2, "%02d/%s/%d:%02d:%02d:%02d %c%02d%02d",
                       tm.ngx_tm_mday, months[tm.ngx_tm_mon - 1],
                       tm.ngx_tm_year, tm.ngx_tm_hour,
                       tm.ngx_tm_min, tm.ngx_tm_sec,
                       tp->gmtoff < 0 ? '-' : '+',
                       ngx_abs(tp->gmtoff / 60), ngx_abs(tp->gmtoff % 60));




    ngx_memory_barrier(); // NB,  告诉编译器不要优化排序,因为如果乱序的话,前面还没有填充好内容,


//下面就把这个没有初始化好内容的指针赋值给了多线程访问的ngx_cached_time


    ngx_cached_time = tp;
    ngx_cached_http_time.data = p0;
    ngx_cached_err_log_time.data = p1;
    ngx_cached_http_log_time.data = p2;


    ngx_unlock( &ngx_time_lock );
}


//另一种格式的字符串


u_char *
ngx_http_time( u_char *buf, time_t t )
{
    ngx_tm_t  tm;


    ngx_gmtime( t, &tm );


    return ngx_sprintf( buf, "%s, %02d %s %4d %02d:%02d:%02d GMT",
                       week[tm.ngx_tm_wday],
                       tm.ngx_tm_mday,
                       months[tm.ngx_tm_mon - 1],
                       tm.ngx_tm_year,
                       tm.ngx_tm_hour,
                       tm.ngx_tm_min,
                       tm.ngx_tm_sec );
}


//将时间t格式化为 nginx的tm结构体类型,然后组装成一个字符串


u_char *
ngx_http_cookie_time( u_char *buf, time_t t )
{
    ngx_tm_t  tm;


    ngx_gmtime( t, &tm );


    /*
     * Netscape 3.x does not understand 4-digit years at all and
     * 2-digit years more than "37"
     */


    return ngx_sprintf( buf,
                       (tm.ngx_tm_year > 2037) ?
                                         "%s, %02d-%s-%d %02d:%02d:%02d GMT":
                                         "%s, %02d-%s-%02d %02d:%02d:%02d GMT",
                       week[tm.ngx_tm_wday],
                       tm.ngx_tm_mday,
                       months[tm.ngx_tm_mon - 1],
                       (tm.ngx_tm_year > 2037) ? tm.ngx_tm_year:
                                                 tm.ngx_tm_year % 100,
                       tm.ngx_tm_hour,
                       tm.ngx_tm_min,
                       tm.ngx_tm_sec );
}




//将time_t变为  ngx的tm结构体类型


void
ngx_gmtime(time_t t, ngx_tm_t *tp)
{
    ngx_int_t   yday;
    ngx_uint_t  n, sec, min, hour, mday, mon, year, wday, days, leap;


    /* the calculation is valid for positive time_t only */


    n = (ngx_uint_t) t;


    days = n / 86400;


    /* Jaunary 1, 1970 was Thursday */


    wday = (4 + days) % 7;


    n %= 86400;
    hour = n / 3600;
    n %= 3600;
    min = n / 60;
    sec = n % 60;


    /*
     * the algorithm based on Gauss' formula,
     * see src/http/ngx_http_parse_time.c
     */


    /* days since March 1, 1 BC */
    days = days - (31 + 28) + 719527;


    /*
     * The "days" should be adjusted to 1 only, however, some March 1st's go
     * to previous year, so we adjust them to 2.  This causes also shift of the
     * last Feburary days to next year, but we catch the case when "yday"
     * becomes negative.
     */


    year = (days + 2) * 400 / (365 * 400 + 100 - 4 + 1);


    yday = days - (365 * year + year / 4 - year / 100 + year / 400);


    if (yday < 0) {
        leap = (year % 4 == 0) && (year % 100 || (year % 400 == 0));
        yday = 365 + leap + yday;
        year--;
    }


    /*
     * The empirical formula that maps "yday" to month.
     * There are at least 10 variants, some of them are:
     *     mon = (yday + 31) * 15 / 459
     *     mon = (yday + 31) * 17 / 520
     *     mon = (yday + 31) * 20 / 612
     */


    mon = (yday + 31) * 10 / 306;


    /* the Gauss' formula that evaluates days before the month */


    mday = yday - (367 * mon / 12 - 30) + 1;


    if (yday >= 306) {


        year++;
        mon -= 10;


        /*
         * there is no "yday" in Win32 SYSTEMTIME
         *
         * yday -= 306;
         */


    } else {


        mon += 2;


        /*
         * there is no "yday" in Win32 SYSTEMTIME
         *
         * yday += 31 + 28 + leap;
         */
    }


    tp->ngx_tm_sec = (ngx_tm_sec_t) sec;
    tp->ngx_tm_min = (ngx_tm_min_t) min;
    tp->ngx_tm_hour = (ngx_tm_hour_t) hour;
    tp->ngx_tm_mday = (ngx_tm_mday_t) mday;
    tp->ngx_tm_mon = (ngx_tm_mon_t) mon;
    tp->ngx_tm_year = (ngx_tm_year_t) year;
    tp->ngx_tm_wday = (ngx_tm_wday_t) wday;
}


//今天0:00:00开始,过when秒后是多少时间, 获取本地时间,递增指定的秒数,再转化为time_t


time_t
ngx_next_time( time_t when )
{
    time_t     now, next;
    struct tm  tm;


    now = ngx_time();


    ngx_libc_localtime( now, &tm );


    tm.tm_hour = (int) ( when / 3600 );


    when %= 3600;


    tm.tm_min = (int) (when / 60);


    tm.tm_sec = (int) (when % 60);


    next = mktime( &tm );


    if ( next == -1 )
{
        return -1;
    }


    if ( next - now > 0 ) 
{
        return next;
    }


    tm.tm_mday++;


    /* mktime() should normalize a date (Jan 32, etc) */


    next = mktime( &tm );


    if ( next != -1 )
{
        return next;
    }


    return -1;
}


参考文章: http://blog.csdn.net/fengmo_q/article/details/6302354 


nginx为了减少系统调用的次数,将时间缓存起来, 缓存了几种格式的字符串, 老的内容读到也没有问题,1秒的误差也是可以接受的


每次 epoll_wait返回的时候更新一下时间 (可设定)调用下  ngx_time_update 函数 ,还有一个是在信号处理函数中调用



    if ( ngx_timer_resolution && !(ngx_event_flags & NGX_USE_TIMER_EVENT ) ) 
{
        struct sigaction  sa;
        struct itimerval  itv;


        ngx_memzero(&sa, sizeof(struct sigaction));


        sa.sa_handler = ngx_timer_signal_handler;


        sigemptyset(&sa.sa_mask);


        if ( sigaction(SIGALRM, &sa, NULL) == -1 ) 
{
            ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                          "sigaction(SIGALRM) failed");
            return NGX_ERROR;
        }


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


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



void
ngx_timer_signal_handler(int signo)
{
    ngx_event_timer_alarm = 1;


    ngx_time_update(0, 0);


#if 1
    ngx_log_debug0(NGX_LOG_DEBUG_EVENT, ngx_cycle->log, 0, "timer signal");
#endif
}


 类似资料:

相关阅读

相关文章

相关问答