为什么PostgreSQL启动后有个UDP监听localhost - pgstat统计信息进程间通信

1 minute read

背景

PostgreSQL启动后,通过netstat -anpo可以看到监听了一个UDP端口。

udp 0 0 127.0.0.1:51869 127.0.0.1:51869 ESTABLISHED 13443/postgres  

为什么呢?

这个端口干什么用的?

有没有危险?

用于pgstat进程发送和接收统计信息用的,见代码:

src/backend/postmaster/pgstat.c

/* ----------  
 * pgstat_init() -  
 *  
 *      Called from postmaster at startup. Create the resources required  
 *      by the statistics collector process.  If unable to do so, do not  
 *      fail --- better to let the postmaster start with stats collection  
 *      disabled.  
 * ----------  
 */  
void  
pgstat_init(void)  
{  
        ACCEPT_TYPE_ARG3 alen;  
        struct addrinfo *addrs = NULL,  
                           *addr,  
                                hints;  
        int                     ret;  
        fd_set          rset;  
        struct timeval tv;  
        char            test_byte;  
        int                     sel_res;  
        int                     tries = 0;  
  
#define TESTBYTEVAL ((char) 199)  
  
        /*  
         * This static assertion verifies that we didn't mess up the calculations  
         * involved in selecting maximum payload sizes for our UDP messages.  
         * Because the only consequence of overrunning PGSTAT_MAX_MSG_SIZE would  
         * be silent performance loss from fragmentation, it seems worth having a  
         * compile-time cross-check that we didn't.  
         */  
        StaticAssertStmt(sizeof(PgStat_Msg) <= PGSTAT_MAX_MSG_SIZE,  
                                   "maximum stats message size exceeds PGSTAT_MAX_MSG_SIZE");  
  
        /*  
         * Create the UDP socket for sending and receiving statistic messages  
         */  
        hints.ai_flags = AI_PASSIVE;  
        hints.ai_family = AF_UNSPEC;  
        hints.ai_socktype = SOCK_DGRAM;  
        hints.ai_protocol = 0;  
        hints.ai_addrlen = 0;  
        hints.ai_addr = NULL;  
        hints.ai_canonname = NULL;  
        hints.ai_next = NULL;  
        ret = pg_getaddrinfo_all("localhost", NULL, &hints, &addrs);  
        if (ret || !addrs)  
        {  
                ereport(LOG,  
                                (errmsg("could not resolve \"localhost\": %s",  
                                                gai_strerror(ret))));  
                goto startup_failed;  
        }  

Flag Counter

digoal’s 大量PostgreSQL文章入口