]> granicus.if.org Git - postgresql/blob - src/backend/postmaster/pgstat.c
0355fa65fb899b6cb6823fae5d971042e1db033a
[postgresql] / src / backend / postmaster / pgstat.c
1 /* ----------
2  * pgstat.c
3  *
4  *      All the statistics collector stuff hacked up in one big, ugly file.
5  *
6  *      TODO:   - Separate collector, postmaster and backend stuff
7  *                        into different files.
8  *
9  *                      - Add some automatic call for pgstat vacuuming.
10  *
11  *                      - Add a pgstat config column to pg_database, so this
12  *                        entire thing can be enabled/disabled on a per db basis.
13  *
14  *      Copyright (c) 2001-2019, PostgreSQL Global Development Group
15  *
16  *      src/backend/postmaster/pgstat.c
17  * ----------
18  */
19 #include "postgres.h"
20
21 #include <unistd.h>
22 #include <fcntl.h>
23 #include <sys/param.h>
24 #include <sys/time.h>
25 #include <sys/socket.h>
26 #include <netdb.h>
27 #include <netinet/in.h>
28 #include <arpa/inet.h>
29 #include <signal.h>
30 #include <time.h>
31 #ifdef HAVE_SYS_SELECT_H
32 #include <sys/select.h>
33 #endif
34
35 #include "pgstat.h"
36
37 #include "access/heapam.h"
38 #include "access/htup_details.h"
39 #include "access/tableam.h"
40 #include "access/transam.h"
41 #include "access/twophase_rmgr.h"
42 #include "access/xact.h"
43 #include "catalog/pg_database.h"
44 #include "catalog/pg_proc.h"
45 #include "common/ip.h"
46 #include "libpq/libpq.h"
47 #include "libpq/pqsignal.h"
48 #include "mb/pg_wchar.h"
49 #include "miscadmin.h"
50 #include "pg_trace.h"
51 #include "postmaster/autovacuum.h"
52 #include "postmaster/fork_process.h"
53 #include "postmaster/postmaster.h"
54 #include "replication/walsender.h"
55 #include "storage/backendid.h"
56 #include "storage/dsm.h"
57 #include "storage/fd.h"
58 #include "storage/ipc.h"
59 #include "storage/latch.h"
60 #include "storage/lmgr.h"
61 #include "storage/pg_shmem.h"
62 #include "storage/procsignal.h"
63 #include "storage/sinvaladt.h"
64 #include "utils/ascii.h"
65 #include "utils/guc.h"
66 #include "utils/memutils.h"
67 #include "utils/ps_status.h"
68 #include "utils/rel.h"
69 #include "utils/snapmgr.h"
70 #include "utils/timestamp.h"
71
72
73 /* ----------
74  * Timer definitions.
75  * ----------
76  */
77 #define PGSTAT_STAT_INTERVAL    500 /* Minimum time between stats file
78                                                                          * updates; in milliseconds. */
79
80 #define PGSTAT_RETRY_DELAY              10      /* How long to wait between checks for a
81                                                                          * new file; in milliseconds. */
82
83 #define PGSTAT_MAX_WAIT_TIME    10000   /* Maximum time to wait for a stats
84                                                                                  * file update; in milliseconds. */
85
86 #define PGSTAT_INQ_INTERVAL             640 /* How often to ping the collector for a
87                                                                          * new file; in milliseconds. */
88
89 #define PGSTAT_RESTART_INTERVAL 60      /* How often to attempt to restart a
90                                                                          * failed statistics collector; in
91                                                                          * seconds. */
92
93 #define PGSTAT_POLL_LOOP_COUNT  (PGSTAT_MAX_WAIT_TIME / PGSTAT_RETRY_DELAY)
94 #define PGSTAT_INQ_LOOP_COUNT   (PGSTAT_INQ_INTERVAL / PGSTAT_RETRY_DELAY)
95
96 /* Minimum receive buffer size for the collector's socket. */
97 #define PGSTAT_MIN_RCVBUF               (100 * 1024)
98
99
100 /* ----------
101  * The initial size hints for the hash tables used in the collector.
102  * ----------
103  */
104 #define PGSTAT_DB_HASH_SIZE             16
105 #define PGSTAT_TAB_HASH_SIZE    512
106 #define PGSTAT_FUNCTION_HASH_SIZE       512
107
108
109 /* ----------
110  * Total number of backends including auxiliary
111  *
112  * We reserve a slot for each possible BackendId, plus one for each
113  * possible auxiliary process type.  (This scheme assumes there is not
114  * more than one of any auxiliary process type at a time.) MaxBackends
115  * includes autovacuum workers and background workers as well.
116  * ----------
117  */
118 #define NumBackendStatSlots (MaxBackends + NUM_AUXPROCTYPES)
119
120
121 /* ----------
122  * GUC parameters
123  * ----------
124  */
125 bool            pgstat_track_activities = false;
126 bool            pgstat_track_counts = false;
127 int                     pgstat_track_functions = TRACK_FUNC_OFF;
128 int                     pgstat_track_activity_query_size = 1024;
129
130 /* ----------
131  * Built from GUC parameter
132  * ----------
133  */
134 char       *pgstat_stat_directory = NULL;
135 char       *pgstat_stat_filename = NULL;
136 char       *pgstat_stat_tmpname = NULL;
137
138 /*
139  * BgWriter global statistics counters (unused in other processes).
140  * Stored directly in a stats message structure so it can be sent
141  * without needing to copy things around.  We assume this inits to zeroes.
142  */
143 PgStat_MsgBgWriter BgWriterStats;
144
145 /* ----------
146  * Local data
147  * ----------
148  */
149 NON_EXEC_STATIC pgsocket pgStatSock = PGINVALID_SOCKET;
150
151 static struct sockaddr_storage pgStatAddr;
152
153 static time_t last_pgstat_start_time;
154
155 static bool pgStatRunningInCollector = false;
156
157 /*
158  * Structures in which backends store per-table info that's waiting to be
159  * sent to the collector.
160  *
161  * NOTE: once allocated, TabStatusArray structures are never moved or deleted
162  * for the life of the backend.  Also, we zero out the t_id fields of the
163  * contained PgStat_TableStatus structs whenever they are not actively in use.
164  * This allows relcache pgstat_info pointers to be treated as long-lived data,
165  * avoiding repeated searches in pgstat_initstats() when a relation is
166  * repeatedly opened during a transaction.
167  */
168 #define TABSTAT_QUANTUM         100 /* we alloc this many at a time */
169
170 typedef struct TabStatusArray
171 {
172         struct TabStatusArray *tsa_next;        /* link to next array, if any */
173         int                     tsa_used;               /* # entries currently used */
174         PgStat_TableStatus tsa_entries[TABSTAT_QUANTUM];        /* per-table data */
175 } TabStatusArray;
176
177 static TabStatusArray *pgStatTabList = NULL;
178
179 /*
180  * pgStatTabHash entry: map from relation OID to PgStat_TableStatus pointer
181  */
182 typedef struct TabStatHashEntry
183 {
184         Oid                     t_id;
185         PgStat_TableStatus *tsa_entry;
186 } TabStatHashEntry;
187
188 /*
189  * Hash table for O(1) t_id -> tsa_entry lookup
190  */
191 static HTAB *pgStatTabHash = NULL;
192
193 /*
194  * Backends store per-function info that's waiting to be sent to the collector
195  * in this hash table (indexed by function OID).
196  */
197 static HTAB *pgStatFunctions = NULL;
198
199 /*
200  * Indicates if backend has some function stats that it hasn't yet
201  * sent to the collector.
202  */
203 static bool have_function_stats = false;
204
205 /*
206  * Tuple insertion/deletion counts for an open transaction can't be propagated
207  * into PgStat_TableStatus counters until we know if it is going to commit
208  * or abort.  Hence, we keep these counts in per-subxact structs that live
209  * in TopTransactionContext.  This data structure is designed on the assumption
210  * that subxacts won't usually modify very many tables.
211  */
212 typedef struct PgStat_SubXactStatus
213 {
214         int                     nest_level;             /* subtransaction nest level */
215         struct PgStat_SubXactStatus *prev;      /* higher-level subxact if any */
216         PgStat_TableXactStatus *first;  /* head of list for this subxact */
217 } PgStat_SubXactStatus;
218
219 static PgStat_SubXactStatus *pgStatXactStack = NULL;
220
221 static int      pgStatXactCommit = 0;
222 static int      pgStatXactRollback = 0;
223 PgStat_Counter pgStatBlockReadTime = 0;
224 PgStat_Counter pgStatBlockWriteTime = 0;
225
226 /* Record that's written to 2PC state file when pgstat state is persisted */
227 typedef struct TwoPhasePgStatRecord
228 {
229         PgStat_Counter tuples_inserted; /* tuples inserted in xact */
230         PgStat_Counter tuples_updated;  /* tuples updated in xact */
231         PgStat_Counter tuples_deleted;  /* tuples deleted in xact */
232         PgStat_Counter inserted_pre_trunc;      /* tuples inserted prior to truncate */
233         PgStat_Counter updated_pre_trunc;       /* tuples updated prior to truncate */
234         PgStat_Counter deleted_pre_trunc;       /* tuples deleted prior to truncate */
235         Oid                     t_id;                   /* table's OID */
236         bool            t_shared;               /* is it a shared catalog? */
237         bool            t_truncated;    /* was the relation truncated? */
238 } TwoPhasePgStatRecord;
239
240 /*
241  * Info about current "snapshot" of stats file
242  */
243 static MemoryContext pgStatLocalContext = NULL;
244 static HTAB *pgStatDBHash = NULL;
245
246 /* Status for backends including auxiliary */
247 static LocalPgBackendStatus *localBackendStatusTable = NULL;
248
249 /* Total number of backends including auxiliary */
250 static int      localNumBackends = 0;
251
252 /*
253  * Cluster wide statistics, kept in the stats collector.
254  * Contains statistics that are not collected per database
255  * or per table.
256  */
257 static PgStat_ArchiverStats archiverStats;
258 static PgStat_GlobalStats globalStats;
259
260 /*
261  * List of OIDs of databases we need to write out.  If an entry is InvalidOid,
262  * it means to write only the shared-catalog stats ("DB 0"); otherwise, we
263  * will write both that DB's data and the shared stats.
264  */
265 static List *pending_write_requests = NIL;
266
267 /* Signal handler flags */
268 static volatile bool need_exit = false;
269 static volatile bool got_SIGHUP = false;
270
271 /*
272  * Total time charged to functions so far in the current backend.
273  * We use this to help separate "self" and "other" time charges.
274  * (We assume this initializes to zero.)
275  */
276 static instr_time total_func_time;
277
278
279 /* ----------
280  * Local function forward declarations
281  * ----------
282  */
283 #ifdef EXEC_BACKEND
284 static pid_t pgstat_forkexec(void);
285 #endif
286
287 NON_EXEC_STATIC void PgstatCollectorMain(int argc, char *argv[]) pg_attribute_noreturn();
288 static void pgstat_exit(SIGNAL_ARGS);
289 static void pgstat_beshutdown_hook(int code, Datum arg);
290 static void pgstat_sighup_handler(SIGNAL_ARGS);
291
292 static PgStat_StatDBEntry *pgstat_get_db_entry(Oid databaseid, bool create);
293 static PgStat_StatTabEntry *pgstat_get_tab_entry(PgStat_StatDBEntry *dbentry,
294                                          Oid tableoid, bool create);
295 static void pgstat_write_statsfiles(bool permanent, bool allDbs);
296 static void pgstat_write_db_statsfile(PgStat_StatDBEntry *dbentry, bool permanent);
297 static HTAB *pgstat_read_statsfiles(Oid onlydb, bool permanent, bool deep);
298 static void pgstat_read_db_statsfile(Oid databaseid, HTAB *tabhash, HTAB *funchash, bool permanent);
299 static void backend_read_statsfile(void);
300 static void pgstat_read_current_status(void);
301
302 static bool pgstat_write_statsfile_needed(void);
303 static bool pgstat_db_requested(Oid databaseid);
304
305 static void pgstat_send_tabstat(PgStat_MsgTabstat *tsmsg);
306 static void pgstat_send_funcstats(void);
307 static HTAB *pgstat_collect_oids(Oid catalogid, AttrNumber anum_oid);
308
309 static PgStat_TableStatus *get_tabstat_entry(Oid rel_id, bool isshared);
310
311 static void pgstat_setup_memcxt(void);
312
313 static const char *pgstat_get_wait_activity(WaitEventActivity w);
314 static const char *pgstat_get_wait_client(WaitEventClient w);
315 static const char *pgstat_get_wait_ipc(WaitEventIPC w);
316 static const char *pgstat_get_wait_timeout(WaitEventTimeout w);
317 static const char *pgstat_get_wait_io(WaitEventIO w);
318
319 static void pgstat_setheader(PgStat_MsgHdr *hdr, StatMsgType mtype);
320 static void pgstat_send(void *msg, int len);
321
322 static void pgstat_recv_inquiry(PgStat_MsgInquiry *msg, int len);
323 static void pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len);
324 static void pgstat_recv_tabpurge(PgStat_MsgTabpurge *msg, int len);
325 static void pgstat_recv_dropdb(PgStat_MsgDropdb *msg, int len);
326 static void pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len);
327 static void pgstat_recv_resetsharedcounter(PgStat_MsgResetsharedcounter *msg, int len);
328 static void pgstat_recv_resetsinglecounter(PgStat_MsgResetsinglecounter *msg, int len);
329 static void pgstat_recv_autovac(PgStat_MsgAutovacStart *msg, int len);
330 static void pgstat_recv_vacuum(PgStat_MsgVacuum *msg, int len);
331 static void pgstat_recv_analyze(PgStat_MsgAnalyze *msg, int len);
332 static void pgstat_recv_archiver(PgStat_MsgArchiver *msg, int len);
333 static void pgstat_recv_bgwriter(PgStat_MsgBgWriter *msg, int len);
334 static void pgstat_recv_funcstat(PgStat_MsgFuncstat *msg, int len);
335 static void pgstat_recv_funcpurge(PgStat_MsgFuncpurge *msg, int len);
336 static void pgstat_recv_recoveryconflict(PgStat_MsgRecoveryConflict *msg, int len);
337 static void pgstat_recv_deadlock(PgStat_MsgDeadlock *msg, int len);
338 static void pgstat_recv_checksum_failure(PgStat_MsgChecksumFailure *msg, int len);
339 static void pgstat_recv_tempfile(PgStat_MsgTempFile *msg, int len);
340
341 /* ------------------------------------------------------------
342  * Public functions called from postmaster follow
343  * ------------------------------------------------------------
344  */
345
346 /* ----------
347  * pgstat_init() -
348  *
349  *      Called from postmaster at startup. Create the resources required
350  *      by the statistics collector process.  If unable to do so, do not
351  *      fail --- better to let the postmaster start with stats collection
352  *      disabled.
353  * ----------
354  */
355 void
356 pgstat_init(void)
357 {
358         ACCEPT_TYPE_ARG3 alen;
359         struct addrinfo *addrs = NULL,
360                            *addr,
361                                 hints;
362         int                     ret;
363         fd_set          rset;
364         struct timeval tv;
365         char            test_byte;
366         int                     sel_res;
367         int                     tries = 0;
368
369 #define TESTBYTEVAL ((char) 199)
370
371         /*
372          * This static assertion verifies that we didn't mess up the calculations
373          * involved in selecting maximum payload sizes for our UDP messages.
374          * Because the only consequence of overrunning PGSTAT_MAX_MSG_SIZE would
375          * be silent performance loss from fragmentation, it seems worth having a
376          * compile-time cross-check that we didn't.
377          */
378         StaticAssertStmt(sizeof(PgStat_Msg) <= PGSTAT_MAX_MSG_SIZE,
379                                          "maximum stats message size exceeds PGSTAT_MAX_MSG_SIZE");
380
381         /*
382          * Create the UDP socket for sending and receiving statistic messages
383          */
384         hints.ai_flags = AI_PASSIVE;
385         hints.ai_family = AF_UNSPEC;
386         hints.ai_socktype = SOCK_DGRAM;
387         hints.ai_protocol = 0;
388         hints.ai_addrlen = 0;
389         hints.ai_addr = NULL;
390         hints.ai_canonname = NULL;
391         hints.ai_next = NULL;
392         ret = pg_getaddrinfo_all("localhost", NULL, &hints, &addrs);
393         if (ret || !addrs)
394         {
395                 ereport(LOG,
396                                 (errmsg("could not resolve \"localhost\": %s",
397                                                 gai_strerror(ret))));
398                 goto startup_failed;
399         }
400
401         /*
402          * On some platforms, pg_getaddrinfo_all() may return multiple addresses
403          * only one of which will actually work (eg, both IPv6 and IPv4 addresses
404          * when kernel will reject IPv6).  Worse, the failure may occur at the
405          * bind() or perhaps even connect() stage.  So we must loop through the
406          * results till we find a working combination. We will generate LOG
407          * messages, but no error, for bogus combinations.
408          */
409         for (addr = addrs; addr; addr = addr->ai_next)
410         {
411 #ifdef HAVE_UNIX_SOCKETS
412                 /* Ignore AF_UNIX sockets, if any are returned. */
413                 if (addr->ai_family == AF_UNIX)
414                         continue;
415 #endif
416
417                 if (++tries > 1)
418                         ereport(LOG,
419                                         (errmsg("trying another address for the statistics collector")));
420
421                 /*
422                  * Create the socket.
423                  */
424                 if ((pgStatSock = socket(addr->ai_family, SOCK_DGRAM, 0)) == PGINVALID_SOCKET)
425                 {
426                         ereport(LOG,
427                                         (errcode_for_socket_access(),
428                                          errmsg("could not create socket for statistics collector: %m")));
429                         continue;
430                 }
431
432                 /*
433                  * Bind it to a kernel assigned port on localhost and get the assigned
434                  * port via getsockname().
435                  */
436                 if (bind(pgStatSock, addr->ai_addr, addr->ai_addrlen) < 0)
437                 {
438                         ereport(LOG,
439                                         (errcode_for_socket_access(),
440                                          errmsg("could not bind socket for statistics collector: %m")));
441                         closesocket(pgStatSock);
442                         pgStatSock = PGINVALID_SOCKET;
443                         continue;
444                 }
445
446                 alen = sizeof(pgStatAddr);
447                 if (getsockname(pgStatSock, (struct sockaddr *) &pgStatAddr, &alen) < 0)
448                 {
449                         ereport(LOG,
450                                         (errcode_for_socket_access(),
451                                          errmsg("could not get address of socket for statistics collector: %m")));
452                         closesocket(pgStatSock);
453                         pgStatSock = PGINVALID_SOCKET;
454                         continue;
455                 }
456
457                 /*
458                  * Connect the socket to its own address.  This saves a few cycles by
459                  * not having to respecify the target address on every send. This also
460                  * provides a kernel-level check that only packets from this same
461                  * address will be received.
462                  */
463                 if (connect(pgStatSock, (struct sockaddr *) &pgStatAddr, alen) < 0)
464                 {
465                         ereport(LOG,
466                                         (errcode_for_socket_access(),
467                                          errmsg("could not connect socket for statistics collector: %m")));
468                         closesocket(pgStatSock);
469                         pgStatSock = PGINVALID_SOCKET;
470                         continue;
471                 }
472
473                 /*
474                  * Try to send and receive a one-byte test message on the socket. This
475                  * is to catch situations where the socket can be created but will not
476                  * actually pass data (for instance, because kernel packet filtering
477                  * rules prevent it).
478                  */
479                 test_byte = TESTBYTEVAL;
480
481 retry1:
482                 if (send(pgStatSock, &test_byte, 1, 0) != 1)
483                 {
484                         if (errno == EINTR)
485                                 goto retry1;    /* if interrupted, just retry */
486                         ereport(LOG,
487                                         (errcode_for_socket_access(),
488                                          errmsg("could not send test message on socket for statistics collector: %m")));
489                         closesocket(pgStatSock);
490                         pgStatSock = PGINVALID_SOCKET;
491                         continue;
492                 }
493
494                 /*
495                  * There could possibly be a little delay before the message can be
496                  * received.  We arbitrarily allow up to half a second before deciding
497                  * it's broken.
498                  */
499                 for (;;)                                /* need a loop to handle EINTR */
500                 {
501                         FD_ZERO(&rset);
502                         FD_SET(pgStatSock, &rset);
503
504                         tv.tv_sec = 0;
505                         tv.tv_usec = 500000;
506                         sel_res = select(pgStatSock + 1, &rset, NULL, NULL, &tv);
507                         if (sel_res >= 0 || errno != EINTR)
508                                 break;
509                 }
510                 if (sel_res < 0)
511                 {
512                         ereport(LOG,
513                                         (errcode_for_socket_access(),
514                                          errmsg("select() failed in statistics collector: %m")));
515                         closesocket(pgStatSock);
516                         pgStatSock = PGINVALID_SOCKET;
517                         continue;
518                 }
519                 if (sel_res == 0 || !FD_ISSET(pgStatSock, &rset))
520                 {
521                         /*
522                          * This is the case we actually think is likely, so take pains to
523                          * give a specific message for it.
524                          *
525                          * errno will not be set meaningfully here, so don't use it.
526                          */
527                         ereport(LOG,
528                                         (errcode(ERRCODE_CONNECTION_FAILURE),
529                                          errmsg("test message did not get through on socket for statistics collector")));
530                         closesocket(pgStatSock);
531                         pgStatSock = PGINVALID_SOCKET;
532                         continue;
533                 }
534
535                 test_byte++;                    /* just make sure variable is changed */
536
537 retry2:
538                 if (recv(pgStatSock, &test_byte, 1, 0) != 1)
539                 {
540                         if (errno == EINTR)
541                                 goto retry2;    /* if interrupted, just retry */
542                         ereport(LOG,
543                                         (errcode_for_socket_access(),
544                                          errmsg("could not receive test message on socket for statistics collector: %m")));
545                         closesocket(pgStatSock);
546                         pgStatSock = PGINVALID_SOCKET;
547                         continue;
548                 }
549
550                 if (test_byte != TESTBYTEVAL)   /* strictly paranoia ... */
551                 {
552                         ereport(LOG,
553                                         (errcode(ERRCODE_INTERNAL_ERROR),
554                                          errmsg("incorrect test message transmission on socket for statistics collector")));
555                         closesocket(pgStatSock);
556                         pgStatSock = PGINVALID_SOCKET;
557                         continue;
558                 }
559
560                 /* If we get here, we have a working socket */
561                 break;
562         }
563
564         /* Did we find a working address? */
565         if (!addr || pgStatSock == PGINVALID_SOCKET)
566                 goto startup_failed;
567
568         /*
569          * Set the socket to non-blocking IO.  This ensures that if the collector
570          * falls behind, statistics messages will be discarded; backends won't
571          * block waiting to send messages to the collector.
572          */
573         if (!pg_set_noblock(pgStatSock))
574         {
575                 ereport(LOG,
576                                 (errcode_for_socket_access(),
577                                  errmsg("could not set statistics collector socket to nonblocking mode: %m")));
578                 goto startup_failed;
579         }
580
581         /*
582          * Try to ensure that the socket's receive buffer is at least
583          * PGSTAT_MIN_RCVBUF bytes, so that it won't easily overflow and lose
584          * data.  Use of UDP protocol means that we are willing to lose data under
585          * heavy load, but we don't want it to happen just because of ridiculously
586          * small default buffer sizes (such as 8KB on older Windows versions).
587          */
588         {
589                 int                     old_rcvbuf;
590                 int                     new_rcvbuf;
591                 ACCEPT_TYPE_ARG3 rcvbufsize = sizeof(old_rcvbuf);
592
593                 if (getsockopt(pgStatSock, SOL_SOCKET, SO_RCVBUF,
594                                            (char *) &old_rcvbuf, &rcvbufsize) < 0)
595                 {
596                         elog(LOG, "getsockopt(SO_RCVBUF) failed: %m");
597                         /* if we can't get existing size, always try to set it */
598                         old_rcvbuf = 0;
599                 }
600
601                 new_rcvbuf = PGSTAT_MIN_RCVBUF;
602                 if (old_rcvbuf < new_rcvbuf)
603                 {
604                         if (setsockopt(pgStatSock, SOL_SOCKET, SO_RCVBUF,
605                                                    (char *) &new_rcvbuf, sizeof(new_rcvbuf)) < 0)
606                                 elog(LOG, "setsockopt(SO_RCVBUF) failed: %m");
607                 }
608         }
609
610         pg_freeaddrinfo_all(hints.ai_family, addrs);
611
612         return;
613
614 startup_failed:
615         ereport(LOG,
616                         (errmsg("disabling statistics collector for lack of working socket")));
617
618         if (addrs)
619                 pg_freeaddrinfo_all(hints.ai_family, addrs);
620
621         if (pgStatSock != PGINVALID_SOCKET)
622                 closesocket(pgStatSock);
623         pgStatSock = PGINVALID_SOCKET;
624
625         /*
626          * Adjust GUC variables to suppress useless activity, and for debugging
627          * purposes (seeing track_counts off is a clue that we failed here). We
628          * use PGC_S_OVERRIDE because there is no point in trying to turn it back
629          * on from postgresql.conf without a restart.
630          */
631         SetConfigOption("track_counts", "off", PGC_INTERNAL, PGC_S_OVERRIDE);
632 }
633
634 /*
635  * subroutine for pgstat_reset_all
636  */
637 static void
638 pgstat_reset_remove_files(const char *directory)
639 {
640         DIR                *dir;
641         struct dirent *entry;
642         char            fname[MAXPGPATH * 2];
643
644         dir = AllocateDir(directory);
645         while ((entry = ReadDir(dir, directory)) != NULL)
646         {
647                 int                     nchars;
648                 Oid                     tmp_oid;
649
650                 /*
651                  * Skip directory entries that don't match the file names we write.
652                  * See get_dbstat_filename for the database-specific pattern.
653                  */
654                 if (strncmp(entry->d_name, "global.", 7) == 0)
655                         nchars = 7;
656                 else
657                 {
658                         nchars = 0;
659                         (void) sscanf(entry->d_name, "db_%u.%n",
660                                                   &tmp_oid, &nchars);
661                         if (nchars <= 0)
662                                 continue;
663                         /* %u allows leading whitespace, so reject that */
664                         if (strchr("0123456789", entry->d_name[3]) == NULL)
665                                 continue;
666                 }
667
668                 if (strcmp(entry->d_name + nchars, "tmp") != 0 &&
669                         strcmp(entry->d_name + nchars, "stat") != 0)
670                         continue;
671
672                 snprintf(fname, sizeof(fname), "%s/%s", directory,
673                                  entry->d_name);
674                 unlink(fname);
675         }
676         FreeDir(dir);
677 }
678
679 /*
680  * pgstat_reset_all() -
681  *
682  * Remove the stats files.  This is currently used only if WAL
683  * recovery is needed after a crash.
684  */
685 void
686 pgstat_reset_all(void)
687 {
688         pgstat_reset_remove_files(pgstat_stat_directory);
689         pgstat_reset_remove_files(PGSTAT_STAT_PERMANENT_DIRECTORY);
690 }
691
692 #ifdef EXEC_BACKEND
693
694 /*
695  * pgstat_forkexec() -
696  *
697  * Format up the arglist for, then fork and exec, statistics collector process
698  */
699 static pid_t
700 pgstat_forkexec(void)
701 {
702         char       *av[10];
703         int                     ac = 0;
704
705         av[ac++] = "postgres";
706         av[ac++] = "--forkcol";
707         av[ac++] = NULL;                        /* filled in by postmaster_forkexec */
708
709         av[ac] = NULL;
710         Assert(ac < lengthof(av));
711
712         return postmaster_forkexec(ac, av);
713 }
714 #endif                                                  /* EXEC_BACKEND */
715
716
717 /*
718  * pgstat_start() -
719  *
720  *      Called from postmaster at startup or after an existing collector
721  *      died.  Attempt to fire up a fresh statistics collector.
722  *
723  *      Returns PID of child process, or 0 if fail.
724  *
725  *      Note: if fail, we will be called again from the postmaster main loop.
726  */
727 int
728 pgstat_start(void)
729 {
730         time_t          curtime;
731         pid_t           pgStatPid;
732
733         /*
734          * Check that the socket is there, else pgstat_init failed and we can do
735          * nothing useful.
736          */
737         if (pgStatSock == PGINVALID_SOCKET)
738                 return 0;
739
740         /*
741          * Do nothing if too soon since last collector start.  This is a safety
742          * valve to protect against continuous respawn attempts if the collector
743          * is dying immediately at launch.  Note that since we will be re-called
744          * from the postmaster main loop, we will get another chance later.
745          */
746         curtime = time(NULL);
747         if ((unsigned int) (curtime - last_pgstat_start_time) <
748                 (unsigned int) PGSTAT_RESTART_INTERVAL)
749                 return 0;
750         last_pgstat_start_time = curtime;
751
752         /*
753          * Okay, fork off the collector.
754          */
755 #ifdef EXEC_BACKEND
756         switch ((pgStatPid = pgstat_forkexec()))
757 #else
758         switch ((pgStatPid = fork_process()))
759 #endif
760         {
761                 case -1:
762                         ereport(LOG,
763                                         (errmsg("could not fork statistics collector: %m")));
764                         return 0;
765
766 #ifndef EXEC_BACKEND
767                 case 0:
768                         /* in postmaster child ... */
769                         InitPostmasterChild();
770
771                         /* Close the postmaster's sockets */
772                         ClosePostmasterPorts(false);
773
774                         /* Drop our connection to postmaster's shared memory, as well */
775                         dsm_detach_all();
776                         PGSharedMemoryDetach();
777
778                         PgstatCollectorMain(0, NULL);
779                         break;
780 #endif
781
782                 default:
783                         return (int) pgStatPid;
784         }
785
786         /* shouldn't get here */
787         return 0;
788 }
789
790 void
791 allow_immediate_pgstat_restart(void)
792 {
793         last_pgstat_start_time = 0;
794 }
795
796 /* ------------------------------------------------------------
797  * Public functions used by backends follow
798  *------------------------------------------------------------
799  */
800
801
802 /* ----------
803  * pgstat_report_stat() -
804  *
805  *      Must be called by processes that performs DML: tcop/postgres.c, logical
806  *      receiver processes, SPI worker, etc. to send the so far collected
807  *      per-table and function usage statistics to the collector.  Note that this
808  *      is called only when not within a transaction, so it is fair to use
809  *      transaction stop time as an approximation of current time.
810  * ----------
811  */
812 void
813 pgstat_report_stat(bool force)
814 {
815         /* we assume this inits to all zeroes: */
816         static const PgStat_TableCounts all_zeroes;
817         static TimestampTz last_report = 0;
818
819         TimestampTz now;
820         PgStat_MsgTabstat regular_msg;
821         PgStat_MsgTabstat shared_msg;
822         TabStatusArray *tsa;
823         int                     i;
824
825         /* Don't expend a clock check if nothing to do */
826         if ((pgStatTabList == NULL || pgStatTabList->tsa_used == 0) &&
827                 pgStatXactCommit == 0 && pgStatXactRollback == 0 &&
828                 !have_function_stats)
829                 return;
830
831         /*
832          * Don't send a message unless it's been at least PGSTAT_STAT_INTERVAL
833          * msec since we last sent one, or the caller wants to force stats out.
834          */
835         now = GetCurrentTransactionStopTimestamp();
836         if (!force &&
837                 !TimestampDifferenceExceeds(last_report, now, PGSTAT_STAT_INTERVAL))
838                 return;
839         last_report = now;
840
841         /*
842          * Destroy pgStatTabHash before we start invalidating PgStat_TableEntry
843          * entries it points to.  (Should we fail partway through the loop below,
844          * it's okay to have removed the hashtable already --- the only
845          * consequence is we'd get multiple entries for the same table in the
846          * pgStatTabList, and that's safe.)
847          */
848         if (pgStatTabHash)
849                 hash_destroy(pgStatTabHash);
850         pgStatTabHash = NULL;
851
852         /*
853          * Scan through the TabStatusArray struct(s) to find tables that actually
854          * have counts, and build messages to send.  We have to separate shared
855          * relations from regular ones because the databaseid field in the message
856          * header has to depend on that.
857          */
858         regular_msg.m_databaseid = MyDatabaseId;
859         shared_msg.m_databaseid = InvalidOid;
860         regular_msg.m_nentries = 0;
861         shared_msg.m_nentries = 0;
862
863         for (tsa = pgStatTabList; tsa != NULL; tsa = tsa->tsa_next)
864         {
865                 for (i = 0; i < tsa->tsa_used; i++)
866                 {
867                         PgStat_TableStatus *entry = &tsa->tsa_entries[i];
868                         PgStat_MsgTabstat *this_msg;
869                         PgStat_TableEntry *this_ent;
870
871                         /* Shouldn't have any pending transaction-dependent counts */
872                         Assert(entry->trans == NULL);
873
874                         /*
875                          * Ignore entries that didn't accumulate any actual counts, such
876                          * as indexes that were opened by the planner but not used.
877                          */
878                         if (memcmp(&entry->t_counts, &all_zeroes,
879                                            sizeof(PgStat_TableCounts)) == 0)
880                                 continue;
881
882                         /*
883                          * OK, insert data into the appropriate message, and send if full.
884                          */
885                         this_msg = entry->t_shared ? &shared_msg : &regular_msg;
886                         this_ent = &this_msg->m_entry[this_msg->m_nentries];
887                         this_ent->t_id = entry->t_id;
888                         memcpy(&this_ent->t_counts, &entry->t_counts,
889                                    sizeof(PgStat_TableCounts));
890                         if (++this_msg->m_nentries >= PGSTAT_NUM_TABENTRIES)
891                         {
892                                 pgstat_send_tabstat(this_msg);
893                                 this_msg->m_nentries = 0;
894                         }
895                 }
896                 /* zero out TableStatus structs after use */
897                 MemSet(tsa->tsa_entries, 0,
898                            tsa->tsa_used * sizeof(PgStat_TableStatus));
899                 tsa->tsa_used = 0;
900         }
901
902         /*
903          * Send partial messages.  Make sure that any pending xact commit/abort
904          * gets counted, even if there are no table stats to send.
905          */
906         if (regular_msg.m_nentries > 0 ||
907                 pgStatXactCommit > 0 || pgStatXactRollback > 0)
908                 pgstat_send_tabstat(&regular_msg);
909         if (shared_msg.m_nentries > 0)
910                 pgstat_send_tabstat(&shared_msg);
911
912         /* Now, send function statistics */
913         pgstat_send_funcstats();
914 }
915
916 /*
917  * Subroutine for pgstat_report_stat: finish and send a tabstat message
918  */
919 static void
920 pgstat_send_tabstat(PgStat_MsgTabstat *tsmsg)
921 {
922         int                     n;
923         int                     len;
924
925         /* It's unlikely we'd get here with no socket, but maybe not impossible */
926         if (pgStatSock == PGINVALID_SOCKET)
927                 return;
928
929         /*
930          * Report and reset accumulated xact commit/rollback and I/O timings
931          * whenever we send a normal tabstat message
932          */
933         if (OidIsValid(tsmsg->m_databaseid))
934         {
935                 tsmsg->m_xact_commit = pgStatXactCommit;
936                 tsmsg->m_xact_rollback = pgStatXactRollback;
937                 tsmsg->m_block_read_time = pgStatBlockReadTime;
938                 tsmsg->m_block_write_time = pgStatBlockWriteTime;
939                 pgStatXactCommit = 0;
940                 pgStatXactRollback = 0;
941                 pgStatBlockReadTime = 0;
942                 pgStatBlockWriteTime = 0;
943         }
944         else
945         {
946                 tsmsg->m_xact_commit = 0;
947                 tsmsg->m_xact_rollback = 0;
948                 tsmsg->m_block_read_time = 0;
949                 tsmsg->m_block_write_time = 0;
950         }
951
952         n = tsmsg->m_nentries;
953         len = offsetof(PgStat_MsgTabstat, m_entry[0]) +
954                 n * sizeof(PgStat_TableEntry);
955
956         pgstat_setheader(&tsmsg->m_hdr, PGSTAT_MTYPE_TABSTAT);
957         pgstat_send(tsmsg, len);
958 }
959
960 /*
961  * Subroutine for pgstat_report_stat: populate and send a function stat message
962  */
963 static void
964 pgstat_send_funcstats(void)
965 {
966         /* we assume this inits to all zeroes: */
967         static const PgStat_FunctionCounts all_zeroes;
968
969         PgStat_MsgFuncstat msg;
970         PgStat_BackendFunctionEntry *entry;
971         HASH_SEQ_STATUS fstat;
972
973         if (pgStatFunctions == NULL)
974                 return;
975
976         pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_FUNCSTAT);
977         msg.m_databaseid = MyDatabaseId;
978         msg.m_nentries = 0;
979
980         hash_seq_init(&fstat, pgStatFunctions);
981         while ((entry = (PgStat_BackendFunctionEntry *) hash_seq_search(&fstat)) != NULL)
982         {
983                 PgStat_FunctionEntry *m_ent;
984
985                 /* Skip it if no counts accumulated since last time */
986                 if (memcmp(&entry->f_counts, &all_zeroes,
987                                    sizeof(PgStat_FunctionCounts)) == 0)
988                         continue;
989
990                 /* need to convert format of time accumulators */
991                 m_ent = &msg.m_entry[msg.m_nentries];
992                 m_ent->f_id = entry->f_id;
993                 m_ent->f_numcalls = entry->f_counts.f_numcalls;
994                 m_ent->f_total_time = INSTR_TIME_GET_MICROSEC(entry->f_counts.f_total_time);
995                 m_ent->f_self_time = INSTR_TIME_GET_MICROSEC(entry->f_counts.f_self_time);
996
997                 if (++msg.m_nentries >= PGSTAT_NUM_FUNCENTRIES)
998                 {
999                         pgstat_send(&msg, offsetof(PgStat_MsgFuncstat, m_entry[0]) +
1000                                                 msg.m_nentries * sizeof(PgStat_FunctionEntry));
1001                         msg.m_nentries = 0;
1002                 }
1003
1004                 /* reset the entry's counts */
1005                 MemSet(&entry->f_counts, 0, sizeof(PgStat_FunctionCounts));
1006         }
1007
1008         if (msg.m_nentries > 0)
1009                 pgstat_send(&msg, offsetof(PgStat_MsgFuncstat, m_entry[0]) +
1010                                         msg.m_nentries * sizeof(PgStat_FunctionEntry));
1011
1012         have_function_stats = false;
1013 }
1014
1015
1016 /* ----------
1017  * pgstat_vacuum_stat() -
1018  *
1019  *      Will tell the collector about objects he can get rid of.
1020  * ----------
1021  */
1022 void
1023 pgstat_vacuum_stat(void)
1024 {
1025         HTAB       *htab;
1026         PgStat_MsgTabpurge msg;
1027         PgStat_MsgFuncpurge f_msg;
1028         HASH_SEQ_STATUS hstat;
1029         PgStat_StatDBEntry *dbentry;
1030         PgStat_StatTabEntry *tabentry;
1031         PgStat_StatFuncEntry *funcentry;
1032         int                     len;
1033
1034         if (pgStatSock == PGINVALID_SOCKET)
1035                 return;
1036
1037         /*
1038          * If not done for this transaction, read the statistics collector stats
1039          * file into some hash tables.
1040          */
1041         backend_read_statsfile();
1042
1043         /*
1044          * Read pg_database and make a list of OIDs of all existing databases
1045          */
1046         htab = pgstat_collect_oids(DatabaseRelationId, Anum_pg_database_oid);
1047
1048         /*
1049          * Search the database hash table for dead databases and tell the
1050          * collector to drop them.
1051          */
1052         hash_seq_init(&hstat, pgStatDBHash);
1053         while ((dbentry = (PgStat_StatDBEntry *) hash_seq_search(&hstat)) != NULL)
1054         {
1055                 Oid                     dbid = dbentry->databaseid;
1056
1057                 CHECK_FOR_INTERRUPTS();
1058
1059                 /* the DB entry for shared tables (with InvalidOid) is never dropped */
1060                 if (OidIsValid(dbid) &&
1061                         hash_search(htab, (void *) &dbid, HASH_FIND, NULL) == NULL)
1062                         pgstat_drop_database(dbid);
1063         }
1064
1065         /* Clean up */
1066         hash_destroy(htab);
1067
1068         /*
1069          * Lookup our own database entry; if not found, nothing more to do.
1070          */
1071         dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
1072                                                                                                  (void *) &MyDatabaseId,
1073                                                                                                  HASH_FIND, NULL);
1074         if (dbentry == NULL || dbentry->tables == NULL)
1075                 return;
1076
1077         /*
1078          * Similarly to above, make a list of all known relations in this DB.
1079          */
1080         htab = pgstat_collect_oids(RelationRelationId, Anum_pg_class_oid);
1081
1082         /*
1083          * Initialize our messages table counter to zero
1084          */
1085         msg.m_nentries = 0;
1086
1087         /*
1088          * Check for all tables listed in stats hashtable if they still exist.
1089          */
1090         hash_seq_init(&hstat, dbentry->tables);
1091         while ((tabentry = (PgStat_StatTabEntry *) hash_seq_search(&hstat)) != NULL)
1092         {
1093                 Oid                     tabid = tabentry->tableid;
1094
1095                 CHECK_FOR_INTERRUPTS();
1096
1097                 if (hash_search(htab, (void *) &tabid, HASH_FIND, NULL) != NULL)
1098                         continue;
1099
1100                 /*
1101                  * Not there, so add this table's Oid to the message
1102                  */
1103                 msg.m_tableid[msg.m_nentries++] = tabid;
1104
1105                 /*
1106                  * If the message is full, send it out and reinitialize to empty
1107                  */
1108                 if (msg.m_nentries >= PGSTAT_NUM_TABPURGE)
1109                 {
1110                         len = offsetof(PgStat_MsgTabpurge, m_tableid[0])
1111                                 + msg.m_nentries * sizeof(Oid);
1112
1113                         pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
1114                         msg.m_databaseid = MyDatabaseId;
1115                         pgstat_send(&msg, len);
1116
1117                         msg.m_nentries = 0;
1118                 }
1119         }
1120
1121         /*
1122          * Send the rest
1123          */
1124         if (msg.m_nentries > 0)
1125         {
1126                 len = offsetof(PgStat_MsgTabpurge, m_tableid[0])
1127                         + msg.m_nentries * sizeof(Oid);
1128
1129                 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
1130                 msg.m_databaseid = MyDatabaseId;
1131                 pgstat_send(&msg, len);
1132         }
1133
1134         /* Clean up */
1135         hash_destroy(htab);
1136
1137         /*
1138          * Now repeat the above steps for functions.  However, we needn't bother
1139          * in the common case where no function stats are being collected.
1140          */
1141         if (dbentry->functions != NULL &&
1142                 hash_get_num_entries(dbentry->functions) > 0)
1143         {
1144                 htab = pgstat_collect_oids(ProcedureRelationId, Anum_pg_proc_oid);
1145
1146                 pgstat_setheader(&f_msg.m_hdr, PGSTAT_MTYPE_FUNCPURGE);
1147                 f_msg.m_databaseid = MyDatabaseId;
1148                 f_msg.m_nentries = 0;
1149
1150                 hash_seq_init(&hstat, dbentry->functions);
1151                 while ((funcentry = (PgStat_StatFuncEntry *) hash_seq_search(&hstat)) != NULL)
1152                 {
1153                         Oid                     funcid = funcentry->functionid;
1154
1155                         CHECK_FOR_INTERRUPTS();
1156
1157                         if (hash_search(htab, (void *) &funcid, HASH_FIND, NULL) != NULL)
1158                                 continue;
1159
1160                         /*
1161                          * Not there, so add this function's Oid to the message
1162                          */
1163                         f_msg.m_functionid[f_msg.m_nentries++] = funcid;
1164
1165                         /*
1166                          * If the message is full, send it out and reinitialize to empty
1167                          */
1168                         if (f_msg.m_nentries >= PGSTAT_NUM_FUNCPURGE)
1169                         {
1170                                 len = offsetof(PgStat_MsgFuncpurge, m_functionid[0])
1171                                         + f_msg.m_nentries * sizeof(Oid);
1172
1173                                 pgstat_send(&f_msg, len);
1174
1175                                 f_msg.m_nentries = 0;
1176                         }
1177                 }
1178
1179                 /*
1180                  * Send the rest
1181                  */
1182                 if (f_msg.m_nentries > 0)
1183                 {
1184                         len = offsetof(PgStat_MsgFuncpurge, m_functionid[0])
1185                                 + f_msg.m_nentries * sizeof(Oid);
1186
1187                         pgstat_send(&f_msg, len);
1188                 }
1189
1190                 hash_destroy(htab);
1191         }
1192 }
1193
1194
1195 /* ----------
1196  * pgstat_collect_oids() -
1197  *
1198  *      Collect the OIDs of all objects listed in the specified system catalog
1199  *      into a temporary hash table.  Caller should hash_destroy the result
1200  *      when done with it.  (However, we make the table in CurrentMemoryContext
1201  *      so that it will be freed properly in event of an error.)
1202  * ----------
1203  */
1204 static HTAB *
1205 pgstat_collect_oids(Oid catalogid, AttrNumber anum_oid)
1206 {
1207         HTAB       *htab;
1208         HASHCTL         hash_ctl;
1209         Relation        rel;
1210         TableScanDesc scan;
1211         HeapTuple       tup;
1212         Snapshot        snapshot;
1213
1214         memset(&hash_ctl, 0, sizeof(hash_ctl));
1215         hash_ctl.keysize = sizeof(Oid);
1216         hash_ctl.entrysize = sizeof(Oid);
1217         hash_ctl.hcxt = CurrentMemoryContext;
1218         htab = hash_create("Temporary table of OIDs",
1219                                            PGSTAT_TAB_HASH_SIZE,
1220                                            &hash_ctl,
1221                                            HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
1222
1223         rel = table_open(catalogid, AccessShareLock);
1224         snapshot = RegisterSnapshot(GetLatestSnapshot());
1225         scan = table_beginscan(rel, snapshot, 0, NULL);
1226         while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
1227         {
1228                 Oid                     thisoid;
1229                 bool            isnull;
1230
1231                 thisoid = heap_getattr(tup, anum_oid, RelationGetDescr(rel), &isnull);
1232                 Assert(!isnull);
1233
1234                 CHECK_FOR_INTERRUPTS();
1235
1236                 (void) hash_search(htab, (void *) &thisoid, HASH_ENTER, NULL);
1237         }
1238         table_endscan(scan);
1239         UnregisterSnapshot(snapshot);
1240         table_close(rel, AccessShareLock);
1241
1242         return htab;
1243 }
1244
1245
1246 /* ----------
1247  * pgstat_drop_database() -
1248  *
1249  *      Tell the collector that we just dropped a database.
1250  *      (If the message gets lost, we will still clean the dead DB eventually
1251  *      via future invocations of pgstat_vacuum_stat().)
1252  * ----------
1253  */
1254 void
1255 pgstat_drop_database(Oid databaseid)
1256 {
1257         PgStat_MsgDropdb msg;
1258
1259         if (pgStatSock == PGINVALID_SOCKET)
1260                 return;
1261
1262         pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_DROPDB);
1263         msg.m_databaseid = databaseid;
1264         pgstat_send(&msg, sizeof(msg));
1265 }
1266
1267
1268 /* ----------
1269  * pgstat_drop_relation() -
1270  *
1271  *      Tell the collector that we just dropped a relation.
1272  *      (If the message gets lost, we will still clean the dead entry eventually
1273  *      via future invocations of pgstat_vacuum_stat().)
1274  *
1275  *      Currently not used for lack of any good place to call it; we rely
1276  *      entirely on pgstat_vacuum_stat() to clean out stats for dead rels.
1277  * ----------
1278  */
1279 #ifdef NOT_USED
1280 void
1281 pgstat_drop_relation(Oid relid)
1282 {
1283         PgStat_MsgTabpurge msg;
1284         int                     len;
1285
1286         if (pgStatSock == PGINVALID_SOCKET)
1287                 return;
1288
1289         msg.m_tableid[0] = relid;
1290         msg.m_nentries = 1;
1291
1292         len = offsetof(PgStat_MsgTabpurge, m_tableid[0]) + sizeof(Oid);
1293
1294         pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
1295         msg.m_databaseid = MyDatabaseId;
1296         pgstat_send(&msg, len);
1297 }
1298 #endif                                                  /* NOT_USED */
1299
1300
1301 /* ----------
1302  * pgstat_reset_counters() -
1303  *
1304  *      Tell the statistics collector to reset counters for our database.
1305  *
1306  *      Permission checking for this function is managed through the normal
1307  *      GRANT system.
1308  * ----------
1309  */
1310 void
1311 pgstat_reset_counters(void)
1312 {
1313         PgStat_MsgResetcounter msg;
1314
1315         if (pgStatSock == PGINVALID_SOCKET)
1316                 return;
1317
1318         pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RESETCOUNTER);
1319         msg.m_databaseid = MyDatabaseId;
1320         pgstat_send(&msg, sizeof(msg));
1321 }
1322
1323 /* ----------
1324  * pgstat_reset_shared_counters() -
1325  *
1326  *      Tell the statistics collector to reset cluster-wide shared counters.
1327  *
1328  *      Permission checking for this function is managed through the normal
1329  *      GRANT system.
1330  * ----------
1331  */
1332 void
1333 pgstat_reset_shared_counters(const char *target)
1334 {
1335         PgStat_MsgResetsharedcounter msg;
1336
1337         if (pgStatSock == PGINVALID_SOCKET)
1338                 return;
1339
1340         if (strcmp(target, "archiver") == 0)
1341                 msg.m_resettarget = RESET_ARCHIVER;
1342         else if (strcmp(target, "bgwriter") == 0)
1343                 msg.m_resettarget = RESET_BGWRITER;
1344         else
1345                 ereport(ERROR,
1346                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1347                                  errmsg("unrecognized reset target: \"%s\"", target),
1348                                  errhint("Target must be \"archiver\" or \"bgwriter\".")));
1349
1350         pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RESETSHAREDCOUNTER);
1351         pgstat_send(&msg, sizeof(msg));
1352 }
1353
1354 /* ----------
1355  * pgstat_reset_single_counter() -
1356  *
1357  *      Tell the statistics collector to reset a single counter.
1358  *
1359  *      Permission checking for this function is managed through the normal
1360  *      GRANT system.
1361  * ----------
1362  */
1363 void
1364 pgstat_reset_single_counter(Oid objoid, PgStat_Single_Reset_Type type)
1365 {
1366         PgStat_MsgResetsinglecounter msg;
1367
1368         if (pgStatSock == PGINVALID_SOCKET)
1369                 return;
1370
1371         pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RESETSINGLECOUNTER);
1372         msg.m_databaseid = MyDatabaseId;
1373         msg.m_resettype = type;
1374         msg.m_objectid = objoid;
1375
1376         pgstat_send(&msg, sizeof(msg));
1377 }
1378
1379 /* ----------
1380  * pgstat_report_autovac() -
1381  *
1382  *      Called from autovacuum.c to report startup of an autovacuum process.
1383  *      We are called before InitPostgres is done, so can't rely on MyDatabaseId;
1384  *      the db OID must be passed in, instead.
1385  * ----------
1386  */
1387 void
1388 pgstat_report_autovac(Oid dboid)
1389 {
1390         PgStat_MsgAutovacStart msg;
1391
1392         if (pgStatSock == PGINVALID_SOCKET)
1393                 return;
1394
1395         pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_AUTOVAC_START);
1396         msg.m_databaseid = dboid;
1397         msg.m_start_time = GetCurrentTimestamp();
1398
1399         pgstat_send(&msg, sizeof(msg));
1400 }
1401
1402
1403 /* ---------
1404  * pgstat_report_vacuum() -
1405  *
1406  *      Tell the collector about the table we just vacuumed.
1407  * ---------
1408  */
1409 void
1410 pgstat_report_vacuum(Oid tableoid, bool shared,
1411                                          PgStat_Counter livetuples, PgStat_Counter deadtuples)
1412 {
1413         PgStat_MsgVacuum msg;
1414
1415         if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
1416                 return;
1417
1418         pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_VACUUM);
1419         msg.m_databaseid = shared ? InvalidOid : MyDatabaseId;
1420         msg.m_tableoid = tableoid;
1421         msg.m_autovacuum = IsAutoVacuumWorkerProcess();
1422         msg.m_vacuumtime = GetCurrentTimestamp();
1423         msg.m_live_tuples = livetuples;
1424         msg.m_dead_tuples = deadtuples;
1425         pgstat_send(&msg, sizeof(msg));
1426 }
1427
1428 /* --------
1429  * pgstat_report_analyze() -
1430  *
1431  *      Tell the collector about the table we just analyzed.
1432  *
1433  * Caller must provide new live- and dead-tuples estimates, as well as a
1434  * flag indicating whether to reset the changes_since_analyze counter.
1435  * --------
1436  */
1437 void
1438 pgstat_report_analyze(Relation rel,
1439                                           PgStat_Counter livetuples, PgStat_Counter deadtuples,
1440                                           bool resetcounter)
1441 {
1442         PgStat_MsgAnalyze msg;
1443
1444         if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
1445                 return;
1446
1447         /*
1448          * Unlike VACUUM, ANALYZE might be running inside a transaction that has
1449          * already inserted and/or deleted rows in the target table. ANALYZE will
1450          * have counted such rows as live or dead respectively. Because we will
1451          * report our counts of such rows at transaction end, we should subtract
1452          * off these counts from what we send to the collector now, else they'll
1453          * be double-counted after commit.  (This approach also ensures that the
1454          * collector ends up with the right numbers if we abort instead of
1455          * committing.)
1456          */
1457         if (rel->pgstat_info != NULL)
1458         {
1459                 PgStat_TableXactStatus *trans;
1460
1461                 for (trans = rel->pgstat_info->trans; trans; trans = trans->upper)
1462                 {
1463                         livetuples -= trans->tuples_inserted - trans->tuples_deleted;
1464                         deadtuples -= trans->tuples_updated + trans->tuples_deleted;
1465                 }
1466                 /* count stuff inserted by already-aborted subxacts, too */
1467                 deadtuples -= rel->pgstat_info->t_counts.t_delta_dead_tuples;
1468                 /* Since ANALYZE's counts are estimates, we could have underflowed */
1469                 livetuples = Max(livetuples, 0);
1470                 deadtuples = Max(deadtuples, 0);
1471         }
1472
1473         pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_ANALYZE);
1474         msg.m_databaseid = rel->rd_rel->relisshared ? InvalidOid : MyDatabaseId;
1475         msg.m_tableoid = RelationGetRelid(rel);
1476         msg.m_autovacuum = IsAutoVacuumWorkerProcess();
1477         msg.m_resetcounter = resetcounter;
1478         msg.m_analyzetime = GetCurrentTimestamp();
1479         msg.m_live_tuples = livetuples;
1480         msg.m_dead_tuples = deadtuples;
1481         pgstat_send(&msg, sizeof(msg));
1482 }
1483
1484 /* --------
1485  * pgstat_report_recovery_conflict() -
1486  *
1487  *      Tell the collector about a Hot Standby recovery conflict.
1488  * --------
1489  */
1490 void
1491 pgstat_report_recovery_conflict(int reason)
1492 {
1493         PgStat_MsgRecoveryConflict msg;
1494
1495         if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
1496                 return;
1497
1498         pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RECOVERYCONFLICT);
1499         msg.m_databaseid = MyDatabaseId;
1500         msg.m_reason = reason;
1501         pgstat_send(&msg, sizeof(msg));
1502 }
1503
1504 /* --------
1505  * pgstat_report_deadlock() -
1506  *
1507  *      Tell the collector about a deadlock detected.
1508  * --------
1509  */
1510 void
1511 pgstat_report_deadlock(void)
1512 {
1513         PgStat_MsgDeadlock msg;
1514
1515         if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
1516                 return;
1517
1518         pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_DEADLOCK);
1519         msg.m_databaseid = MyDatabaseId;
1520         pgstat_send(&msg, sizeof(msg));
1521 }
1522
1523
1524
1525 /* --------
1526  * pgstat_report_checksum_failures_in_db(dboid, failure_count) -
1527  *
1528  *      Tell the collector about one or more checksum failures.
1529  * --------
1530  */
1531 void
1532 pgstat_report_checksum_failures_in_db(Oid dboid, int failurecount)
1533 {
1534         PgStat_MsgChecksumFailure msg;
1535
1536         if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
1537                 return;
1538
1539         pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_CHECKSUMFAILURE);
1540         msg.m_databaseid = dboid;
1541         msg.m_failurecount = failurecount;
1542         pgstat_send(&msg, sizeof(msg));
1543 }
1544
1545 /* --------
1546  * pgstat_report_checksum_failure() -
1547  *
1548  *      Tell the collector about a checksum failure.
1549  * --------
1550  */
1551 void
1552 pgstat_report_checksum_failure(void)
1553 {
1554         pgstat_report_checksum_failures_in_db(MyDatabaseId, 1);
1555 }
1556
1557 /* --------
1558  * pgstat_report_tempfile() -
1559  *
1560  *      Tell the collector about a temporary file.
1561  * --------
1562  */
1563 void
1564 pgstat_report_tempfile(size_t filesize)
1565 {
1566         PgStat_MsgTempFile msg;
1567
1568         if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
1569                 return;
1570
1571         pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TEMPFILE);
1572         msg.m_databaseid = MyDatabaseId;
1573         msg.m_filesize = filesize;
1574         pgstat_send(&msg, sizeof(msg));
1575 }
1576
1577
1578 /* ----------
1579  * pgstat_ping() -
1580  *
1581  *      Send some junk data to the collector to increase traffic.
1582  * ----------
1583  */
1584 void
1585 pgstat_ping(void)
1586 {
1587         PgStat_MsgDummy msg;
1588
1589         if (pgStatSock == PGINVALID_SOCKET)
1590                 return;
1591
1592         pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_DUMMY);
1593         pgstat_send(&msg, sizeof(msg));
1594 }
1595
1596 /* ----------
1597  * pgstat_send_inquiry() -
1598  *
1599  *      Notify collector that we need fresh data.
1600  * ----------
1601  */
1602 static void
1603 pgstat_send_inquiry(TimestampTz clock_time, TimestampTz cutoff_time, Oid databaseid)
1604 {
1605         PgStat_MsgInquiry msg;
1606
1607         pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_INQUIRY);
1608         msg.clock_time = clock_time;
1609         msg.cutoff_time = cutoff_time;
1610         msg.databaseid = databaseid;
1611         pgstat_send(&msg, sizeof(msg));
1612 }
1613
1614
1615 /*
1616  * Initialize function call usage data.
1617  * Called by the executor before invoking a function.
1618  */
1619 void
1620 pgstat_init_function_usage(FunctionCallInfo fcinfo,
1621                                                    PgStat_FunctionCallUsage *fcu)
1622 {
1623         PgStat_BackendFunctionEntry *htabent;
1624         bool            found;
1625
1626         if (pgstat_track_functions <= fcinfo->flinfo->fn_stats)
1627         {
1628                 /* stats not wanted */
1629                 fcu->fs = NULL;
1630                 return;
1631         }
1632
1633         if (!pgStatFunctions)
1634         {
1635                 /* First time through - initialize function stat table */
1636                 HASHCTL         hash_ctl;
1637
1638                 memset(&hash_ctl, 0, sizeof(hash_ctl));
1639                 hash_ctl.keysize = sizeof(Oid);
1640                 hash_ctl.entrysize = sizeof(PgStat_BackendFunctionEntry);
1641                 pgStatFunctions = hash_create("Function stat entries",
1642                                                                           PGSTAT_FUNCTION_HASH_SIZE,
1643                                                                           &hash_ctl,
1644                                                                           HASH_ELEM | HASH_BLOBS);
1645         }
1646
1647         /* Get the stats entry for this function, create if necessary */
1648         htabent = hash_search(pgStatFunctions, &fcinfo->flinfo->fn_oid,
1649                                                   HASH_ENTER, &found);
1650         if (!found)
1651                 MemSet(&htabent->f_counts, 0, sizeof(PgStat_FunctionCounts));
1652
1653         fcu->fs = &htabent->f_counts;
1654
1655         /* save stats for this function, later used to compensate for recursion */
1656         fcu->save_f_total_time = htabent->f_counts.f_total_time;
1657
1658         /* save current backend-wide total time */
1659         fcu->save_total = total_func_time;
1660
1661         /* get clock time as of function start */
1662         INSTR_TIME_SET_CURRENT(fcu->f_start);
1663 }
1664
1665 /*
1666  * find_funcstat_entry - find any existing PgStat_BackendFunctionEntry entry
1667  *              for specified function
1668  *
1669  * If no entry, return NULL, don't create a new one
1670  */
1671 PgStat_BackendFunctionEntry *
1672 find_funcstat_entry(Oid func_id)
1673 {
1674         if (pgStatFunctions == NULL)
1675                 return NULL;
1676
1677         return (PgStat_BackendFunctionEntry *) hash_search(pgStatFunctions,
1678                                                                                                            (void *) &func_id,
1679                                                                                                            HASH_FIND, NULL);
1680 }
1681
1682 /*
1683  * Calculate function call usage and update stat counters.
1684  * Called by the executor after invoking a function.
1685  *
1686  * In the case of a set-returning function that runs in value-per-call mode,
1687  * we will see multiple pgstat_init_function_usage/pgstat_end_function_usage
1688  * calls for what the user considers a single call of the function.  The
1689  * finalize flag should be TRUE on the last call.
1690  */
1691 void
1692 pgstat_end_function_usage(PgStat_FunctionCallUsage *fcu, bool finalize)
1693 {
1694         PgStat_FunctionCounts *fs = fcu->fs;
1695         instr_time      f_total;
1696         instr_time      f_others;
1697         instr_time      f_self;
1698
1699         /* stats not wanted? */
1700         if (fs == NULL)
1701                 return;
1702
1703         /* total elapsed time in this function call */
1704         INSTR_TIME_SET_CURRENT(f_total);
1705         INSTR_TIME_SUBTRACT(f_total, fcu->f_start);
1706
1707         /* self usage: elapsed minus anything already charged to other calls */
1708         f_others = total_func_time;
1709         INSTR_TIME_SUBTRACT(f_others, fcu->save_total);
1710         f_self = f_total;
1711         INSTR_TIME_SUBTRACT(f_self, f_others);
1712
1713         /* update backend-wide total time */
1714         INSTR_TIME_ADD(total_func_time, f_self);
1715
1716         /*
1717          * Compute the new f_total_time as the total elapsed time added to the
1718          * pre-call value of f_total_time.  This is necessary to avoid
1719          * double-counting any time taken by recursive calls of myself.  (We do
1720          * not need any similar kluge for self time, since that already excludes
1721          * any recursive calls.)
1722          */
1723         INSTR_TIME_ADD(f_total, fcu->save_f_total_time);
1724
1725         /* update counters in function stats table */
1726         if (finalize)
1727                 fs->f_numcalls++;
1728         fs->f_total_time = f_total;
1729         INSTR_TIME_ADD(fs->f_self_time, f_self);
1730
1731         /* indicate that we have something to send */
1732         have_function_stats = true;
1733 }
1734
1735
1736 /* ----------
1737  * pgstat_initstats() -
1738  *
1739  *      Initialize a relcache entry to count access statistics.
1740  *      Called whenever a relation is opened.
1741  *
1742  *      We assume that a relcache entry's pgstat_info field is zeroed by
1743  *      relcache.c when the relcache entry is made; thereafter it is long-lived
1744  *      data.  We can avoid repeated searches of the TabStatus arrays when the
1745  *      same relation is touched repeatedly within a transaction.
1746  * ----------
1747  */
1748 void
1749 pgstat_initstats(Relation rel)
1750 {
1751         Oid                     rel_id = rel->rd_id;
1752         char            relkind = rel->rd_rel->relkind;
1753
1754         /* We only count stats for things that have storage */
1755         if (!(relkind == RELKIND_RELATION ||
1756                   relkind == RELKIND_MATVIEW ||
1757                   relkind == RELKIND_INDEX ||
1758                   relkind == RELKIND_TOASTVALUE ||
1759                   relkind == RELKIND_SEQUENCE))
1760         {
1761                 rel->pgstat_info = NULL;
1762                 return;
1763         }
1764
1765         if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
1766         {
1767                 /* We're not counting at all */
1768                 rel->pgstat_info = NULL;
1769                 return;
1770         }
1771
1772         /*
1773          * If we already set up this relation in the current transaction, nothing
1774          * to do.
1775          */
1776         if (rel->pgstat_info != NULL &&
1777                 rel->pgstat_info->t_id == rel_id)
1778                 return;
1779
1780         /* Else find or make the PgStat_TableStatus entry, and update link */
1781         rel->pgstat_info = get_tabstat_entry(rel_id, rel->rd_rel->relisshared);
1782 }
1783
1784 /*
1785  * get_tabstat_entry - find or create a PgStat_TableStatus entry for rel
1786  */
1787 static PgStat_TableStatus *
1788 get_tabstat_entry(Oid rel_id, bool isshared)
1789 {
1790         TabStatHashEntry *hash_entry;
1791         PgStat_TableStatus *entry;
1792         TabStatusArray *tsa;
1793         bool            found;
1794
1795         /*
1796          * Create hash table if we don't have it already.
1797          */
1798         if (pgStatTabHash == NULL)
1799         {
1800                 HASHCTL         ctl;
1801
1802                 memset(&ctl, 0, sizeof(ctl));
1803                 ctl.keysize = sizeof(Oid);
1804                 ctl.entrysize = sizeof(TabStatHashEntry);
1805
1806                 pgStatTabHash = hash_create("pgstat TabStatusArray lookup hash table",
1807                                                                         TABSTAT_QUANTUM,
1808                                                                         &ctl,
1809                                                                         HASH_ELEM | HASH_BLOBS);
1810         }
1811
1812         /*
1813          * Find an entry or create a new one.
1814          */
1815         hash_entry = hash_search(pgStatTabHash, &rel_id, HASH_ENTER, &found);
1816         if (!found)
1817         {
1818                 /* initialize new entry with null pointer */
1819                 hash_entry->tsa_entry = NULL;
1820         }
1821
1822         /*
1823          * If entry is already valid, we're done.
1824          */
1825         if (hash_entry->tsa_entry)
1826                 return hash_entry->tsa_entry;
1827
1828         /*
1829          * Locate the first pgStatTabList entry with free space, making a new list
1830          * entry if needed.  Note that we could get an OOM failure here, but if so
1831          * we have left the hashtable and the list in a consistent state.
1832          */
1833         if (pgStatTabList == NULL)
1834         {
1835                 /* Set up first pgStatTabList entry */
1836                 pgStatTabList = (TabStatusArray *)
1837                         MemoryContextAllocZero(TopMemoryContext,
1838                                                                    sizeof(TabStatusArray));
1839         }
1840
1841         tsa = pgStatTabList;
1842         while (tsa->tsa_used >= TABSTAT_QUANTUM)
1843         {
1844                 if (tsa->tsa_next == NULL)
1845                         tsa->tsa_next = (TabStatusArray *)
1846                                 MemoryContextAllocZero(TopMemoryContext,
1847                                                                            sizeof(TabStatusArray));
1848                 tsa = tsa->tsa_next;
1849         }
1850
1851         /*
1852          * Allocate a PgStat_TableStatus entry within this list entry.  We assume
1853          * the entry was already zeroed, either at creation or after last use.
1854          */
1855         entry = &tsa->tsa_entries[tsa->tsa_used++];
1856         entry->t_id = rel_id;
1857         entry->t_shared = isshared;
1858
1859         /*
1860          * Now we can fill the entry in pgStatTabHash.
1861          */
1862         hash_entry->tsa_entry = entry;
1863
1864         return entry;
1865 }
1866
1867 /*
1868  * find_tabstat_entry - find any existing PgStat_TableStatus entry for rel
1869  *
1870  * If no entry, return NULL, don't create a new one
1871  *
1872  * Note: if we got an error in the most recent execution of pgstat_report_stat,
1873  * it's possible that an entry exists but there's no hashtable entry for it.
1874  * That's okay, we'll treat this case as "doesn't exist".
1875  */
1876 PgStat_TableStatus *
1877 find_tabstat_entry(Oid rel_id)
1878 {
1879         TabStatHashEntry *hash_entry;
1880
1881         /* If hashtable doesn't exist, there are no entries at all */
1882         if (!pgStatTabHash)
1883                 return NULL;
1884
1885         hash_entry = hash_search(pgStatTabHash, &rel_id, HASH_FIND, NULL);
1886         if (!hash_entry)
1887                 return NULL;
1888
1889         /* Note that this step could also return NULL, but that's correct */
1890         return hash_entry->tsa_entry;
1891 }
1892
1893 /*
1894  * get_tabstat_stack_level - add a new (sub)transaction stack entry if needed
1895  */
1896 static PgStat_SubXactStatus *
1897 get_tabstat_stack_level(int nest_level)
1898 {
1899         PgStat_SubXactStatus *xact_state;
1900
1901         xact_state = pgStatXactStack;
1902         if (xact_state == NULL || xact_state->nest_level != nest_level)
1903         {
1904                 xact_state = (PgStat_SubXactStatus *)
1905                         MemoryContextAlloc(TopTransactionContext,
1906                                                            sizeof(PgStat_SubXactStatus));
1907                 xact_state->nest_level = nest_level;
1908                 xact_state->prev = pgStatXactStack;
1909                 xact_state->first = NULL;
1910                 pgStatXactStack = xact_state;
1911         }
1912         return xact_state;
1913 }
1914
1915 /*
1916  * add_tabstat_xact_level - add a new (sub)transaction state record
1917  */
1918 static void
1919 add_tabstat_xact_level(PgStat_TableStatus *pgstat_info, int nest_level)
1920 {
1921         PgStat_SubXactStatus *xact_state;
1922         PgStat_TableXactStatus *trans;
1923
1924         /*
1925          * If this is the first rel to be modified at the current nest level, we
1926          * first have to push a transaction stack entry.
1927          */
1928         xact_state = get_tabstat_stack_level(nest_level);
1929
1930         /* Now make a per-table stack entry */
1931         trans = (PgStat_TableXactStatus *)
1932                 MemoryContextAllocZero(TopTransactionContext,
1933                                                            sizeof(PgStat_TableXactStatus));
1934         trans->nest_level = nest_level;
1935         trans->upper = pgstat_info->trans;
1936         trans->parent = pgstat_info;
1937         trans->next = xact_state->first;
1938         xact_state->first = trans;
1939         pgstat_info->trans = trans;
1940 }
1941
1942 /*
1943  * pgstat_count_heap_insert - count a tuple insertion of n tuples
1944  */
1945 void
1946 pgstat_count_heap_insert(Relation rel, PgStat_Counter n)
1947 {
1948         PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1949
1950         if (pgstat_info != NULL)
1951         {
1952                 /* We have to log the effect at the proper transactional level */
1953                 int                     nest_level = GetCurrentTransactionNestLevel();
1954
1955                 if (pgstat_info->trans == NULL ||
1956                         pgstat_info->trans->nest_level != nest_level)
1957                         add_tabstat_xact_level(pgstat_info, nest_level);
1958
1959                 pgstat_info->trans->tuples_inserted += n;
1960         }
1961 }
1962
1963 /*
1964  * pgstat_count_heap_update - count a tuple update
1965  */
1966 void
1967 pgstat_count_heap_update(Relation rel, bool hot)
1968 {
1969         PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1970
1971         if (pgstat_info != NULL)
1972         {
1973                 /* We have to log the effect at the proper transactional level */
1974                 int                     nest_level = GetCurrentTransactionNestLevel();
1975
1976                 if (pgstat_info->trans == NULL ||
1977                         pgstat_info->trans->nest_level != nest_level)
1978                         add_tabstat_xact_level(pgstat_info, nest_level);
1979
1980                 pgstat_info->trans->tuples_updated++;
1981
1982                 /* t_tuples_hot_updated is nontransactional, so just advance it */
1983                 if (hot)
1984                         pgstat_info->t_counts.t_tuples_hot_updated++;
1985         }
1986 }
1987
1988 /*
1989  * pgstat_count_heap_delete - count a tuple deletion
1990  */
1991 void
1992 pgstat_count_heap_delete(Relation rel)
1993 {
1994         PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1995
1996         if (pgstat_info != NULL)
1997         {
1998                 /* We have to log the effect at the proper transactional level */
1999                 int                     nest_level = GetCurrentTransactionNestLevel();
2000
2001                 if (pgstat_info->trans == NULL ||
2002                         pgstat_info->trans->nest_level != nest_level)
2003                         add_tabstat_xact_level(pgstat_info, nest_level);
2004
2005                 pgstat_info->trans->tuples_deleted++;
2006         }
2007 }
2008
2009 /*
2010  * pgstat_truncate_save_counters
2011  *
2012  * Whenever a table is truncated, we save its i/u/d counters so that they can
2013  * be cleared, and if the (sub)xact that executed the truncate later aborts,
2014  * the counters can be restored to the saved (pre-truncate) values.  Note we do
2015  * this on the first truncate in any particular subxact level only.
2016  */
2017 static void
2018 pgstat_truncate_save_counters(PgStat_TableXactStatus *trans)
2019 {
2020         if (!trans->truncated)
2021         {
2022                 trans->inserted_pre_trunc = trans->tuples_inserted;
2023                 trans->updated_pre_trunc = trans->tuples_updated;
2024                 trans->deleted_pre_trunc = trans->tuples_deleted;
2025                 trans->truncated = true;
2026         }
2027 }
2028
2029 /*
2030  * pgstat_truncate_restore_counters - restore counters when a truncate aborts
2031  */
2032 static void
2033 pgstat_truncate_restore_counters(PgStat_TableXactStatus *trans)
2034 {
2035         if (trans->truncated)
2036         {
2037                 trans->tuples_inserted = trans->inserted_pre_trunc;
2038                 trans->tuples_updated = trans->updated_pre_trunc;
2039                 trans->tuples_deleted = trans->deleted_pre_trunc;
2040         }
2041 }
2042
2043 /*
2044  * pgstat_count_truncate - update tuple counters due to truncate
2045  */
2046 void
2047 pgstat_count_truncate(Relation rel)
2048 {
2049         PgStat_TableStatus *pgstat_info = rel->pgstat_info;
2050
2051         if (pgstat_info != NULL)
2052         {
2053                 /* We have to log the effect at the proper transactional level */
2054                 int                     nest_level = GetCurrentTransactionNestLevel();
2055
2056                 if (pgstat_info->trans == NULL ||
2057                         pgstat_info->trans->nest_level != nest_level)
2058                         add_tabstat_xact_level(pgstat_info, nest_level);
2059
2060                 pgstat_truncate_save_counters(pgstat_info->trans);
2061                 pgstat_info->trans->tuples_inserted = 0;
2062                 pgstat_info->trans->tuples_updated = 0;
2063                 pgstat_info->trans->tuples_deleted = 0;
2064         }
2065 }
2066
2067 /*
2068  * pgstat_update_heap_dead_tuples - update dead-tuples count
2069  *
2070  * The semantics of this are that we are reporting the nontransactional
2071  * recovery of "delta" dead tuples; so t_delta_dead_tuples decreases
2072  * rather than increasing, and the change goes straight into the per-table
2073  * counter, not into transactional state.
2074  */
2075 void
2076 pgstat_update_heap_dead_tuples(Relation rel, int delta)
2077 {
2078         PgStat_TableStatus *pgstat_info = rel->pgstat_info;
2079
2080         if (pgstat_info != NULL)
2081                 pgstat_info->t_counts.t_delta_dead_tuples -= delta;
2082 }
2083
2084
2085 /* ----------
2086  * AtEOXact_PgStat
2087  *
2088  *      Called from access/transam/xact.c at top-level transaction commit/abort.
2089  * ----------
2090  */
2091 void
2092 AtEOXact_PgStat(bool isCommit)
2093 {
2094         PgStat_SubXactStatus *xact_state;
2095
2096         /*
2097          * Count transaction commit or abort.  (We use counters, not just bools,
2098          * in case the reporting message isn't sent right away.)
2099          */
2100         if (isCommit)
2101                 pgStatXactCommit++;
2102         else
2103                 pgStatXactRollback++;
2104
2105         /*
2106          * Transfer transactional insert/update counts into the base tabstat
2107          * entries.  We don't bother to free any of the transactional state, since
2108          * it's all in TopTransactionContext and will go away anyway.
2109          */
2110         xact_state = pgStatXactStack;
2111         if (xact_state != NULL)
2112         {
2113                 PgStat_TableXactStatus *trans;
2114
2115                 Assert(xact_state->nest_level == 1);
2116                 Assert(xact_state->prev == NULL);
2117                 for (trans = xact_state->first; trans != NULL; trans = trans->next)
2118                 {
2119                         PgStat_TableStatus *tabstat;
2120
2121                         Assert(trans->nest_level == 1);
2122                         Assert(trans->upper == NULL);
2123                         tabstat = trans->parent;
2124                         Assert(tabstat->trans == trans);
2125                         /* restore pre-truncate stats (if any) in case of aborted xact */
2126                         if (!isCommit)
2127                                 pgstat_truncate_restore_counters(trans);
2128                         /* count attempted actions regardless of commit/abort */
2129                         tabstat->t_counts.t_tuples_inserted += trans->tuples_inserted;
2130                         tabstat->t_counts.t_tuples_updated += trans->tuples_updated;
2131                         tabstat->t_counts.t_tuples_deleted += trans->tuples_deleted;
2132                         if (isCommit)
2133                         {
2134                                 tabstat->t_counts.t_truncated = trans->truncated;
2135                                 if (trans->truncated)
2136                                 {
2137                                         /* forget live/dead stats seen by backend thus far */
2138                                         tabstat->t_counts.t_delta_live_tuples = 0;
2139                                         tabstat->t_counts.t_delta_dead_tuples = 0;
2140                                 }
2141                                 /* insert adds a live tuple, delete removes one */
2142                                 tabstat->t_counts.t_delta_live_tuples +=
2143                                         trans->tuples_inserted - trans->tuples_deleted;
2144                                 /* update and delete each create a dead tuple */
2145                                 tabstat->t_counts.t_delta_dead_tuples +=
2146                                         trans->tuples_updated + trans->tuples_deleted;
2147                                 /* insert, update, delete each count as one change event */
2148                                 tabstat->t_counts.t_changed_tuples +=
2149                                         trans->tuples_inserted + trans->tuples_updated +
2150                                         trans->tuples_deleted;
2151                         }
2152                         else
2153                         {
2154                                 /* inserted tuples are dead, deleted tuples are unaffected */
2155                                 tabstat->t_counts.t_delta_dead_tuples +=
2156                                         trans->tuples_inserted + trans->tuples_updated;
2157                                 /* an aborted xact generates no changed_tuple events */
2158                         }
2159                         tabstat->trans = NULL;
2160                 }
2161         }
2162         pgStatXactStack = NULL;
2163
2164         /* Make sure any stats snapshot is thrown away */
2165         pgstat_clear_snapshot();
2166 }
2167
2168 /* ----------
2169  * AtEOSubXact_PgStat
2170  *
2171  *      Called from access/transam/xact.c at subtransaction commit/abort.
2172  * ----------
2173  */
2174 void
2175 AtEOSubXact_PgStat(bool isCommit, int nestDepth)
2176 {
2177         PgStat_SubXactStatus *xact_state;
2178
2179         /*
2180          * Transfer transactional insert/update counts into the next higher
2181          * subtransaction state.
2182          */
2183         xact_state = pgStatXactStack;
2184         if (xact_state != NULL &&
2185                 xact_state->nest_level >= nestDepth)
2186         {
2187                 PgStat_TableXactStatus *trans;
2188                 PgStat_TableXactStatus *next_trans;
2189
2190                 /* delink xact_state from stack immediately to simplify reuse case */
2191                 pgStatXactStack = xact_state->prev;
2192
2193                 for (trans = xact_state->first; trans != NULL; trans = next_trans)
2194                 {
2195                         PgStat_TableStatus *tabstat;
2196
2197                         next_trans = trans->next;
2198                         Assert(trans->nest_level == nestDepth);
2199                         tabstat = trans->parent;
2200                         Assert(tabstat->trans == trans);
2201                         if (isCommit)
2202                         {
2203                                 if (trans->upper && trans->upper->nest_level == nestDepth - 1)
2204                                 {
2205                                         if (trans->truncated)
2206                                         {
2207                                                 /* propagate the truncate status one level up */
2208                                                 pgstat_truncate_save_counters(trans->upper);
2209                                                 /* replace upper xact stats with ours */
2210                                                 trans->upper->tuples_inserted = trans->tuples_inserted;
2211                                                 trans->upper->tuples_updated = trans->tuples_updated;
2212                                                 trans->upper->tuples_deleted = trans->tuples_deleted;
2213                                         }
2214                                         else
2215                                         {
2216                                                 trans->upper->tuples_inserted += trans->tuples_inserted;
2217                                                 trans->upper->tuples_updated += trans->tuples_updated;
2218                                                 trans->upper->tuples_deleted += trans->tuples_deleted;
2219                                         }
2220                                         tabstat->trans = trans->upper;
2221                                         pfree(trans);
2222                                 }
2223                                 else
2224                                 {
2225                                         /*
2226                                          * When there isn't an immediate parent state, we can just
2227                                          * reuse the record instead of going through a
2228                                          * palloc/pfree pushup (this works since it's all in
2229                                          * TopTransactionContext anyway).  We have to re-link it
2230                                          * into the parent level, though, and that might mean
2231                                          * pushing a new entry into the pgStatXactStack.
2232                                          */
2233                                         PgStat_SubXactStatus *upper_xact_state;
2234
2235                                         upper_xact_state = get_tabstat_stack_level(nestDepth - 1);
2236                                         trans->next = upper_xact_state->first;
2237                                         upper_xact_state->first = trans;
2238                                         trans->nest_level = nestDepth - 1;
2239                                 }
2240                         }
2241                         else
2242                         {
2243                                 /*
2244                                  * On abort, update top-level tabstat counts, then forget the
2245                                  * subtransaction
2246                                  */
2247
2248                                 /* first restore values obliterated by truncate */
2249                                 pgstat_truncate_restore_counters(trans);
2250                                 /* count attempted actions regardless of commit/abort */
2251                                 tabstat->t_counts.t_tuples_inserted += trans->tuples_inserted;
2252                                 tabstat->t_counts.t_tuples_updated += trans->tuples_updated;
2253                                 tabstat->t_counts.t_tuples_deleted += trans->tuples_deleted;
2254                                 /* inserted tuples are dead, deleted tuples are unaffected */
2255                                 tabstat->t_counts.t_delta_dead_tuples +=
2256                                         trans->tuples_inserted + trans->tuples_updated;
2257                                 tabstat->trans = trans->upper;
2258                                 pfree(trans);
2259                         }
2260                 }
2261                 pfree(xact_state);
2262         }
2263 }
2264
2265
2266 /*
2267  * AtPrepare_PgStat
2268  *              Save the transactional stats state at 2PC transaction prepare.
2269  *
2270  * In this phase we just generate 2PC records for all the pending
2271  * transaction-dependent stats work.
2272  */
2273 void
2274 AtPrepare_PgStat(void)
2275 {
2276         PgStat_SubXactStatus *xact_state;
2277
2278         xact_state = pgStatXactStack;
2279         if (xact_state != NULL)
2280         {
2281                 PgStat_TableXactStatus *trans;
2282
2283                 Assert(xact_state->nest_level == 1);
2284                 Assert(xact_state->prev == NULL);
2285                 for (trans = xact_state->first; trans != NULL; trans = trans->next)
2286                 {
2287                         PgStat_TableStatus *tabstat;
2288                         TwoPhasePgStatRecord record;
2289
2290                         Assert(trans->nest_level == 1);
2291                         Assert(trans->upper == NULL);
2292                         tabstat = trans->parent;
2293                         Assert(tabstat->trans == trans);
2294
2295                         record.tuples_inserted = trans->tuples_inserted;
2296                         record.tuples_updated = trans->tuples_updated;
2297                         record.tuples_deleted = trans->tuples_deleted;
2298                         record.inserted_pre_trunc = trans->inserted_pre_trunc;
2299                         record.updated_pre_trunc = trans->updated_pre_trunc;
2300                         record.deleted_pre_trunc = trans->deleted_pre_trunc;
2301                         record.t_id = tabstat->t_id;
2302                         record.t_shared = tabstat->t_shared;
2303                         record.t_truncated = trans->truncated;
2304
2305                         RegisterTwoPhaseRecord(TWOPHASE_RM_PGSTAT_ID, 0,
2306                                                                    &record, sizeof(TwoPhasePgStatRecord));
2307                 }
2308         }
2309 }
2310
2311 /*
2312  * PostPrepare_PgStat
2313  *              Clean up after successful PREPARE.
2314  *
2315  * All we need do here is unlink the transaction stats state from the
2316  * nontransactional state.  The nontransactional action counts will be
2317  * reported to the stats collector immediately, while the effects on live
2318  * and dead tuple counts are preserved in the 2PC state file.
2319  *
2320  * Note: AtEOXact_PgStat is not called during PREPARE.
2321  */
2322 void
2323 PostPrepare_PgStat(void)
2324 {
2325         PgStat_SubXactStatus *xact_state;
2326
2327         /*
2328          * We don't bother to free any of the transactional state, since it's all
2329          * in TopTransactionContext and will go away anyway.
2330          */
2331         xact_state = pgStatXactStack;
2332         if (xact_state != NULL)
2333         {
2334                 PgStat_TableXactStatus *trans;
2335
2336                 for (trans = xact_state->first; trans != NULL; trans = trans->next)
2337                 {
2338                         PgStat_TableStatus *tabstat;
2339
2340                         tabstat = trans->parent;
2341                         tabstat->trans = NULL;
2342                 }
2343         }
2344         pgStatXactStack = NULL;
2345
2346         /* Make sure any stats snapshot is thrown away */
2347         pgstat_clear_snapshot();
2348 }
2349
2350 /*
2351  * 2PC processing routine for COMMIT PREPARED case.
2352  *
2353  * Load the saved counts into our local pgstats state.
2354  */
2355 void
2356 pgstat_twophase_postcommit(TransactionId xid, uint16 info,
2357                                                    void *recdata, uint32 len)
2358 {
2359         TwoPhasePgStatRecord *rec = (TwoPhasePgStatRecord *) recdata;
2360         PgStat_TableStatus *pgstat_info;
2361
2362         /* Find or create a tabstat entry for the rel */
2363         pgstat_info = get_tabstat_entry(rec->t_id, rec->t_shared);
2364
2365         /* Same math as in AtEOXact_PgStat, commit case */
2366         pgstat_info->t_counts.t_tuples_inserted += rec->tuples_inserted;
2367         pgstat_info->t_counts.t_tuples_updated += rec->tuples_updated;
2368         pgstat_info->t_counts.t_tuples_deleted += rec->tuples_deleted;
2369         pgstat_info->t_counts.t_truncated = rec->t_truncated;
2370         if (rec->t_truncated)
2371         {
2372                 /* forget live/dead stats seen by backend thus far */
2373                 pgstat_info->t_counts.t_delta_live_tuples = 0;
2374                 pgstat_info->t_counts.t_delta_dead_tuples = 0;
2375         }
2376         pgstat_info->t_counts.t_delta_live_tuples +=
2377                 rec->tuples_inserted - rec->tuples_deleted;
2378         pgstat_info->t_counts.t_delta_dead_tuples +=
2379                 rec->tuples_updated + rec->tuples_deleted;
2380         pgstat_info->t_counts.t_changed_tuples +=
2381                 rec->tuples_inserted + rec->tuples_updated +
2382                 rec->tuples_deleted;
2383 }
2384
2385 /*
2386  * 2PC processing routine for ROLLBACK PREPARED case.
2387  *
2388  * Load the saved counts into our local pgstats state, but treat them
2389  * as aborted.
2390  */
2391 void
2392 pgstat_twophase_postabort(TransactionId xid, uint16 info,
2393                                                   void *recdata, uint32 len)
2394 {
2395         TwoPhasePgStatRecord *rec = (TwoPhasePgStatRecord *) recdata;
2396         PgStat_TableStatus *pgstat_info;
2397
2398         /* Find or create a tabstat entry for the rel */
2399         pgstat_info = get_tabstat_entry(rec->t_id, rec->t_shared);
2400
2401         /* Same math as in AtEOXact_PgStat, abort case */
2402         if (rec->t_truncated)
2403         {
2404                 rec->tuples_inserted = rec->inserted_pre_trunc;
2405                 rec->tuples_updated = rec->updated_pre_trunc;
2406                 rec->tuples_deleted = rec->deleted_pre_trunc;
2407         }
2408         pgstat_info->t_counts.t_tuples_inserted += rec->tuples_inserted;
2409         pgstat_info->t_counts.t_tuples_updated += rec->tuples_updated;
2410         pgstat_info->t_counts.t_tuples_deleted += rec->tuples_deleted;
2411         pgstat_info->t_counts.t_delta_dead_tuples +=
2412                 rec->tuples_inserted + rec->tuples_updated;
2413 }
2414
2415
2416 /* ----------
2417  * pgstat_fetch_stat_dbentry() -
2418  *
2419  *      Support function for the SQL-callable pgstat* functions. Returns
2420  *      the collected statistics for one database or NULL. NULL doesn't mean
2421  *      that the database doesn't exist, it is just not yet known by the
2422  *      collector, so the caller is better off to report ZERO instead.
2423  * ----------
2424  */
2425 PgStat_StatDBEntry *
2426 pgstat_fetch_stat_dbentry(Oid dbid)
2427 {
2428         /*
2429          * If not done for this transaction, read the statistics collector stats
2430          * file into some hash tables.
2431          */
2432         backend_read_statsfile();
2433
2434         /*
2435          * Lookup the requested database; return NULL if not found
2436          */
2437         return (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
2438                                                                                           (void *) &dbid,
2439                                                                                           HASH_FIND, NULL);
2440 }
2441
2442
2443 /* ----------
2444  * pgstat_fetch_stat_tabentry() -
2445  *
2446  *      Support function for the SQL-callable pgstat* functions. Returns
2447  *      the collected statistics for one table or NULL. NULL doesn't mean
2448  *      that the table doesn't exist, it is just not yet known by the
2449  *      collector, so the caller is better off to report ZERO instead.
2450  * ----------
2451  */
2452 PgStat_StatTabEntry *
2453 pgstat_fetch_stat_tabentry(Oid relid)
2454 {
2455         Oid                     dbid;
2456         PgStat_StatDBEntry *dbentry;
2457         PgStat_StatTabEntry *tabentry;
2458
2459         /*
2460          * If not done for this transaction, read the statistics collector stats
2461          * file into some hash tables.
2462          */
2463         backend_read_statsfile();
2464
2465         /*
2466          * Lookup our database, then look in its table hash table.
2467          */
2468         dbid = MyDatabaseId;
2469         dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
2470                                                                                                  (void *) &dbid,
2471                                                                                                  HASH_FIND, NULL);
2472         if (dbentry != NULL && dbentry->tables != NULL)
2473         {
2474                 tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
2475                                                                                                            (void *) &relid,
2476                                                                                                            HASH_FIND, NULL);
2477                 if (tabentry)
2478                         return tabentry;
2479         }
2480
2481         /*
2482          * If we didn't find it, maybe it's a shared table.
2483          */
2484         dbid = InvalidOid;
2485         dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
2486                                                                                                  (void *) &dbid,
2487                                                                                                  HASH_FIND, NULL);
2488         if (dbentry != NULL && dbentry->tables != NULL)
2489         {
2490                 tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
2491                                                                                                            (void *) &relid,
2492                                                                                                            HASH_FIND, NULL);
2493                 if (tabentry)
2494                         return tabentry;
2495         }
2496
2497         return NULL;
2498 }
2499
2500
2501 /* ----------
2502  * pgstat_fetch_stat_funcentry() -
2503  *
2504  *      Support function for the SQL-callable pgstat* functions. Returns
2505  *      the collected statistics for one function or NULL.
2506  * ----------
2507  */
2508 PgStat_StatFuncEntry *
2509 pgstat_fetch_stat_funcentry(Oid func_id)
2510 {
2511         PgStat_StatDBEntry *dbentry;
2512         PgStat_StatFuncEntry *funcentry = NULL;
2513
2514         /* load the stats file if needed */
2515         backend_read_statsfile();
2516
2517         /* Lookup our database, then find the requested function.  */
2518         dbentry = pgstat_fetch_stat_dbentry(MyDatabaseId);
2519         if (dbentry != NULL && dbentry->functions != NULL)
2520         {
2521                 funcentry = (PgStat_StatFuncEntry *) hash_search(dbentry->functions,
2522                                                                                                                  (void *) &func_id,
2523                                                                                                                  HASH_FIND, NULL);
2524         }
2525
2526         return funcentry;
2527 }
2528
2529
2530 /* ----------
2531  * pgstat_fetch_stat_beentry() -
2532  *
2533  *      Support function for the SQL-callable pgstat* functions. Returns
2534  *      our local copy of the current-activity entry for one backend.
2535  *
2536  *      NB: caller is responsible for a check if the user is permitted to see
2537  *      this info (especially the querystring).
2538  * ----------
2539  */
2540 PgBackendStatus *
2541 pgstat_fetch_stat_beentry(int beid)
2542 {
2543         pgstat_read_current_status();
2544
2545         if (beid < 1 || beid > localNumBackends)
2546                 return NULL;
2547
2548         return &localBackendStatusTable[beid - 1].backendStatus;
2549 }
2550
2551
2552 /* ----------
2553  * pgstat_fetch_stat_local_beentry() -
2554  *
2555  *      Like pgstat_fetch_stat_beentry() but with locally computed additions (like
2556  *      xid and xmin values of the backend)
2557  *
2558  *      NB: caller is responsible for a check if the user is permitted to see
2559  *      this info (especially the querystring).
2560  * ----------
2561  */
2562 LocalPgBackendStatus *
2563 pgstat_fetch_stat_local_beentry(int beid)
2564 {
2565         pgstat_read_current_status();
2566
2567         if (beid < 1 || beid > localNumBackends)
2568                 return NULL;
2569
2570         return &localBackendStatusTable[beid - 1];
2571 }
2572
2573
2574 /* ----------
2575  * pgstat_fetch_stat_numbackends() -
2576  *
2577  *      Support function for the SQL-callable pgstat* functions. Returns
2578  *      the maximum current backend id.
2579  * ----------
2580  */
2581 int
2582 pgstat_fetch_stat_numbackends(void)
2583 {
2584         pgstat_read_current_status();
2585
2586         return localNumBackends;
2587 }
2588
2589 /*
2590  * ---------
2591  * pgstat_fetch_stat_archiver() -
2592  *
2593  *      Support function for the SQL-callable pgstat* functions. Returns
2594  *      a pointer to the archiver statistics struct.
2595  * ---------
2596  */
2597 PgStat_ArchiverStats *
2598 pgstat_fetch_stat_archiver(void)
2599 {
2600         backend_read_statsfile();
2601
2602         return &archiverStats;
2603 }
2604
2605
2606 /*
2607  * ---------
2608  * pgstat_fetch_global() -
2609  *
2610  *      Support function for the SQL-callable pgstat* functions. Returns
2611  *      a pointer to the global statistics struct.
2612  * ---------
2613  */
2614 PgStat_GlobalStats *
2615 pgstat_fetch_global(void)
2616 {
2617         backend_read_statsfile();
2618
2619         return &globalStats;
2620 }
2621
2622
2623 /* ------------------------------------------------------------
2624  * Functions for management of the shared-memory PgBackendStatus array
2625  * ------------------------------------------------------------
2626  */
2627
2628 static PgBackendStatus *BackendStatusArray = NULL;
2629 static PgBackendStatus *MyBEEntry = NULL;
2630 static char *BackendAppnameBuffer = NULL;
2631 static char *BackendClientHostnameBuffer = NULL;
2632 static char *BackendActivityBuffer = NULL;
2633 static Size BackendActivityBufferSize = 0;
2634 #ifdef USE_SSL
2635 static PgBackendSSLStatus *BackendSslStatusBuffer = NULL;
2636 #endif
2637 #ifdef ENABLE_GSS
2638 static PgBackendGSSStatus *BackendGssStatusBuffer = NULL;
2639 #endif
2640
2641
2642 /*
2643  * Report shared-memory space needed by CreateSharedBackendStatus.
2644  */
2645 Size
2646 BackendStatusShmemSize(void)
2647 {
2648         Size            size;
2649
2650         /* BackendStatusArray: */
2651         size = mul_size(sizeof(PgBackendStatus), NumBackendStatSlots);
2652         /* BackendAppnameBuffer: */
2653         size = add_size(size,
2654                                         mul_size(NAMEDATALEN, NumBackendStatSlots));
2655         /* BackendClientHostnameBuffer: */
2656         size = add_size(size,
2657                                         mul_size(NAMEDATALEN, NumBackendStatSlots));
2658         /* BackendActivityBuffer: */
2659         size = add_size(size,
2660                                         mul_size(pgstat_track_activity_query_size, NumBackendStatSlots));
2661 #ifdef USE_SSL
2662         /* BackendSslStatusBuffer: */
2663         size = add_size(size,
2664                                         mul_size(sizeof(PgBackendSSLStatus), NumBackendStatSlots));
2665 #endif
2666         return size;
2667 }
2668
2669 /*
2670  * Initialize the shared status array and several string buffers
2671  * during postmaster startup.
2672  */
2673 void
2674 CreateSharedBackendStatus(void)
2675 {
2676         Size            size;
2677         bool            found;
2678         int                     i;
2679         char       *buffer;
2680
2681         /* Create or attach to the shared array */
2682         size = mul_size(sizeof(PgBackendStatus), NumBackendStatSlots);
2683         BackendStatusArray = (PgBackendStatus *)
2684                 ShmemInitStruct("Backend Status Array", size, &found);
2685
2686         if (!found)
2687         {
2688                 /*
2689                  * We're the first - initialize.
2690                  */
2691                 MemSet(BackendStatusArray, 0, size);
2692         }
2693
2694         /* Create or attach to the shared appname buffer */
2695         size = mul_size(NAMEDATALEN, NumBackendStatSlots);
2696         BackendAppnameBuffer = (char *)
2697                 ShmemInitStruct("Backend Application Name Buffer", size, &found);
2698
2699         if (!found)
2700         {
2701                 MemSet(BackendAppnameBuffer, 0, size);
2702
2703                 /* Initialize st_appname pointers. */
2704                 buffer = BackendAppnameBuffer;
2705                 for (i = 0; i < NumBackendStatSlots; i++)
2706                 {
2707                         BackendStatusArray[i].st_appname = buffer;
2708                         buffer += NAMEDATALEN;
2709                 }
2710         }
2711
2712         /* Create or attach to the shared client hostname buffer */
2713         size = mul_size(NAMEDATALEN, NumBackendStatSlots);
2714         BackendClientHostnameBuffer = (char *)
2715                 ShmemInitStruct("Backend Client Host Name Buffer", size, &found);
2716
2717         if (!found)
2718         {
2719                 MemSet(BackendClientHostnameBuffer, 0, size);
2720
2721                 /* Initialize st_clienthostname pointers. */
2722                 buffer = BackendClientHostnameBuffer;
2723                 for (i = 0; i < NumBackendStatSlots; i++)
2724                 {
2725                         BackendStatusArray[i].st_clienthostname = buffer;
2726                         buffer += NAMEDATALEN;
2727                 }
2728         }
2729
2730         /* Create or attach to the shared activity buffer */
2731         BackendActivityBufferSize = mul_size(pgstat_track_activity_query_size,
2732                                                                                  NumBackendStatSlots);
2733         BackendActivityBuffer = (char *)
2734                 ShmemInitStruct("Backend Activity Buffer",
2735                                                 BackendActivityBufferSize,
2736                                                 &found);
2737
2738         if (!found)
2739         {
2740                 MemSet(BackendActivityBuffer, 0, BackendActivityBufferSize);
2741
2742                 /* Initialize st_activity pointers. */
2743                 buffer = BackendActivityBuffer;
2744                 for (i = 0; i < NumBackendStatSlots; i++)
2745                 {
2746                         BackendStatusArray[i].st_activity_raw = buffer;
2747                         buffer += pgstat_track_activity_query_size;
2748                 }
2749         }
2750
2751 #ifdef USE_SSL
2752         /* Create or attach to the shared SSL status buffer */
2753         size = mul_size(sizeof(PgBackendSSLStatus), NumBackendStatSlots);
2754         BackendSslStatusBuffer = (PgBackendSSLStatus *)
2755                 ShmemInitStruct("Backend SSL Status Buffer", size, &found);
2756
2757         if (!found)
2758         {
2759                 PgBackendSSLStatus *ptr;
2760
2761                 MemSet(BackendSslStatusBuffer, 0, size);
2762
2763                 /* Initialize st_sslstatus pointers. */
2764                 ptr = BackendSslStatusBuffer;
2765                 for (i = 0; i < NumBackendStatSlots; i++)
2766                 {
2767                         BackendStatusArray[i].st_sslstatus = ptr;
2768                         ptr++;
2769                 }
2770         }
2771 #endif
2772
2773 #ifdef ENABLE_GSS
2774         /* Create or attach to the shared GSSAPI status buffer */
2775         size = mul_size(sizeof(PgBackendGSSStatus), NumBackendStatSlots);
2776         BackendGssStatusBuffer = (PgBackendGSSStatus *)
2777                 ShmemInitStruct("Backend GSS Status Buffer", size, &found);
2778
2779         if (!found)
2780         {
2781                 PgBackendGSSStatus *ptr;
2782
2783                 MemSet(BackendGssStatusBuffer, 0, size);
2784
2785                 /* Initialize st_gssstatus pointers. */
2786                 ptr = BackendGssStatusBuffer;
2787                 for (i = 0; i < NumBackendStatSlots; i++)
2788                 {
2789                         BackendStatusArray[i].st_gssstatus = ptr;
2790                         ptr++;
2791                 }
2792         }
2793 #endif
2794 }
2795
2796
2797 /* ----------
2798  * pgstat_initialize() -
2799  *
2800  *      Initialize pgstats state, and set up our on-proc-exit hook.
2801  *      Called from InitPostgres and AuxiliaryProcessMain. For auxiliary process,
2802  *      MyBackendId is invalid. Otherwise, MyBackendId must be set,
2803  *      but we must not have started any transaction yet (since the
2804  *      exit hook must run after the last transaction exit).
2805  *      NOTE: MyDatabaseId isn't set yet; so the shutdown hook has to be careful.
2806  * ----------
2807  */
2808 void
2809 pgstat_initialize(void)
2810 {
2811         /* Initialize MyBEEntry */
2812         if (MyBackendId != InvalidBackendId)
2813         {
2814                 Assert(MyBackendId >= 1 && MyBackendId <= MaxBackends);
2815                 MyBEEntry = &BackendStatusArray[MyBackendId - 1];
2816         }
2817         else
2818         {
2819                 /* Must be an auxiliary process */
2820                 Assert(MyAuxProcType != NotAnAuxProcess);
2821
2822                 /*
2823                  * Assign the MyBEEntry for an auxiliary process.  Since it doesn't
2824                  * have a BackendId, the slot is statically allocated based on the
2825                  * auxiliary process type (MyAuxProcType).  Backends use slots indexed
2826                  * in the range from 1 to MaxBackends (inclusive), so we use
2827                  * MaxBackends + AuxBackendType + 1 as the index of the slot for an
2828                  * auxiliary process.
2829                  */
2830                 MyBEEntry = &BackendStatusArray[MaxBackends + MyAuxProcType];
2831         }
2832
2833         /* Set up a process-exit hook to clean up */
2834         on_shmem_exit(pgstat_beshutdown_hook, 0);
2835 }
2836
2837 /* ----------
2838  * pgstat_bestart() -
2839  *
2840  *      Initialize this backend's entry in the PgBackendStatus array.
2841  *      Called from InitPostgres.
2842  *
2843  *      Apart from auxiliary processes, MyBackendId, MyDatabaseId,
2844  *      session userid, and application_name must be set for a
2845  *      backend (hence, this cannot be combined with pgstat_initialize).
2846  * ----------
2847  */
2848 void
2849 pgstat_bestart(void)
2850 {
2851         SockAddr        clientaddr;
2852         volatile PgBackendStatus *beentry;
2853
2854         /*
2855          * To minimize the time spent modifying the PgBackendStatus entry, fetch
2856          * all the needed data first.
2857          */
2858
2859         /*
2860          * We may not have a MyProcPort (eg, if this is the autovacuum process).
2861          * If so, use all-zeroes client address, which is dealt with specially in
2862          * pg_stat_get_backend_client_addr and pg_stat_get_backend_client_port.
2863          */
2864         if (MyProcPort)
2865                 memcpy(&clientaddr, &MyProcPort->raddr, sizeof(clientaddr));
2866         else
2867                 MemSet(&clientaddr, 0, sizeof(clientaddr));
2868
2869         /*
2870          * Initialize my status entry, following the protocol of bumping
2871          * st_changecount before and after; and make sure it's even afterwards. We
2872          * use a volatile pointer here to ensure the compiler doesn't try to get
2873          * cute.
2874          */
2875         beentry = MyBEEntry;
2876
2877         /* pgstats state must be initialized from pgstat_initialize() */
2878         Assert(beentry != NULL);
2879
2880         if (MyBackendId != InvalidBackendId)
2881         {
2882                 if (IsAutoVacuumLauncherProcess())
2883                 {
2884                         /* Autovacuum Launcher */
2885                         beentry->st_backendType = B_AUTOVAC_LAUNCHER;
2886                 }
2887                 else if (IsAutoVacuumWorkerProcess())
2888                 {
2889                         /* Autovacuum Worker */
2890                         beentry->st_backendType = B_AUTOVAC_WORKER;
2891                 }
2892                 else if (am_walsender)
2893                 {
2894                         /* Wal sender */
2895                         beentry->st_backendType = B_WAL_SENDER;
2896                 }
2897                 else if (IsBackgroundWorker)
2898                 {
2899                         /* bgworker */
2900                         beentry->st_backendType = B_BG_WORKER;
2901                 }
2902                 else
2903                 {
2904                         /* client-backend */
2905                         beentry->st_backendType = B_BACKEND;
2906                 }
2907         }
2908         else
2909         {
2910                 /* Must be an auxiliary process */
2911                 Assert(MyAuxProcType != NotAnAuxProcess);
2912                 switch (MyAuxProcType)
2913                 {
2914                         case StartupProcess:
2915                                 beentry->st_backendType = B_STARTUP;
2916                                 break;
2917                         case BgWriterProcess:
2918                                 beentry->st_backendType = B_BG_WRITER;
2919                                 break;
2920                         case CheckpointerProcess:
2921                                 beentry->st_backendType = B_CHECKPOINTER;
2922                                 break;
2923                         case WalWriterProcess:
2924                                 beentry->st_backendType = B_WAL_WRITER;
2925                                 break;
2926                         case WalReceiverProcess:
2927                                 beentry->st_backendType = B_WAL_RECEIVER;
2928                                 break;
2929                         default:
2930                                 elog(FATAL, "unrecognized process type: %d",
2931                                          (int) MyAuxProcType);
2932                                 proc_exit(1);
2933                 }
2934         }
2935
2936         do
2937         {
2938                 pgstat_increment_changecount_before(beentry);
2939         } while ((beentry->st_changecount & 1) == 0);
2940
2941         beentry->st_procpid = MyProcPid;
2942         beentry->st_proc_start_timestamp = MyStartTimestamp;
2943         beentry->st_activity_start_timestamp = 0;
2944         beentry->st_state_start_timestamp = 0;
2945         beentry->st_xact_start_timestamp = 0;
2946         beentry->st_databaseid = MyDatabaseId;
2947
2948         /* We have userid for client-backends, wal-sender and bgworker processes */
2949         if (beentry->st_backendType == B_BACKEND
2950                 || beentry->st_backendType == B_WAL_SENDER
2951                 || beentry->st_backendType == B_BG_WORKER)
2952                 beentry->st_userid = GetSessionUserId();
2953         else
2954                 beentry->st_userid = InvalidOid;
2955
2956         beentry->st_clientaddr = clientaddr;
2957         if (MyProcPort && MyProcPort->remote_hostname)
2958                 strlcpy(beentry->st_clienthostname, MyProcPort->remote_hostname,
2959                                 NAMEDATALEN);
2960         else
2961                 beentry->st_clienthostname[0] = '\0';
2962 #ifdef USE_SSL
2963         if (MyProcPort && MyProcPort->ssl != NULL)
2964         {
2965                 beentry->st_ssl = true;
2966                 beentry->st_sslstatus->ssl_bits = be_tls_get_cipher_bits(MyProcPort);
2967                 beentry->st_sslstatus->ssl_compression = be_tls_get_compression(MyProcPort);
2968                 strlcpy(beentry->st_sslstatus->ssl_version, be_tls_get_version(MyProcPort), NAMEDATALEN);
2969                 strlcpy(beentry->st_sslstatus->ssl_cipher, be_tls_get_cipher(MyProcPort), NAMEDATALEN);
2970                 be_tls_get_peer_subject_name(MyProcPort, beentry->st_sslstatus->ssl_client_dn, NAMEDATALEN);
2971                 be_tls_get_peer_serial(MyProcPort, beentry->st_sslstatus->ssl_client_serial, NAMEDATALEN);
2972                 be_tls_get_peer_issuer_name(MyProcPort, beentry->st_sslstatus->ssl_issuer_dn, NAMEDATALEN);
2973         }
2974         else
2975         {
2976                 beentry->st_ssl = false;
2977         }
2978 #else
2979         beentry->st_ssl = false;
2980 #endif
2981
2982 #ifdef ENABLE_GSS
2983         if (MyProcPort && MyProcPort->gss != NULL)
2984         {
2985                 beentry->st_gss = true;
2986                 beentry->st_gssstatus->gss_auth = be_gssapi_get_auth(MyProcPort);
2987                 beentry->st_gssstatus->gss_enc = be_gssapi_get_enc(MyProcPort);
2988
2989                 if (beentry->st_gssstatus->gss_auth)
2990                         strlcpy(beentry->st_gssstatus->gss_princ, be_gssapi_get_princ(MyProcPort), NAMEDATALEN);
2991         }
2992         else
2993         {
2994                 beentry->st_gss = false;
2995         }
2996 #else
2997         beentry->st_gss = false;
2998 #endif
2999         beentry->st_state = STATE_UNDEFINED;
3000         beentry->st_appname[0] = '\0';
3001         beentry->st_activity_raw[0] = '\0';
3002         /* Also make sure the last byte in each string area is always 0 */
3003         beentry->st_clienthostname[NAMEDATALEN - 1] = '\0';
3004         beentry->st_appname[NAMEDATALEN - 1] = '\0';
3005         beentry->st_activity_raw[pgstat_track_activity_query_size - 1] = '\0';
3006         beentry->st_progress_command = PROGRESS_COMMAND_INVALID;
3007         beentry->st_progress_command_target = InvalidOid;
3008
3009         /*
3010          * we don't zero st_progress_param here to save cycles; nobody should
3011          * examine it until st_progress_command has been set to something other
3012          * than PROGRESS_COMMAND_INVALID
3013          */
3014
3015         pgstat_increment_changecount_after(beentry);
3016
3017         /* Update app name to current GUC setting */
3018         if (application_name)
3019                 pgstat_report_appname(application_name);
3020 }
3021
3022 /*
3023  * Shut down a single backend's statistics reporting at process exit.
3024  *
3025  * Flush any remaining statistics counts out to the collector.
3026  * Without this, operations triggered during backend exit (such as
3027  * temp table deletions) won't be counted.
3028  *
3029  * Lastly, clear out our entry in the PgBackendStatus array.
3030  */
3031 static void
3032 pgstat_beshutdown_hook(int code, Datum arg)
3033 {
3034         volatile PgBackendStatus *beentry = MyBEEntry;
3035
3036         /*
3037          * If we got as far as discovering our own database ID, we can report what
3038          * we did to the collector.  Otherwise, we'd be sending an invalid
3039          * database ID, so forget it.  (This means that accesses to pg_database
3040          * during failed backend starts might never get counted.)
3041          */
3042         if (OidIsValid(MyDatabaseId))
3043                 pgstat_report_stat(true);
3044
3045         /*
3046          * Clear my status entry, following the protocol of bumping st_changecount
3047          * before and after.  We use a volatile pointer here to ensure the
3048          * compiler doesn't try to get cute.
3049          */
3050         pgstat_increment_changecount_before(beentry);
3051
3052         beentry->st_procpid = 0;        /* mark invalid */
3053
3054         pgstat_increment_changecount_after(beentry);
3055 }
3056
3057
3058 /* ----------
3059  * pgstat_report_activity() -
3060  *
3061  *      Called from tcop/postgres.c to report what the backend is actually doing
3062  *      (but note cmd_str can be NULL for certain cases).
3063  *
3064  * All updates of the status entry follow the protocol of bumping
3065  * st_changecount before and after.  We use a volatile pointer here to
3066  * ensure the compiler doesn't try to get cute.
3067  * ----------
3068  */
3069 void
3070 pgstat_report_activity(BackendState state, const char *cmd_str)
3071 {
3072         volatile PgBackendStatus *beentry = MyBEEntry;
3073         TimestampTz start_timestamp;
3074         TimestampTz current_timestamp;
3075         int                     len = 0;
3076
3077         TRACE_POSTGRESQL_STATEMENT_STATUS(cmd_str);
3078
3079         if (!beentry)
3080                 return;
3081
3082         if (!pgstat_track_activities)
3083         {
3084                 if (beentry->st_state != STATE_DISABLED)
3085                 {
3086                         volatile PGPROC *proc = MyProc;
3087
3088                         /*
3089                          * track_activities is disabled, but we last reported a
3090                          * non-disabled state.  As our final update, change the state and
3091                          * clear fields we will not be updating anymore.
3092                          */
3093                         pgstat_increment_changecount_before(beentry);
3094                         beentry->st_state = STATE_DISABLED;
3095                         beentry->st_state_start_timestamp = 0;
3096                         beentry->st_activity_raw[0] = '\0';
3097                         beentry->st_activity_start_timestamp = 0;
3098                         /* st_xact_start_timestamp and wait_event_info are also disabled */
3099                         beentry->st_xact_start_timestamp = 0;
3100                         proc->wait_event_info = 0;
3101                         pgstat_increment_changecount_after(beentry);
3102                 }
3103                 return;
3104         }
3105
3106         /*
3107          * To minimize the time spent modifying the entry, fetch all the needed
3108          * data first.
3109          */
3110         start_timestamp = GetCurrentStatementStartTimestamp();
3111         if (cmd_str != NULL)
3112         {
3113                 /*
3114                  * Compute length of to-be-stored string unaware of multi-byte
3115                  * characters. For speed reasons that'll get corrected on read, rather
3116                  * than computed every write.
3117                  */
3118                 len = Min(strlen(cmd_str), pgstat_track_activity_query_size - 1);
3119         }
3120         current_timestamp = GetCurrentTimestamp();
3121
3122         /*
3123          * Now update the status entry
3124          */
3125         pgstat_increment_changecount_before(beentry);
3126
3127         beentry->st_state = state;
3128         beentry->st_state_start_timestamp = current_timestamp;
3129
3130         if (cmd_str != NULL)
3131         {
3132                 memcpy((char *) beentry->st_activity_raw, cmd_str, len);
3133                 beentry->st_activity_raw[len] = '\0';
3134                 beentry->st_activity_start_timestamp = start_timestamp;
3135         }
3136
3137         pgstat_increment_changecount_after(beentry);
3138 }
3139
3140 /*-----------
3141  * pgstat_progress_start_command() -
3142  *
3143  * Set st_progress_command (and st_progress_command_target) in own backend
3144  * entry.  Also, zero-initialize st_progress_param array.
3145  *-----------
3146  */
3147 void
3148 pgstat_progress_start_command(ProgressCommandType cmdtype, Oid relid)
3149 {
3150         volatile PgBackendStatus *beentry = MyBEEntry;
3151
3152         if (!beentry || !pgstat_track_activities)
3153                 return;
3154
3155         pgstat_increment_changecount_before(beentry);
3156         beentry->st_progress_command = cmdtype;
3157         beentry->st_progress_command_target = relid;
3158         MemSet(&beentry->st_progress_param, 0, sizeof(beentry->st_progress_param));
3159         pgstat_increment_changecount_after(beentry);
3160 }
3161
3162 /*-----------
3163  * pgstat_progress_update_param() -
3164  *
3165  * Update index'th member in st_progress_param[] of own backend entry.
3166  *-----------
3167  */
3168 void
3169 pgstat_progress_update_param(int index, int64 val)
3170 {
3171         volatile PgBackendStatus *beentry = MyBEEntry;
3172
3173         Assert(index >= 0 && index < PGSTAT_NUM_PROGRESS_PARAM);
3174
3175         if (!beentry || !pgstat_track_activities)
3176                 return;
3177
3178         pgstat_increment_changecount_before(beentry);
3179         beentry->st_progress_param[index] = val;
3180         pgstat_increment_changecount_after(beentry);
3181 }
3182
3183 /*-----------
3184  * pgstat_progress_update_multi_param() -
3185  *
3186  * Update multiple members in st_progress_param[] of own backend entry.
3187  * This is atomic; readers won't see intermediate states.
3188  *-----------
3189  */
3190 void
3191 pgstat_progress_update_multi_param(int nparam, const int *index,
3192                                                                    const int64 *val)
3193 {
3194         volatile PgBackendStatus *beentry = MyBEEntry;
3195         int                     i;
3196
3197         if (!beentry || !pgstat_track_activities || nparam == 0)
3198                 return;
3199
3200         pgstat_increment_changecount_before(beentry);
3201
3202         for (i = 0; i < nparam; ++i)
3203         {
3204                 Assert(index[i] >= 0 && index[i] < PGSTAT_NUM_PROGRESS_PARAM);
3205
3206                 beentry->st_progress_param[index[i]] = val[i];
3207         }
3208
3209         pgstat_increment_changecount_after(beentry);
3210 }
3211
3212 /*-----------
3213  * pgstat_progress_end_command() -
3214  *
3215  * Reset st_progress_command (and st_progress_command_target) in own backend
3216  * entry.  This signals the end of the command.
3217  *-----------
3218  */
3219 void
3220 pgstat_progress_end_command(void)
3221 {
3222         volatile PgBackendStatus *beentry = MyBEEntry;
3223
3224         if (!beentry)
3225                 return;
3226         if (!pgstat_track_activities
3227                 && beentry->st_progress_command == PROGRESS_COMMAND_INVALID)
3228                 return;
3229
3230         pgstat_increment_changecount_before(beentry);
3231         beentry->st_progress_command = PROGRESS_COMMAND_INVALID;
3232         beentry->st_progress_command_target = InvalidOid;
3233         pgstat_increment_changecount_after(beentry);
3234 }
3235
3236 /* ----------
3237  * pgstat_report_appname() -
3238  *
3239  *      Called to update our application name.
3240  * ----------
3241  */
3242 void
3243 pgstat_report_appname(const char *appname)
3244 {
3245         volatile PgBackendStatus *beentry = MyBEEntry;
3246         int                     len;
3247
3248         if (!beentry)
3249                 return;
3250
3251         /* This should be unnecessary if GUC did its job, but be safe */
3252         len = pg_mbcliplen(appname, strlen(appname), NAMEDATALEN - 1);
3253
3254         /*
3255          * Update my status entry, following the protocol of bumping
3256          * st_changecount before and after.  We use a volatile pointer here to
3257          * ensure the compiler doesn't try to get cute.
3258          */
3259         pgstat_increment_changecount_before(beentry);
3260
3261         memcpy((char *) beentry->st_appname, appname, len);
3262         beentry->st_appname[len] = '\0';
3263
3264         pgstat_increment_changecount_after(beentry);
3265 }
3266
3267 /*
3268  * Report current transaction start timestamp as the specified value.
3269  * Zero means there is no active transaction.
3270  */
3271 void
3272 pgstat_report_xact_timestamp(TimestampTz tstamp)
3273 {
3274         volatile PgBackendStatus *beentry = MyBEEntry;
3275
3276         if (!pgstat_track_activities || !beentry)
3277                 return;
3278
3279         /*
3280          * Update my status entry, following the protocol of bumping
3281          * st_changecount before and after.  We use a volatile pointer here to
3282          * ensure the compiler doesn't try to get cute.
3283          */
3284         pgstat_increment_changecount_before(beentry);
3285         beentry->st_xact_start_timestamp = tstamp;
3286         pgstat_increment_changecount_after(beentry);
3287 }
3288
3289 /* ----------
3290  * pgstat_read_current_status() -
3291  *
3292  *      Copy the current contents of the PgBackendStatus array to local memory,
3293  *      if not already done in this transaction.
3294  * ----------
3295  */
3296 static void
3297 pgstat_read_current_status(void)
3298 {
3299         volatile PgBackendStatus *beentry;
3300         LocalPgBackendStatus *localtable;
3301         LocalPgBackendStatus *localentry;
3302         char       *localappname,
3303                            *localclienthostname,
3304                            *localactivity;
3305 #ifdef USE_SSL
3306         PgBackendSSLStatus *localsslstatus;
3307 #endif
3308         int                     i;
3309
3310         Assert(!pgStatRunningInCollector);
3311         if (localBackendStatusTable)
3312                 return;                                 /* already done */
3313
3314         pgstat_setup_memcxt();
3315
3316         localtable = (LocalPgBackendStatus *)
3317                 MemoryContextAlloc(pgStatLocalContext,
3318                                                    sizeof(LocalPgBackendStatus) * NumBackendStatSlots);
3319         localappname = (char *)
3320                 MemoryContextAlloc(pgStatLocalContext,
3321                                                    NAMEDATALEN * NumBackendStatSlots);
3322         localclienthostname = (char *)
3323                 MemoryContextAlloc(pgStatLocalContext,
3324                                                    NAMEDATALEN * NumBackendStatSlots);
3325         localactivity = (char *)
3326                 MemoryContextAlloc(pgStatLocalContext,
3327                                                    pgstat_track_activity_query_size * NumBackendStatSlots);
3328 #ifdef USE_SSL
3329         localsslstatus = (PgBackendSSLStatus *)
3330                 MemoryContextAlloc(pgStatLocalContext,
3331                                                    sizeof(PgBackendSSLStatus) * NumBackendStatSlots);
3332 #endif
3333
3334         localNumBackends = 0;
3335
3336         beentry = BackendStatusArray;
3337         localentry = localtable;
3338         for (i = 1; i <= NumBackendStatSlots; i++)
3339         {
3340                 /*
3341                  * Follow the protocol of retrying if st_changecount changes while we
3342                  * copy the entry, or if it's odd.  (The check for odd is needed to
3343                  * cover the case where we are able to completely copy the entry while
3344                  * the source backend is between increment steps.)      We use a volatile
3345                  * pointer here to ensure the compiler doesn't try to get cute.
3346                  */
3347                 for (;;)
3348                 {
3349                         int                     before_changecount;
3350                         int                     after_changecount;
3351
3352                         pgstat_save_changecount_before(beentry, before_changecount);
3353
3354                         localentry->backendStatus.st_procpid = beentry->st_procpid;
3355                         if (localentry->backendStatus.st_procpid > 0)
3356                         {
3357                                 memcpy(&localentry->backendStatus, unvolatize(PgBackendStatus *, beentry), sizeof(PgBackendStatus));
3358
3359                                 /*
3360                                  * strcpy is safe even if the string is modified concurrently,
3361                                  * because there's always a \0 at the end of the buffer.
3362                                  */
3363                                 strcpy(localappname, (char *) beentry->st_appname);
3364                                 localentry->backendStatus.st_appname = localappname;
3365                                 strcpy(localclienthostname, (char *) beentry->st_clienthostname);
3366                                 localentry->backendStatus.st_clienthostname = localclienthostname;
3367                                 strcpy(localactivity, (char *) beentry->st_activity_raw);
3368                                 localentry->backendStatus.st_activity_raw = localactivity;
3369                                 localentry->backendStatus.st_ssl = beentry->st_ssl;
3370 #ifdef USE_SSL
3371                                 if (beentry->st_ssl)
3372                                 {
3373                                         memcpy(localsslstatus, beentry->st_sslstatus, sizeof(PgBackendSSLStatus));
3374                                         localentry->backendStatus.st_sslstatus = localsslstatus;
3375                                 }
3376 #endif
3377                         }
3378
3379                         pgstat_save_changecount_after(beentry, after_changecount);
3380                         if (before_changecount == after_changecount &&
3381                                 (before_changecount & 1) == 0)
3382                                 break;
3383
3384                         /* Make sure we can break out of loop if stuck... */
3385                         CHECK_FOR_INTERRUPTS();
3386                 }
3387
3388                 beentry++;
3389                 /* Only valid entries get included into the local array */
3390                 if (localentry->backendStatus.st_procpid > 0)
3391                 {
3392                         BackendIdGetTransactionIds(i,
3393                                                                            &localentry->backend_xid,
3394                                                                            &localentry->backend_xmin);
3395
3396                         localentry++;
3397                         localappname += NAMEDATALEN;
3398                         localclienthostname += NAMEDATALEN;
3399                         localactivity += pgstat_track_activity_query_size;
3400 #ifdef USE_SSL
3401                         localsslstatus++;
3402 #endif
3403                         localNumBackends++;
3404                 }
3405         }
3406
3407         /* Set the pointer only after completion of a valid table */
3408         localBackendStatusTable = localtable;
3409 }
3410
3411 /* ----------
3412  * pgstat_get_wait_event_type() -
3413  *
3414  *      Return a string representing the current wait event type, backend is
3415  *      waiting on.
3416  */
3417 const char *
3418 pgstat_get_wait_event_type(uint32 wait_event_info)
3419 {
3420         uint32          classId;
3421         const char *event_type;
3422
3423         /* report process as not waiting. */
3424         if (wait_event_info == 0)
3425                 return NULL;
3426
3427         classId = wait_event_info & 0xFF000000;
3428
3429         switch (classId)
3430         {
3431                 case PG_WAIT_LWLOCK:
3432                         event_type = "LWLock";
3433                         break;
3434                 case PG_WAIT_LOCK:
3435                         event_type = "Lock";
3436                         break;
3437                 case PG_WAIT_BUFFER_PIN:
3438                         event_type = "BufferPin";
3439                         break;
3440                 case PG_WAIT_ACTIVITY:
3441                         event_type = "Activity";
3442                         break;
3443                 case PG_WAIT_CLIENT:
3444                         event_type = "Client";
3445                         break;
3446                 case PG_WAIT_EXTENSION:
3447                         event_type = "Extension";
3448                         break;
3449                 case PG_WAIT_IPC:
3450                         event_type = "IPC";
3451                         break;
3452                 case PG_WAIT_TIMEOUT:
3453                         event_type = "Timeout";
3454                         break;
3455                 case PG_WAIT_IO:
3456                         event_type = "IO";
3457                         break;
3458                 default:
3459                         event_type = "???";
3460                         break;
3461         }
3462
3463         return event_type;
3464 }
3465
3466 /* ----------
3467  * pgstat_get_wait_event() -
3468  *
3469  *      Return a string representing the current wait event, backend is
3470  *      waiting on.
3471  */
3472 const char *
3473 pgstat_get_wait_event(uint32 wait_event_info)
3474 {
3475         uint32          classId;
3476         uint16          eventId;
3477         const char *event_name;
3478
3479         /* report process as not waiting. */
3480         if (wait_event_info == 0)
3481                 return NULL;
3482
3483         classId = wait_event_info & 0xFF000000;
3484         eventId = wait_event_info & 0x0000FFFF;
3485
3486         switch (classId)
3487         {
3488                 case PG_WAIT_LWLOCK:
3489                         event_name = GetLWLockIdentifier(classId, eventId);
3490                         break;
3491                 case PG_WAIT_LOCK:
3492                         event_name = GetLockNameFromTagType(eventId);
3493                         break;
3494                 case PG_WAIT_BUFFER_PIN:
3495                         event_name = "BufferPin";
3496                         break;
3497                 case PG_WAIT_ACTIVITY:
3498                         {
3499                                 WaitEventActivity w = (WaitEventActivity) wait_event_info;
3500
3501                                 event_name = pgstat_get_wait_activity(w);
3502                                 break;
3503                         }
3504                 case PG_WAIT_CLIENT:
3505                         {
3506                                 WaitEventClient w = (WaitEventClient) wait_event_info;
3507
3508                                 event_name = pgstat_get_wait_client(w);
3509                                 break;
3510                         }
3511                 case PG_WAIT_EXTENSION:
3512                         event_name = "Extension";
3513                         break;
3514                 case PG_WAIT_IPC:
3515                         {
3516                                 WaitEventIPC w = (WaitEventIPC) wait_event_info;
3517
3518                                 event_name = pgstat_get_wait_ipc(w);
3519                                 break;
3520                         }
3521                 case PG_WAIT_TIMEOUT:
3522                         {
3523                                 WaitEventTimeout w = (WaitEventTimeout) wait_event_info;
3524
3525                                 event_name = pgstat_get_wait_timeout(w);
3526                                 break;
3527                         }
3528                 case PG_WAIT_IO:
3529                         {
3530                                 WaitEventIO w = (WaitEventIO) wait_event_info;
3531
3532                                 event_name = pgstat_get_wait_io(w);
3533                                 break;
3534                         }
3535                 default:
3536                         event_name = "unknown wait event";
3537                         break;
3538         }
3539
3540         return event_name;
3541 }
3542
3543 /* ----------
3544  * pgstat_get_wait_activity() -
3545  *
3546  * Convert WaitEventActivity to string.
3547  * ----------
3548  */
3549 static const char *
3550 pgstat_get_wait_activity(WaitEventActivity w)
3551 {
3552         const char *event_name = "unknown wait event";
3553
3554         switch (w)
3555         {
3556                 case WAIT_EVENT_ARCHIVER_MAIN:
3557                         event_name = "ArchiverMain";
3558                         break;
3559                 case WAIT_EVENT_AUTOVACUUM_MAIN:
3560                         event_name = "AutoVacuumMain";
3561                         break;
3562                 case WAIT_EVENT_BGWRITER_HIBERNATE:
3563                         event_name = "BgWriterHibernate";
3564                         break;
3565                 case WAIT_EVENT_BGWRITER_MAIN:
3566                         event_name = "BgWriterMain";
3567                         break;
3568                 case WAIT_EVENT_CHECKPOINTER_MAIN:
3569                         event_name = "CheckpointerMain";
3570                         break;
3571                 case WAIT_EVENT_LOGICAL_APPLY_MAIN:
3572                         event_name = "LogicalApplyMain";
3573                         break;
3574                 case WAIT_EVENT_LOGICAL_LAUNCHER_MAIN:
3575                         event_name = "LogicalLauncherMain";
3576                         break;
3577                 case WAIT_EVENT_PGSTAT_MAIN:
3578                         event_name = "PgStatMain";
3579                         break;
3580                 case WAIT_EVENT_RECOVERY_WAL_ALL:
3581                         event_name = "RecoveryWalAll";
3582                         break;
3583                 case WAIT_EVENT_RECOVERY_WAL_STREAM:
3584                         event_name = "RecoveryWalStream";
3585                         break;
3586                 case WAIT_EVENT_SYSLOGGER_MAIN:
3587                         event_name = "SysLoggerMain";
3588                         break;
3589                 case WAIT_EVENT_WAL_RECEIVER_MAIN:
3590                         event_name = "WalReceiverMain";
3591                         break;
3592                 case WAIT_EVENT_WAL_SENDER_MAIN:
3593                         event_name = "WalSenderMain";
3594                         break;
3595                 case WAIT_EVENT_WAL_WRITER_MAIN:
3596                         event_name = "WalWriterMain";
3597                         break;
3598                         /* no default case, so that compiler will warn */
3599         }
3600
3601         return event_name;
3602 }
3603
3604 /* ----------
3605  * pgstat_get_wait_client() -
3606  *
3607  * Convert WaitEventClient to string.
3608  * ----------
3609  */
3610 static const char *
3611 pgstat_get_wait_client(WaitEventClient w)
3612 {
3613         const char *event_name = "unknown wait event";
3614
3615         switch (w)
3616         {
3617                 case WAIT_EVENT_CLIENT_READ:
3618                         event_name = "ClientRead";
3619                         break;
3620                 case WAIT_EVENT_CLIENT_WRITE:
3621                         event_name = "ClientWrite";
3622                         break;
3623                 case WAIT_EVENT_LIBPQWALRECEIVER_CONNECT:
3624                         event_name = "LibPQWalReceiverConnect";
3625                         break;
3626                 case WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE:
3627                         event_name = "LibPQWalReceiverReceive";
3628                         break;
3629                 case WAIT_EVENT_SSL_OPEN_SERVER:
3630                         event_name = "SSLOpenServer";
3631                         break;
3632                 case WAIT_EVENT_WAL_RECEIVER_WAIT_START:
3633                         event_name = "WalReceiverWaitStart";
3634                         break;
3635                 case WAIT_EVENT_WAL_SENDER_WAIT_WAL:
3636                         event_name = "WalSenderWaitForWAL";
3637                         break;
3638                 case WAIT_EVENT_WAL_SENDER_WRITE_DATA:
3639                         event_name = "WalSenderWriteData";
3640                         break;
3641                 case WAIT_EVENT_GSS_OPEN_SERVER:
3642                         event_name = "GSSOpenServer";
3643                         break;
3644                         /* no default case, so that compiler will warn */
3645         }
3646
3647         return event_name;
3648 }
3649
3650 /* ----------
3651  * pgstat_get_wait_ipc() -
3652  *
3653  * Convert WaitEventIPC to string.
3654  * ----------
3655  */
3656 static const char *
3657 pgstat_get_wait_ipc(WaitEventIPC w)
3658 {
3659         const char *event_name = "unknown wait event";
3660
3661         switch (w)
3662         {
3663                 case WAIT_EVENT_BGWORKER_SHUTDOWN:
3664                         event_name = "BgWorkerShutdown";
3665                         break;
3666                 case WAIT_EVENT_BGWORKER_STARTUP:
3667                         event_name = "BgWorkerStartup";
3668                         break;
3669                 case WAIT_EVENT_BTREE_PAGE:
3670                         event_name = "BtreePage";
3671                         break;
3672                 case WAIT_EVENT_CHECKPOINT_DONE:
3673                         event_name = "CheckpointDone";
3674                         break;
3675                 case WAIT_EVENT_CHECKPOINT_START:
3676                         event_name = "CheckpointStart";
3677                         break;
3678                 case WAIT_EVENT_CLOG_GROUP_UPDATE:
3679                         event_name = "ClogGroupUpdate";
3680                         break;
3681                 case WAIT_EVENT_EXECUTE_GATHER:
3682                         event_name = "ExecuteGather";
3683                         break;
3684                 case WAIT_EVENT_HASH_BATCH_ALLOCATING:
3685                         event_name = "Hash/Batch/Allocating";
3686                         break;
3687                 case WAIT_EVENT_HASH_BATCH_ELECTING:
3688                         event_name = "Hash/Batch/Electing";
3689                         break;
3690                 case WAIT_EVENT_HASH_BATCH_LOADING:
3691                         event_name = "Hash/Batch/Loading";
3692                         break;
3693                 case WAIT_EVENT_HASH_BUILD_ALLOCATING:
3694                         event_name = "Hash/Build/Allocating";
3695                         break;
3696                 case WAIT_EVENT_HASH_BUILD_ELECTING:
3697                         event_name = "Hash/Build/Electing";
3698                         break;
3699                 case WAIT_EVENT_HASH_BUILD_HASHING_INNER:
3700                         event_name = "Hash/Build/HashingInner";
3701                         break;
3702                 case WAIT_EVENT_HASH_BUILD_HASHING_OUTER:
3703                         event_name = "Hash/Build/HashingOuter";
3704                         break;
3705                 case WAIT_EVENT_HASH_GROW_BATCHES_ALLOCATING:
3706                         event_name = "Hash/GrowBatches/Allocating";
3707                         break;
3708                 case WAIT_EVENT_HASH_GROW_BATCHES_DECIDING:
3709                         event_name = "Hash/GrowBatches/Deciding";
3710                         break;
3711                 case WAIT_EVENT_HASH_GROW_BATCHES_ELECTING:
3712                         event_name = "Hash/GrowBatches/Electing";
3713                         break;
3714                 case WAIT_EVENT_HASH_GROW_BATCHES_FINISHING:
3715                         event_name = "Hash/GrowBatches/Finishing";
3716                         break;
3717                 case WAIT_EVENT_HASH_GROW_BATCHES_REPARTITIONING:
3718                         event_name = "Hash/GrowBatches/Repartitioning";
3719                         break;
3720                 case WAIT_EVENT_HASH_GROW_BUCKETS_ALLOCATING:
3721                         event_name = "Hash/GrowBuckets/Allocating";
3722                         break;
3723                 case WAIT_EVENT_HASH_GROW_BUCKETS_ELECTING:
3724                         event_name = "Hash/GrowBuckets/Electing";
3725                         break;
3726                 case WAIT_EVENT_HASH_GROW_BUCKETS_REINSERTING:
3727                         event_name = "Hash/GrowBuckets/Reinserting";
3728                         break;
3729                 case WAIT_EVENT_LOGICAL_SYNC_DATA:
3730                         event_name = "LogicalSyncData";
3731                         break;
3732                 case WAIT_EVENT_LOGICAL_SYNC_STATE_CHANGE:
3733                         event_name = "LogicalSyncStateChange";
3734                         break;
3735                 case WAIT_EVENT_MQ_INTERNAL:
3736                         event_name = "MessageQueueInternal";
3737                         break;
3738                 case WAIT_EVENT_MQ_PUT_MESSAGE:
3739                         event_name = "MessageQueuePutMessage";
3740                         break;
3741                 case WAIT_EVENT_MQ_RECEIVE:
3742                         event_name = "MessageQueueReceive";
3743                         break;
3744                 case WAIT_EVENT_MQ_SEND:
3745                         event_name = "MessageQueueSend";
3746                         break;
3747                 case WAIT_EVENT_PARALLEL_BITMAP_SCAN:
3748                         event_name = "ParallelBitmapScan";
3749                         break;
3750                 case WAIT_EVENT_PARALLEL_CREATE_INDEX_SCAN:
3751                         event_name = "ParallelCreateIndexScan";
3752                         break;
3753                 case WAIT_EVENT_PARALLEL_FINISH:
3754                         event_name = "ParallelFinish";
3755                         break;
3756                 case WAIT_EVENT_PROCARRAY_GROUP_UPDATE:
3757                         event_name = "ProcArrayGroupUpdate";
3758                         break;
3759                 case WAIT_EVENT_PROMOTE:
3760                         event_name = "Promote";
3761                         break;
3762                 case WAIT_EVENT_REPLICATION_ORIGIN_DROP:
3763                         event_name = "ReplicationOriginDrop";
3764                         break;
3765                 case WAIT_EVENT_REPLICATION_SLOT_DROP:
3766                         event_name = "ReplicationSlotDrop";
3767                         break;
3768                 case WAIT_EVENT_SAFE_SNAPSHOT:
3769                         event_name = "SafeSnapshot";
3770                         break;
3771                 case WAIT_EVENT_SYNC_REP:
3772                         event_name = "SyncRep";
3773                         break;
3774                         /* no default case, so that compiler will warn */
3775         }
3776
3777         return event_name;
3778 }
3779
3780 /* ----------
3781  * pgstat_get_wait_timeout() -
3782  *
3783  * Convert WaitEventTimeout to string.
3784  * ----------
3785  */
3786 static const char *
3787 pgstat_get_wait_timeout(WaitEventTimeout w)
3788 {
3789         const char *event_name = "unknown wait event";
3790
3791         switch (w)
3792         {
3793                 case WAIT_EVENT_BASE_BACKUP_THROTTLE:
3794                         event_name = "BaseBackupThrottle";
3795                         break;
3796                 case WAIT_EVENT_PG_SLEEP:
3797                         event_name = "PgSleep";
3798                         break;
3799                 case WAIT_EVENT_RECOVERY_APPLY_DELAY:
3800                         event_name = "RecoveryApplyDelay";
3801                         break;
3802                         /* no default case, so that compiler will warn */
3803         }
3804
3805         return event_name;
3806 }
3807
3808 /* ----------
3809  * pgstat_get_wait_io() -
3810  *
3811  * Convert WaitEventIO to string.
3812  * ----------
3813  */
3814 static const char *
3815 pgstat_get_wait_io(WaitEventIO w)
3816 {
3817         const char *event_name = "unknown wait event";
3818
3819         switch (w)
3820         {
3821                 case WAIT_EVENT_BUFFILE_READ:
3822                         event_name = "BufFileRead";
3823                         break;
3824                 case WAIT_EVENT_BUFFILE_WRITE:
3825                         event_name = "BufFileWrite";
3826                         break;
3827                 case WAIT_EVENT_CONTROL_FILE_READ:
3828                         event_name = "ControlFileRead";
3829                         break;
3830                 case WAIT_EVENT_CONTROL_FILE_SYNC:
3831                         event_name = "ControlFileSync";
3832                         break;
3833                 case WAIT_EVENT_CONTROL_FILE_SYNC_UPDATE:
3834                         event_name = "ControlFileSyncUpdate";
3835                         break;
3836                 case WAIT_EVENT_CONTROL_FILE_WRITE:
3837                         event_name = "ControlFileWrite";
3838                         break;
3839                 case WAIT_EVENT_CONTROL_FILE_WRITE_UPDATE:
3840                         event_name = "ControlFileWriteUpdate";
3841                         break;
3842                 case WAIT_EVENT_COPY_FILE_READ:
3843                         event_name = "CopyFileRead";
3844                         break;
3845                 case WAIT_EVENT_COPY_FILE_WRITE:
3846                         event_name = "CopyFileWrite";
3847                         break;
3848                 case WAIT_EVENT_DATA_FILE_EXTEND:
3849                         event_name = "DataFileExtend";
3850                         break;
3851                 case WAIT_EVENT_DATA_FILE_FLUSH:
3852                         event_name = "DataFileFlush";
3853                         break;
3854                 case WAIT_EVENT_DATA_FILE_IMMEDIATE_SYNC:
3855                         event_name = "DataFileImmediateSync";
3856                         break;
3857                 case WAIT_EVENT_DATA_FILE_PREFETCH:
3858                         event_name = "DataFilePrefetch";
3859                         break;
3860                 case WAIT_EVENT_DATA_FILE_READ:
3861                         event_name = "DataFileRead";
3862                         break;
3863                 case WAIT_EVENT_DATA_FILE_SYNC:
3864                         event_name = "DataFileSync";
3865                         break;
3866                 case WAIT_EVENT_DATA_FILE_TRUNCATE:
3867                         event_name = "DataFileTruncate";
3868                         break;
3869                 case WAIT_EVENT_DATA_FILE_WRITE:
3870                         event_name = "DataFileWrite";
3871                         break;
3872                 case WAIT_EVENT_DSM_FILL_ZERO_WRITE:
3873                         event_name = "DSMFillZeroWrite";
3874                         break;
3875                 case WAIT_EVENT_LOCK_FILE_ADDTODATADIR_READ:
3876                         event_name = "LockFileAddToDataDirRead";
3877                         break;
3878                 case WAIT_EVENT_LOCK_FILE_ADDTODATADIR_SYNC:
3879                         event_name = "LockFileAddToDataDirSync";
3880                         break;
3881                 case WAIT_EVENT_LOCK_FILE_ADDTODATADIR_WRITE:
3882                         event_name = "LockFileAddToDataDirWrite";
3883                         break;
3884                 case WAIT_EVENT_LOCK_FILE_CREATE_READ:
3885                         event_name = "LockFileCreateRead";
3886                         break;
3887                 case WAIT_EVENT_LOCK_FILE_CREATE_SYNC:
3888                         event_name = "LockFileCreateSync";
3889                         break;
3890                 case WAIT_EVENT_LOCK_FILE_CREATE_WRITE:
3891                         event_name = "LockFileCreateWrite";
3892                         break;
3893                 case WAIT_EVENT_LOCK_FILE_RECHECKDATADIR_READ:
3894                         event_name = "LockFileReCheckDataDirRead";
3895                         break;
3896                 case WAIT_EVENT_LOGICAL_REWRITE_CHECKPOINT_SYNC:
3897                         event_name = "LogicalRewriteCheckpointSync";
3898                         break;
3899                 case WAIT_EVENT_LOGICAL_REWRITE_MAPPING_SYNC:
3900                         event_name = "LogicalRewriteMappingSync";
3901                         break;
3902                 case WAIT_EVENT_LOGICAL_REWRITE_MAPPING_WRITE:
3903                         event_name = "LogicalRewriteMappingWrite";
3904                         break;
3905                 case WAIT_EVENT_LOGICAL_REWRITE_SYNC:
3906                         event_name = "LogicalRewriteSync";
3907                         break;
3908                 case WAIT_EVENT_LOGICAL_REWRITE_TRUNCATE:
3909                         event_name = "LogicalRewriteTruncate";
3910                         break;
3911                 case WAIT_EVENT_LOGICAL_REWRITE_WRITE:
3912                         event_name = "LogicalRewriteWrite";
3913                         break;
3914                 case WAIT_EVENT_RELATION_MAP_READ:
3915                         event_name = "RelationMapRead";
3916                         break;
3917                 case WAIT_EVENT_RELATION_MAP_SYNC:
3918                         event_name = "RelationMapSync";
3919                         break;
3920                 case WAIT_EVENT_RELATION_MAP_WRITE:
3921                         event_name = "RelationMapWrite";
3922                         break;
3923                 case WAIT_EVENT_REORDER_BUFFER_READ:
3924                         event_name = "ReorderBufferRead";
3925                         break;
3926                 case WAIT_EVENT_REORDER_BUFFER_WRITE:
3927                         event_name = "ReorderBufferWrite";
3928                         break;
3929                 case WAIT_EVENT_REORDER_LOGICAL_MAPPING_READ:
3930                         event_name = "ReorderLogicalMappingRead";
3931                         break;
3932                 case WAIT_EVENT_REPLICATION_SLOT_READ:
3933                         event_name = "ReplicationSlotRead";
3934                         break;
3935                 case WAIT_EVENT_REPLICATION_SLOT_RESTORE_SYNC:
3936                         event_name = "ReplicationSlotRestoreSync";
3937                         break;
3938                 case WAIT_EVENT_REPLICATION_SLOT_SYNC:
3939                         event_name = "ReplicationSlotSync";
3940                         break;
3941                 case WAIT_EVENT_REPLICATION_SLOT_WRITE:
3942                         event_name = "ReplicationSlotWrite";
3943                         break;
3944                 case WAIT_EVENT_SLRU_FLUSH_SYNC:
3945                         event_name = "SLRUFlushSync";
3946                         break;
3947                 case WAIT_EVENT_SLRU_READ:
3948                         event_name = "SLRURead";
3949                         break;
3950                 case WAIT_EVENT_SLRU_SYNC:
3951                         event_name = "SLRUSync";
3952                         break;
3953                 case WAIT_EVENT_SLRU_WRITE:
3954                         event_name = "SLRUWrite";
3955                         break;
3956                 case WAIT_EVENT_SNAPBUILD_READ:
3957                         event_name = "SnapbuildRead";
3958                         break;
3959                 case WAIT_EVENT_SNAPBUILD_SYNC:
3960                         event_name = "SnapbuildSync";
3961                         break;
3962                 case WAIT_EVENT_SNAPBUILD_WRITE:
3963                         event_name = "SnapbuildWrite";
3964                         break;
3965                 case WAIT_EVENT_TIMELINE_HISTORY_FILE_SYNC:
3966                         event_name = "TimelineHistoryFileSync";
3967                         break;
3968                 case WAIT_EVENT_TIMELINE_HISTORY_FILE_WRITE:
3969                         event_name = "TimelineHistoryFileWrite";
3970                         break;
3971                 case WAIT_EVENT_TIMELINE_HISTORY_READ:
3972                         event_name = "TimelineHistoryRead";
3973                         break;
3974                 case WAIT_EVENT_TIMELINE_HISTORY_SYNC:
3975                         event_name = "TimelineHistorySync";
3976                         break;
3977                 case WAIT_EVENT_TIMELINE_HISTORY_WRITE:
3978                         event_name = "TimelineHistoryWrite";
3979                         break;
3980                 case WAIT_EVENT_TWOPHASE_FILE_READ:
3981                         event_name = "TwophaseFileRead";
3982                         break;
3983                 case WAIT_EVENT_TWOPHASE_FILE_SYNC:
3984                         event_name = "TwophaseFileSync";
3985                         break;
3986                 case WAIT_EVENT_TWOPHASE_FILE_WRITE:
3987                         event_name = "TwophaseFileWrite";
3988                         break;
3989                 case WAIT_EVENT_WALSENDER_TIMELINE_HISTORY_READ:
3990                         event_name = "WALSenderTimelineHistoryRead";
3991                         break;
3992                 case WAIT_EVENT_WAL_BOOTSTRAP_SYNC:
3993                         event_name = "WALBootstrapSync";
3994                         break;
3995                 case WAIT_EVENT_WAL_BOOTSTRAP_WRITE:
3996                         event_name = "WALBootstrapWrite";
3997                         break;
3998                 case WAIT_EVENT_WAL_COPY_READ:
3999                         event_name = "WALCopyRead";
4000                         break;
4001                 case WAIT_EVENT_WAL_COPY_SYNC:
4002                         event_name = "WALCopySync";
4003                         break;
4004                 case WAIT_EVENT_WAL_COPY_WRITE:
4005                         event_name = "WALCopyWrite";
4006                         break;
4007                 case WAIT_EVENT_WAL_INIT_SYNC:
4008                         event_name = "WALInitSync";
4009                         break;
4010                 case WAIT_EVENT_WAL_INIT_WRITE:
4011                         event_name = "WALInitWrite";
4012                         break;
4013                 case WAIT_EVENT_WAL_READ:
4014                         event_name = "WALRead";
4015                         break;
4016                 case WAIT_EVENT_WAL_SYNC:
4017                         event_name = "WALSync";
4018                         break;
4019                 case WAIT_EVENT_WAL_SYNC_METHOD_ASSIGN:
4020                         event_name = "WALSyncMethodAssign";
4021                         break;
4022                 case WAIT_EVENT_WAL_WRITE:
4023                         event_name = "WALWrite";
4024                         break;
4025
4026                         /* no default case, so that compiler will warn */
4027         }
4028
4029         return event_name;
4030 }
4031
4032
4033 /* ----------
4034  * pgstat_get_backend_current_activity() -
4035  *
4036  *      Return a string representing the current activity of the backend with
4037  *      the specified PID.  This looks directly at the BackendStatusArray,
4038  *      and so will provide current information regardless of the age of our
4039  *      transaction's snapshot of the status array.
4040  *
4041  *      It is the caller's responsibility to invoke this only for backends whose
4042  *      state is expected to remain stable while the result is in use.  The
4043  *      only current use is in deadlock reporting, where we can expect that
4044  *      the target backend is blocked on a lock.  (There are corner cases
4045  *      where the target's wait could get aborted while we are looking at it,
4046  *      but the very worst consequence is to return a pointer to a string
4047  *      that's been changed, so we won't worry too much.)
4048  *
4049  *      Note: return strings for special cases match pg_stat_get_backend_activity.
4050  * ----------
4051  */
4052 const char *
4053 pgstat_get_backend_current_activity(int pid, bool checkUser)
4054 {
4055         PgBackendStatus *beentry;
4056         int                     i;
4057
4058         beentry = BackendStatusArray;
4059         for (i = 1; i <= MaxBackends; i++)
4060         {
4061                 /*
4062                  * Although we expect the target backend's entry to be stable, that
4063                  * doesn't imply that anyone else's is.  To avoid identifying the
4064                  * wrong backend, while we check for a match to the desired PID we
4065                  * must follow the protocol of retrying if st_changecount changes
4066                  * while we examine the entry, or if it's odd.  (This might be
4067                  * unnecessary, since fetching or storing an int is almost certainly
4068                  * atomic, but let's play it safe.)  We use a volatile pointer here to
4069                  * ensure the compiler doesn't try to get cute.
4070                  */
4071                 volatile PgBackendStatus *vbeentry = beentry;
4072                 bool            found;
4073
4074                 for (;;)
4075                 {
4076                         int                     before_changecount;
4077                         int                     after_changecount;
4078
4079                         pgstat_save_changecount_before(vbeentry, before_changecount);
4080
4081                         found = (vbeentry->st_procpid == pid);
4082
4083                         pgstat_save_changecount_after(vbeentry, after_changecount);
4084
4085                         if (before_changecount == after_changecount &&
4086                                 (before_changecount & 1) == 0)
4087                                 break;
4088
4089                         /* Make sure we can break out of loop if stuck... */
4090                         CHECK_FOR_INTERRUPTS();
4091                 }
4092
4093                 if (found)
4094                 {
4095                         /* Now it is safe to use the non-volatile pointer */
4096                         if (checkUser && !superuser() && beentry->st_userid != GetUserId())
4097                                 return "<insufficient privilege>";
4098                         else if (*(beentry->st_activity_raw) == '\0')
4099                                 return "<command string not enabled>";
4100                         else
4101                         {
4102                                 /* this'll leak a bit of memory, but that seems acceptable */
4103                                 return pgstat_clip_activity(beentry->st_activity_raw);
4104                         }
4105                 }
4106
4107                 beentry++;
4108         }
4109
4110         /* If we get here, caller is in error ... */
4111         return "<backend information not available>";
4112 }
4113
4114 /* ----------
4115  * pgstat_get_crashed_backend_activity() -
4116  *
4117  *      Return a string representing the current activity of the backend with
4118  *      the specified PID.  Like the function above, but reads shared memory with
4119  *      the expectation that it may be corrupt.  On success, copy the string
4120  *      into the "buffer" argument and return that pointer.  On failure,
4121  *      return NULL.
4122  *
4123  *      This function is only intended to be used by the postmaster to report the
4124  *      query that crashed a backend.  In particular, no attempt is made to
4125  *      follow the correct concurrency protocol when accessing the
4126  *      BackendStatusArray.  But that's OK, in the worst case we'll return a
4127  *      corrupted message.  We also must take care not to trip on ereport(ERROR).
4128  * ----------
4129  */
4130 const char *
4131 pgstat_get_crashed_backend_activity(int pid, char *buffer, int buflen)
4132 {
4133         volatile PgBackendStatus *beentry;
4134         int                     i;
4135
4136         beentry = BackendStatusArray;
4137
4138         /*
4139          * We probably shouldn't get here before shared memory has been set up,
4140          * but be safe.
4141          */
4142         if (beentry == NULL || BackendActivityBuffer == NULL)
4143                 return NULL;
4144
4145         for (i = 1; i <= MaxBackends; i++)
4146         {
4147                 if (beentry->st_procpid == pid)
4148                 {
4149                         /* Read pointer just once, so it can't change after validation */
4150                         const char *activity = beentry->st_activity_raw;
4151                         const char *activity_last;
4152
4153                         /*
4154                          * We mustn't access activity string before we verify that it
4155                          * falls within the BackendActivityBuffer. To make sure that the
4156                          * entire string including its ending is contained within the
4157                          * buffer, subtract one activity length from the buffer size.
4158                          */
4159                         activity_last = BackendActivityBuffer + BackendActivityBufferSize
4160                                 - pgstat_track_activity_query_size;
4161
4162                         if (activity < BackendActivityBuffer ||
4163                                 activity > activity_last)
4164                                 return NULL;
4165
4166                         /* If no string available, no point in a report */
4167                         if (activity[0] == '\0')
4168                                 return NULL;
4169
4170                         /*
4171                          * Copy only ASCII-safe characters so we don't run into encoding
4172                          * problems when reporting the message; and be sure not to run off
4173                          * the end of memory.  As only ASCII characters are reported, it
4174                          * doesn't seem necessary to perform multibyte aware clipping.
4175                          */
4176                         ascii_safe_strlcpy(buffer, activity,
4177                                                            Min(buflen, pgstat_track_activity_query_size));
4178
4179                         return buffer;
4180                 }
4181
4182                 beentry++;
4183         }
4184
4185         /* PID not found */
4186         return NULL;
4187 }
4188
4189 const char *
4190 pgstat_get_backend_desc(BackendType backendType)
4191 {
4192         const char *backendDesc = "unknown process type";
4193
4194         switch (backendType)
4195         {
4196                 case B_AUTOVAC_LAUNCHER:
4197                         backendDesc = "autovacuum launcher";
4198                         break;
4199                 case B_AUTOVAC_WORKER:
4200                         backendDesc = "autovacuum worker";
4201                         break;
4202                 case B_BACKEND:
4203                         backendDesc = "client backend";
4204                         break;
4205                 case B_BG_WORKER:
4206                         backendDesc = "background worker";
4207                         break;
4208                 case B_BG_WRITER:
4209                         backendDesc = "background writer";
4210                         break;
4211                 case B_CHECKPOINTER:
4212                         backendDesc = "checkpointer";
4213                         break;
4214                 case B_STARTUP:
4215                         backendDesc = "startup";
4216                         break;
4217                 case B_WAL_RECEIVER:
4218                         backendDesc = "walreceiver";
4219                         break;
4220                 case B_WAL_SENDER:
4221                         backendDesc = "walsender";
4222                         break;
4223                 case B_WAL_WRITER:
4224                         backendDesc = "walwriter";
4225                         break;
4226         }
4227
4228         return backendDesc;
4229 }
4230
4231 /* ------------------------------------------------------------
4232  * Local support functions follow
4233  * ------------------------------------------------------------
4234  */
4235
4236
4237 /* ----------
4238  * pgstat_setheader() -
4239  *
4240  *              Set common header fields in a statistics message
4241  * ----------
4242  */
4243 static void
4244 pgstat_setheader(PgStat_MsgHdr *hdr, StatMsgType mtype)
4245 {
4246         hdr->m_type = mtype;
4247 }
4248
4249
4250 /* ----------
4251  * pgstat_send() -
4252  *
4253  *              Send out one statistics message to the collector
4254  * ----------
4255  */
4256 static void
4257 pgstat_send(void *msg, int len)
4258 {
4259         int                     rc;
4260
4261         if (pgStatSock == PGINVALID_SOCKET)
4262                 return;
4263
4264         ((PgStat_MsgHdr *) msg)->m_size = len;
4265
4266         /* We'll retry after EINTR, but ignore all other failures */
4267         do
4268         {
4269                 rc = send(pgStatSock, msg, len, 0);
4270         } while (rc < 0 && errno == EINTR);
4271
4272 #ifdef USE_ASSERT_CHECKING
4273         /* In debug builds, log send failures ... */
4274         if (rc < 0)
4275                 elog(LOG, "could not send to statistics collector: %m");
4276 #endif
4277 }
4278
4279 /* ----------
4280  * pgstat_send_archiver() -
4281  *
4282  *      Tell the collector about the WAL file that we successfully
4283  *      archived or failed to archive.
4284  * ----------
4285  */
4286 void
4287 pgstat_send_archiver(const char *xlog, bool failed)
4288 {
4289         PgStat_MsgArchiver msg;
4290
4291         /*
4292          * Prepare and send the message
4293          */
4294         pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_ARCHIVER);
4295         msg.m_failed = failed;
4296         StrNCpy(msg.m_xlog, xlog, sizeof(msg.m_xlog));
4297         msg.m_timestamp = GetCurrentTimestamp();
4298         pgstat_send(&msg, sizeof(msg));
4299 }
4300
4301 /* ----------
4302  * pgstat_send_bgwriter() -
4303  *
4304  *              Send bgwriter statistics to the collector
4305  * ----------
4306  */
4307 void
4308 pgstat_send_bgwriter(void)
4309 {
4310         /* We assume this initializes to zeroes */
4311         static const PgStat_MsgBgWriter all_zeroes;
4312
4313         /*
4314          * This function can be called even if nothing at all has happened. In
4315          * this case, avoid sending a completely empty message to the stats
4316          * collector.
4317          */
4318         if (memcmp(&BgWriterStats, &all_zeroes, sizeof(PgStat_MsgBgWriter)) == 0)
4319                 return;
4320
4321         /*
4322          * Prepare and send the message
4323          */
4324         pgstat_setheader(&BgWriterStats.m_hdr, PGSTAT_MTYPE_BGWRITER);
4325         pgstat_send(&BgWriterStats, sizeof(BgWriterStats));
4326
4327         /*
4328          * Clear out the statistics buffer, so it can be re-used.
4329          */
4330         MemSet(&BgWriterStats, 0, sizeof(BgWriterStats));
4331 }
4332
4333
4334 /* ----------
4335  * PgstatCollectorMain() -
4336  *
4337  *      Start up the statistics collector process.  This is the body of the
4338  *      postmaster child process.
4339  *
4340  *      The argc/argv parameters are valid only in EXEC_BACKEND case.
4341  * ----------
4342  */
4343 NON_EXEC_STATIC void
4344 PgstatCollectorMain(int argc, char *argv[])
4345 {
4346         int                     len;
4347         PgStat_Msg      msg;
4348         int                     wr;
4349
4350         /*
4351          * Ignore all signals usually bound to some action in the postmaster,
4352          * except SIGHUP and SIGQUIT.  Note we don't need a SIGUSR1 handler to
4353          * support latch operations, because we only use a local latch.
4354          */
4355         pqsignal(SIGHUP, pgstat_sighup_handler);
4356         pqsignal(SIGINT, SIG_IGN);
4357         pqsignal(SIGTERM, SIG_IGN);
4358         pqsignal(SIGQUIT, pgstat_exit);
4359         pqsignal(SIGALRM, SIG_IGN);
4360         pqsignal(SIGPIPE, SIG_IGN);
4361         pqsignal(SIGUSR1, SIG_IGN);
4362         pqsignal(SIGUSR2, SIG_IGN);
4363         /* Reset some signals that are accepted by postmaster but not here */
4364         pqsignal(SIGCHLD, SIG_DFL);
4365         PG_SETMASK(&UnBlockSig);
4366
4367         /*
4368          * Identify myself via ps
4369          */
4370         init_ps_display("stats collector", "", "", "");
4371
4372         /*
4373          * Read in existing stats files or initialize the stats to zero.
4374          */
4375         pgStatRunningInCollector = true;
4376         pgStatDBHash = pgstat_read_statsfiles(InvalidOid, true, true);
4377
4378         /*
4379          * Loop to process messages until we get SIGQUIT or detect ungraceful
4380          * death of our parent postmaster.
4381          *
4382          * For performance reasons, we don't want to do ResetLatch/WaitLatch after
4383          * every message; instead, do that only after a recv() fails to obtain a
4384          * message.  (This effectively means that if backends are sending us stuff
4385          * like mad, we won't notice postmaster death until things slack off a
4386          * bit; which seems fine.)      To do that, we have an inner loop that
4387          * iterates as long as recv() succeeds.  We do recognize got_SIGHUP inside
4388          * the inner loop, which means that such interrupts will get serviced but
4389          * the latch won't get cleared until next time there is a break in the
4390          * action.
4391          */
4392         for (;;)
4393         {
4394                 /* Clear any already-pending wakeups */
4395                 ResetLatch(MyLatch);
4396
4397                 /*
4398                  * Quit if we get SIGQUIT from the postmaster.
4399                  */
4400                 if (need_exit)
4401                         break;
4402
4403                 /*
4404                  * Inner loop iterates as long as we keep getting messages, or until
4405                  * need_exit becomes set.
4406                  */
4407                 while (!need_exit)
4408                 {
4409                         /*
4410                          * Reload configuration if we got SIGHUP from the postmaster.
4411                          */
4412                         if (got_SIGHUP)
4413                         {
4414                                 got_SIGHUP = false;
4415                                 ProcessConfigFile(PGC_SIGHUP);
4416                         }
4417
4418                         /*
4419                          * Write the stats file(s) if a new request has arrived that is
4420                          * not satisfied by existing file(s).
4421                          */
4422                         if (pgstat_write_statsfile_needed())
4423                                 pgstat_write_statsfiles(false, false);
4424
4425                         /*
4426                          * Try to receive and process a message.  This will not block,
4427                          * since the socket is set to non-blocking mode.
4428                          *
4429                          * XXX On Windows, we have to force pgwin32_recv to cooperate,
4430                          * despite the previous use of pg_set_noblock() on the socket.
4431                          * This is extremely broken and should be fixed someday.
4432                          */
4433 #ifdef WIN32
4434                         pgwin32_noblock = 1;
4435 #endif
4436
4437                         len = recv(pgStatSock, (char *) &msg,
4438                                            sizeof(PgStat_Msg), 0);
4439
4440 #ifdef WIN32
4441                         pgwin32_noblock = 0;
4442 #endif
4443
4444                         if (len < 0)
4445                         {
4446                                 if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
4447                                         break;          /* out of inner loop */
4448                                 ereport(ERROR,
4449                                                 (errcode_for_socket_access(),
4450                                                  errmsg("could not read statistics message: %m")));
4451                         }
4452
4453                         /*
4454                          * We ignore messages that are smaller than our common header
4455                          */
4456                         if (len < sizeof(PgStat_MsgHdr))
4457                                 continue;
4458
4459                         /*
4460                          * The received length must match the length in the header
4461                          */
4462                         if (msg.msg_hdr.m_size != len)
4463                                 continue;
4464
4465                         /*
4466                          * O.K. - we accept this message.  Process it.
4467                          */
4468                         switch (msg.msg_hdr.m_type)
4469                         {
4470                                 case PGSTAT_MTYPE_DUMMY:
4471                                         break;
4472
4473                                 case PGSTAT_MTYPE_INQUIRY:
4474                                         pgstat_recv_inquiry((PgStat_MsgInquiry *) &msg, len);
4475                                         break;
4476
4477                                 case PGSTAT_MTYPE_TABSTAT:
4478                                         pgstat_recv_tabstat((PgStat_MsgTabstat *) &msg, len);
4479                                         break;
4480
4481                                 case PGSTAT_MTYPE_TABPURGE:
4482                                         pgstat_recv_tabpurge((PgStat_MsgTabpurge *) &msg, len);
4483                                         break;
4484
4485                                 case PGSTAT_MTYPE_DROPDB:
4486                                         pgstat_recv_dropdb((PgStat_MsgDropdb *) &msg, len);
4487                                         break;
4488
4489                                 case PGSTAT_MTYPE_RESETCOUNTER:
4490                                         pgstat_recv_resetcounter((PgStat_MsgResetcounter *) &msg,
4491                                                                                          len);
4492                                         break;
4493
4494                                 case PGSTAT_MTYPE_RESETSHAREDCOUNTER:
4495                                         pgstat_recv_resetsharedcounter(
4496                                                                                                    (PgStat_MsgResetsharedcounter *) &msg,
4497                                                                                                    len);
4498                                         break;
4499
4500                                 case PGSTAT_MTYPE_RESETSINGLECOUNTER:
4501                                         pgstat_recv_resetsinglecounter(
4502                                                                                                    (PgStat_MsgResetsinglecounter *) &msg,
4503                                                                                                    len);
4504                                         break;
4505
4506                                 case PGSTAT_MTYPE_AUTOVAC_START:
4507                                         pgstat_recv_autovac((PgStat_MsgAutovacStart *) &msg, len);
4508                                         break;
4509
4510                                 case PGSTAT_MTYPE_VACUUM:
4511                                         pgstat_recv_vacuum((PgStat_MsgVacuum *) &msg, len);
4512                                         break;
4513
4514                                 case PGSTAT_MTYPE_ANALYZE:
4515                                         pgstat_recv_analyze((PgStat_MsgAnalyze *) &msg, len);
4516                                         break;
4517
4518                                 case PGSTAT_MTYPE_ARCHIVER:
4519                                         pgstat_recv_archiver((PgStat_MsgArchiver *) &msg, len);
4520                                         break;
4521
4522                                 case PGSTAT_MTYPE_BGWRITER:
4523                                         pgstat_recv_bgwriter((PgStat_MsgBgWriter *) &msg, len);
4524                                         break;
4525
4526                                 case PGSTAT_MTYPE_FUNCSTAT:
4527                                         pgstat_recv_funcstat((PgStat_MsgFuncstat *) &msg, len);
4528                                         break;
4529
4530                                 case PGSTAT_MTYPE_FUNCPURGE:
4531                                         pgstat_recv_funcpurge((PgStat_MsgFuncpurge *) &msg, len);
4532                                         break;
4533
4534                                 case PGSTAT_MTYPE_RECOVERYCONFLICT:
4535                                         pgstat_recv_recoveryconflict((PgStat_MsgRecoveryConflict *) &msg, len);
4536                                         break;
4537
4538                                 case PGSTAT_MTYPE_DEADLOCK:
4539                                         pgstat_recv_deadlock((PgStat_MsgDeadlock *) &msg, len);
4540                                         break;
4541
4542                                 case PGSTAT_MTYPE_TEMPFILE:
4543                                         pgstat_recv_tempfile((PgStat_MsgTempFile *) &msg, len);
4544                                         break;
4545
4546                                 case PGSTAT_MTYPE_CHECKSUMFAILURE:
4547                                         pgstat_recv_checksum_failure((PgStat_MsgChecksumFailure *) &msg, len);
4548                                         break;
4549
4550                                 default:
4551                                         break;
4552                         }
4553                 }                                               /* end of inner message-processing loop */
4554
4555                 /* Sleep until there's something to do */
4556 #ifndef WIN32
4557                 wr = WaitLatchOrSocket(MyLatch,
4558                                                            WL_LATCH_SET | WL_POSTMASTER_DEATH | WL_SOCKET_READABLE,
4559                                                            pgStatSock, -1L,
4560                                                            WAIT_EVENT_PGSTAT_MAIN);
4561 #else
4562
4563                 /*
4564                  * Windows, at least in its Windows Server 2003 R2 incarnation,
4565                  * sometimes loses FD_READ events.  Waking up and retrying the recv()
4566                  * fixes that, so don't sleep indefinitely.  This is a crock of the
4567                  * first water, but until somebody wants to debug exactly what's
4568                  * happening there, this is the best we can do.  The two-second
4569                  * timeout matches our pre-9.2 behavior, and needs to be short enough
4570                  * to not provoke "using stale statistics" complaints from
4571                  * backend_read_statsfile.
4572                  */
4573                 wr = WaitLatchOrSocket(MyLatch,
4574                                                            WL_LATCH_SET | WL_POSTMASTER_DEATH | WL_SOCKET_READABLE | WL_TIMEOUT,
4575                                                            pgStatSock,
4576                                                            2 * 1000L /* msec */ ,
4577                                                            WAIT_EVENT_PGSTAT_MAIN);
4578 #endif
4579
4580                 /*
4581                  * Emergency bailout if postmaster has died.  This is to avoid the
4582                  * necessity for manual cleanup of all postmaster children.
4583                  */
4584                 if (wr & WL_POSTMASTER_DEATH)
4585                         break;
4586         }                                                       /* end of outer loop */
4587
4588         /*
4589          * Save the final stats to reuse at next startup.
4590          */
4591         pgstat_write_statsfiles(true, true);
4592
4593         exit(0);
4594 }
4595
4596
4597 /* SIGQUIT signal handler for collector process */
4598 static void
4599 pgstat_exit(SIGNAL_ARGS)
4600 {
4601         int                     save_errno = errno;
4602
4603         need_exit = true;
4604         SetLatch(MyLatch);
4605
4606         errno = save_errno;
4607 }
4608
4609 /* SIGHUP handler for collector process */
4610 static void
4611 pgstat_sighup_handler(SIGNAL_ARGS)
4612 {
4613         int                     save_errno = errno;
4614
4615         got_SIGHUP = true;
4616         SetLatch(MyLatch);
4617
4618         errno = save_errno;
4619 }
4620
4621 /*
4622  * Subroutine to clear stats in a database entry
4623  *
4624  * Tables and functions hashes are initialized to empty.
4625  */
4626 static void
4627 reset_dbentry_counters(PgStat_StatDBEntry *dbentry)
4628 {
4629         HASHCTL         hash_ctl;
4630
4631         dbentry->n_xact_commit = 0;
4632         dbentry->n_xact_rollback = 0;
4633         dbentry->n_blocks_fetched = 0;
4634         dbentry->n_blocks_hit = 0;
4635         dbentry->n_tuples_returned = 0;
4636         dbentry->n_tuples_fetched = 0;
4637         dbentry->n_tuples_inserted = 0;
4638         dbentry->n_tuples_updated = 0;
4639         dbentry->n_tuples_deleted = 0;
4640         dbentry->last_autovac_time = 0;
4641         dbentry->n_conflict_tablespace = 0;
4642         dbentry->n_conflict_lock = 0;
4643         dbentry->n_conflict_snapshot = 0;
4644         dbentry->n_conflict_bufferpin = 0;
4645         dbentry->n_conflict_startup_deadlock = 0;
4646         dbentry->n_temp_files = 0;
4647         dbentry->n_temp_bytes = 0;
4648         dbentry->n_deadlocks = 0;
4649         dbentry->n_checksum_failures = 0;
4650         dbentry->n_block_read_time = 0;
4651         dbentry->n_block_write_time = 0;
4652
4653         dbentry->stat_reset_timestamp = GetCurrentTimestamp();
4654         dbentry->stats_timestamp = 0;
4655
4656         memset(&hash_ctl, 0, sizeof(hash_ctl));
4657         hash_ctl.keysize = sizeof(Oid);
4658         hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
4659         dbentry->tables = hash_create("Per-database table",
4660                                                                   PGSTAT_TAB_HASH_SIZE,
4661                                                                   &hash_ctl,
4662                                                                   HASH_ELEM | HASH_BLOBS);
4663
4664         hash_ctl.keysize = sizeof(Oid);
4665         hash_ctl.entrysize = sizeof(PgStat_StatFuncEntry);
4666         dbentry->functions = hash_create("Per-database function",
4667                                                                          PGSTAT_FUNCTION_HASH_SIZE,
4668                                                                          &hash_ctl,
4669                                                                          HASH_ELEM | HASH_BLOBS);
4670 }
4671
4672 /*
4673  * Lookup the hash table entry for the specified database. If no hash
4674  * table entry exists, initialize it, if the create parameter is true.
4675  * Else, return NULL.
4676  */
4677 static PgStat_StatDBEntry *
4678 pgstat_get_db_entry(Oid databaseid, bool create)
4679 {
4680         PgStat_StatDBEntry *result;
4681         bool            found;
4682         HASHACTION      action = (create ? HASH_ENTER : HASH_FIND);
4683
4684         /* Lookup or create the hash table entry for this database */
4685         result = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
4686                                                                                                 &databaseid,
4687                                                                                                 action, &found);
4688
4689         if (!create && !found)
4690                 return NULL;
4691
4692         /*
4693          * If not found, initialize the new one.  This creates empty hash tables
4694          * for tables and functions, too.
4695          */
4696         if (!found)
4697                 reset_dbentry_counters(result);
4698
4699         return result;
4700 }
4701
4702
4703 /*
4704  * Lookup the hash table entry for the specified table. If no hash
4705  * table entry exists, initialize it, if the create parameter is true.
4706  * Else, return NULL.
4707  */
4708 static PgStat_StatTabEntry *
4709 pgstat_get_tab_entry(PgStat_StatDBEntry *dbentry, Oid tableoid, bool create)
4710 {
4711         PgStat_StatTabEntry *result;
4712         bool            found;
4713         HASHACTION      action = (create ? HASH_ENTER : HASH_FIND);
4714
4715         /* Lookup or create the hash table entry for this table */
4716         result = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
4717                                                                                                  &tableoid,
4718                                                                                                  action, &found);
4719
4720         if (!create && !found)
4721                 return NULL;
4722
4723         /* If not found, initialize the new one. */
4724         if (!found)
4725         {
4726                 result->numscans = 0;
4727                 result->tuples_returned = 0;
4728                 result->tuples_fetched = 0;
4729                 result->tuples_inserted = 0;
4730                 result->tuples_updated = 0;
4731                 result->tuples_deleted = 0;
4732                 result->tuples_hot_updated = 0;
4733                 result->n_live_tuples = 0;
4734                 result->n_dead_tuples = 0;
4735                 result->changes_since_analyze = 0;
4736                 result->blocks_fetched = 0;
4737                 result->blocks_hit = 0;
4738                 result->vacuum_timestamp = 0;
4739                 result->vacuum_count = 0;
4740                 result->autovac_vacuum_timestamp = 0;
4741                 result->autovac_vacuum_count = 0;
4742                 result->analyze_timestamp = 0;
4743                 result->analyze_count = 0;
4744                 result->autovac_analyze_timestamp = 0;
4745                 result->autovac_analyze_count = 0;
4746         }
4747
4748         return result;
4749 }
4750
4751
4752 /* ----------
4753  * pgstat_write_statsfiles() -
4754  *              Write the global statistics file, as well as requested DB files.
4755  *
4756  *      'permanent' specifies writing to the permanent files not temporary ones.
4757  *      When true (happens only when the collector is shutting down), also remove
4758  *      the temporary files so that backends starting up under a new postmaster
4759  *      can't read old data before the new collector is ready.
4760  *
4761  *      When 'allDbs' is false, only the requested databases (listed in
4762  *      pending_write_requests) will be written; otherwise, all databases
4763  *      will be written.
4764  * ----------
4765  */
4766 static void
4767 pgstat_write_statsfiles(bool permanent, bool allDbs)
4768 {
4769         HASH_SEQ_STATUS hstat;
4770         PgStat_StatDBEntry *dbentry;
4771         FILE       *fpout;
4772         int32           format_id;
4773         const char *tmpfile = permanent ? PGSTAT_STAT_PERMANENT_TMPFILE : pgstat_stat_tmpname;
4774         const char *statfile = permanent ? PGSTAT_STAT_PERMANENT_FILENAME : pgstat_stat_filename;
4775         int                     rc;
4776
4777         elog(DEBUG2, "writing stats file \"%s\"", statfile);
4778
4779         /*
4780          * Open the statistics temp file to write out the current values.
4781          */
4782         fpout = AllocateFile(tmpfile, PG_BINARY_W);
4783         if (fpout == NULL)
4784         {
4785                 ereport(LOG,
4786                                 (errcode_for_file_access(),
4787                                  errmsg("could not open temporary statistics file \"%s\": %m",
4788                                                 tmpfile)));
4789                 return;
4790         }
4791
4792         /*
4793          * Set the timestamp of the stats file.
4794          */
4795         globalStats.stats_timestamp = GetCurrentTimestamp();
4796
4797         /*
4798          * Write the file header --- currently just a format ID.
4799          */
4800         format_id = PGSTAT_FILE_FORMAT_ID;
4801         rc = fwrite(&format_id, sizeof(format_id), 1, fpout);
4802         (void) rc;                                      /* we'll check for error with ferror */
4803
4804         /*
4805          * Write global stats struct
4806          */
4807         rc = fwrite(&globalStats, sizeof(globalStats), 1, fpout);
4808         (void) rc;                                      /* we'll check for error with ferror */
4809
4810         /*
4811          * Write archiver stats struct
4812          */
4813         rc = fwrite(&archiverStats, sizeof(archiverStats), 1, fpout);
4814         (void) rc;                                      /* we'll check for error with ferror */
4815
4816         /*
4817          * Walk through the database table.
4818          */
4819         hash_seq_init(&hstat, pgStatDBHash);
4820         while ((dbentry = (PgStat_StatDBEntry *) hash_seq_search(&hstat)) != NULL)
4821         {
4822                 /*
4823                  * Write out the table and function stats for this DB into the
4824                  * appropriate per-DB stat file, if required.
4825                  */
4826                 if (allDbs || pgstat_db_requested(dbentry->databaseid))
4827                 {
4828                         /* Make DB's timestamp consistent with the global stats */
4829                         dbentry->stats_timestamp = globalStats.stats_timestamp;
4830
4831                         pgstat_write_db_statsfile(dbentry, permanent);
4832                 }
4833
4834                 /*
4835                  * Write out the DB entry. We don't write the tables or functions
4836                  * pointers, since they're of no use to any other process.
4837                  */
4838                 fputc('D', fpout);
4839                 rc = fwrite(dbentry, offsetof(PgStat_StatDBEntry, tables), 1, fpout);
4840                 (void) rc;                              /* we'll check for error with ferror */
4841         }
4842
4843         /*
4844          * No more output to be done. Close the temp file and replace the old
4845          * pgstat.stat with it.  The ferror() check replaces testing for error
4846          * after each individual fputc or fwrite above.
4847          */
4848         fputc('E', fpout);
4849
4850         if (ferror(fpout))
4851         {
4852                 ereport(LOG,
4853                                 (errcode_for_file_access(),
4854                                  errmsg("could not write temporary statistics file \"%s\": %m",
4855                                                 tmpfile)));
4856                 FreeFile(fpout);
4857                 unlink(tmpfile);
4858         }
4859         else if (FreeFile(fpout) < 0)
4860         {
4861                 ereport(LOG,
4862                                 (errcode_for_file_access(),
4863                                  errmsg("could not close temporary statistics file \"%s\": %m",
4864                                                 tmpfile)));
4865                 unlink(tmpfile);
4866         }
4867         else if (rename(tmpfile, statfile) < 0)
4868         {
4869                 ereport(LOG,
4870                                 (errcode_for_file_access(),
4871                                  errmsg("could not rename temporary statistics file \"%s\" to \"%s\": %m",
4872                                                 tmpfile, statfile)));
4873                 unlink(tmpfile);
4874         }
4875
4876         if (permanent)
4877                 unlink(pgstat_stat_filename);
4878
4879         /*
4880          * Now throw away the list of requests.  Note that requests sent after we
4881          * started the write are still waiting on the network socket.
4882          */
4883         list_free(pending_write_requests);
4884         pending_write_requests = NIL;
4885 }
4886
4887 /*
4888  * return the filename for a DB stat file; filename is the output buffer,
4889  * of length len.
4890  */
4891 static void
4892 get_dbstat_filename(bool permanent, bool tempname, Oid databaseid,
4893                                         char *filename, int len)
4894 {
4895         int                     printed;
4896
4897         /* NB -- pgstat_reset_remove_files knows about the pattern this uses */
4898         printed = snprintf(filename, len, "%s/db_%u.%s",
4899                                            permanent ? PGSTAT_STAT_PERMANENT_DIRECTORY :
4900                                            pgstat_stat_directory,
4901                                            databaseid,
4902                                            tempname ? "tmp" : "stat");
4903         if (printed >= len)
4904                 elog(ERROR, "overlength pgstat path");
4905 }
4906
4907 /* ----------
4908  * pgstat_write_db_statsfile() -
4909  *              Write the stat file for a single database.
4910  *
4911  *      If writing to the permanent file (happens when the collector is
4912  *      shutting down only), remove the temporary file so that backends
4913  *      starting up under a new postmaster can't read the old data before
4914  *      the new collector is ready.
4915  * ----------
4916  */
4917 static void
4918 pgstat_write_db_statsfile(PgStat_StatDBEntry *dbentry, bool permanent)
4919 {
4920         HASH_SEQ_STATUS tstat;
4921         HASH_SEQ_STATUS fstat;
4922         PgStat_StatTabEntry *tabentry;
4923         PgStat_StatFuncEntry *funcentry;
4924         FILE       *fpout;
4925         int32           format_id;
4926         Oid                     dbid = dbentry->databaseid;
4927         int                     rc;
4928         char            tmpfile[MAXPGPATH];
4929         char            statfile[MAXPGPATH];
4930
4931         get_dbstat_filename(permanent, true, dbid, tmpfile, MAXPGPATH);
4932         get_dbstat_filename(permanent, false, dbid, statfile, MAXPGPATH);
4933
4934         elog(DEBUG2, "writing stats file \"%s\"", statfile);
4935
4936         /*
4937          * Open the statistics temp file to write out the current values.
4938          */
4939         fpout = AllocateFile(tmpfile, PG_BINARY_W);
4940         if (fpout == NULL)
4941         {
4942                 ereport(LOG,
4943                                 (errcode_for_file_access(),
4944                                  errmsg("could not open temporary statistics file \"%s\": %m",
4945                                                 tmpfile)));
4946                 return;
4947         }
4948
4949         /*
4950          * Write the file header --- currently just a format ID.
4951          */
4952         format_id = PGSTAT_FILE_FORMAT_ID;
4953         rc = fwrite(&format_id, sizeof(format_id), 1, fpout);
4954         (void) rc;                                      /* we'll check for error with ferror */
4955
4956         /*
4957          * Walk through the database's access stats per table.
4958          */
4959         hash_seq_init(&tstat, dbentry->tables);
4960         while ((tabentry = (PgStat_StatTabEntry *) hash_seq_search(&tstat)) != NULL)
4961         {
4962                 fputc('T', fpout);
4963                 rc = fwrite(tabentry, sizeof(PgStat_StatTabEntry), 1, fpout);
4964                 (void) rc;                              /* we'll check for error with ferror */
4965         }
4966
4967         /*
4968          * Walk through the database's function stats table.
4969          */
4970         hash_seq_init(&fstat, dbentry->functions);
4971         while ((funcentry = (PgStat_StatFuncEntry *) hash_seq_search(&fstat)) != NULL)
4972         {
4973                 fputc('F', fpout);
4974                 rc = fwrite(funcentry, sizeof(PgStat_StatFuncEntry), 1, fpout);
4975                 (void) rc;                              /* we'll check for error with ferror */
4976         }
4977
4978         /*
4979          * No more output to be done. Close the temp file and replace the old
4980          * pgstat.stat with it.  The ferror() check replaces testing for error
4981          * after each individual fputc or fwrite above.
4982          */
4983         fputc('E', fpout);
4984
4985         if (ferror(fpout))
4986         {
4987                 ereport(LOG,
4988                                 (errcode_for_file_access(),
4989                                  errmsg("could not write temporary statistics file \"%s\": %m",
4990                                                 tmpfile)));
4991                 FreeFile(fpout);
4992                 unlink(tmpfile);
4993         }
4994         else if (FreeFile(fpout) < 0)
4995         {
4996                 ereport(LOG,
4997                                 (errcode_for_file_access(),
4998                                  errmsg("could not close temporary statistics file \"%s\": %m",
4999                                                 tmpfile)));
5000                 unlink(tmpfile);
5001         }
5002         else if (rename(tmpfile, statfile) < 0)
5003         {
5004                 ereport(LOG,
5005                                 (errcode_for_file_access(),
5006                                  errmsg("could not rename temporary statistics file \"%s\" to \"%s\": %m",
5007                                                 tmpfile, statfile)));
5008                 unlink(tmpfile);
5009         }
5010
5011         if (permanent)
5012         {
5013                 get_dbstat_filename(false, false, dbid, statfile, MAXPGPATH);
5014
5015                 elog(DEBUG2, "removing temporary stats file \"%s\"", statfile);
5016                 unlink(statfile);
5017         }
5018 }
5019
5020 /* ----------
5021  * pgstat_read_statsfiles() -
5022  *
5023  *      Reads in some existing statistics collector files and returns the
5024  *      databases hash table that is the top level of the data.
5025  *
5026  *      If 'onlydb' is not InvalidOid, it means we only want data for that DB
5027  *      plus the shared catalogs ("DB 0").  We'll still populate the DB hash
5028  *      table for all databases, but we don't bother even creating table/function
5029  *      hash tables for other databases.
5030  *
5031  *      'permanent' specifies reading from the permanent files not temporary ones.
5032  *      When true (happens only when the collector is starting up), remove the
5033  *      files after reading; the in-memory status is now authoritative, and the
5034  *      files would be out of date in case somebody else reads them.
5035  *
5036  *      If a 'deep' read is requested, table/function stats are read, otherwise
5037  *      the table/function hash tables remain empty.
5038  * ----------
5039  */
5040 static HTAB *
5041 pgstat_read_statsfiles(Oid onlydb, bool permanent, bool deep)
5042 {
5043         PgStat_StatDBEntry *dbentry;
5044         PgStat_StatDBEntry dbbuf;
5045         HASHCTL         hash_ctl;
5046         HTAB       *dbhash;
5047         FILE       *fpin;
5048         int32           format_id;
5049         bool            found;
5050         const char *statfile = permanent ? PGSTAT_STAT_PERMANENT_FILENAME : pgstat_stat_filename;
5051
5052         /*
5053          * The tables will live in pgStatLocalContext.
5054          */
5055         pgstat_setup_memcxt();
5056
5057         /*
5058          * Create the DB hashtable
5059          */
5060         memset(&hash_ctl, 0, sizeof(hash_ctl));
5061         hash_ctl.keysize = sizeof(Oid);
5062         hash_ctl.entrysize = sizeof(PgStat_StatDBEntry);
5063         hash_ctl.hcxt = pgStatLocalContext;
5064         dbhash = hash_create("Databases hash", PGSTAT_DB_HASH_SIZE, &hash_ctl,
5065                                                  HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
5066
5067         /*
5068          * Clear out global and archiver statistics so they start from zero in
5069          * case we can't load an existing statsfile.
5070          */
5071         memset(&globalStats, 0, sizeof(globalStats));
5072         memset(&archiverStats, 0, sizeof(archiverStats));
5073
5074         /*
5075          * Set the current timestamp (will be kept only in case we can't load an
5076          * existing statsfile).
5077          */
5078         globalStats.stat_reset_timestamp = GetCurrentTimestamp();
5079         archiverStats.stat_reset_timestamp = globalStats.stat_reset_timestamp;
5080
5081         /*
5082          * Try to open the stats file. If it doesn't exist, the backends simply
5083          * return zero for anything and the collector simply starts from scratch
5084          * with empty counters.
5085          *
5086          * ENOENT is a possibility if the stats collector is not running or has
5087          * not yet written the stats file the first time.  Any other failure
5088          * condition is suspicious.
5089          */
5090         if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
5091         {
5092                 if (errno != ENOENT)
5093                         ereport(pgStatRunningInCollector ? LOG : WARNING,
5094                                         (errcode_for_file_access(),
5095                                          errmsg("could not open statistics file \"%s\": %m",
5096                                                         statfile)));
5097                 return dbhash;
5098         }
5099
5100         /*
5101          * Verify it's of the expected format.
5102          */
5103         if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id) ||
5104                 format_id != PGSTAT_FILE_FORMAT_ID)
5105         {
5106                 ereport(pgStatRunningInCollector ? LOG : WARNING,
5107                                 (errmsg("corrupted statistics file \"%s\"", statfile)));
5108                 goto done;
5109         }
5110
5111         /*
5112          * Read global stats struct
5113          */
5114         if (fread(&globalStats, 1, sizeof(globalStats), fpin) != sizeof(globalStats))
5115         {
5116                 ereport(pgStatRunningInCollector ? LOG : WARNING,
5117                                 (errmsg("corrupted statistics file \"%s\"", statfile)));
5118                 memset(&globalStats, 0, sizeof(globalStats));
5119                 goto done;
5120         }
5121
5122         /*
5123          * In the collector, disregard the timestamp we read from the permanent
5124          * stats file; we should be willing to write a temp stats file immediately
5125          * upon the first request from any backend.  This only matters if the old
5126          * file's timestamp is less than PGSTAT_STAT_INTERVAL ago, but that's not
5127          * an unusual scenario.
5128          */
5129         if (pgStatRunningInCollector)
5130                 globalStats.stats_timestamp = 0;
5131
5132         /*
5133          * Read archiver stats struct
5134          */
5135         if (fread(&archiverStats, 1, sizeof(archiverStats), fpin) != sizeof(archiverStats))
5136         {
5137                 ereport(pgStatRunningInCollector ? LOG : WARNING,
5138                                 (errmsg("corrupted statistics file \"%s\"", statfile)));
5139                 memset(&archiverStats, 0, sizeof(archiverStats));
5140                 goto done;
5141         }
5142
5143         /*
5144          * We found an existing collector stats file. Read it and put all the
5145          * hashtable entries into place.
5146          */
5147         for (;;)
5148         {
5149                 switch (fgetc(fpin))
5150                 {
5151                                 /*
5152                                  * 'D'  A PgStat_StatDBEntry struct describing a database
5153                                  * follows.
5154                                  */
5155                         case 'D':
5156                                 if (fread(&dbbuf, 1, offsetof(PgStat_StatDBEntry, tables),
5157                                                   fpin) != offsetof(PgStat_StatDBEntry, tables))
5158                                 {
5159                                         ereport(pgStatRunningInCollector ? LOG : WARNING,
5160                                                         (errmsg("corrupted statistics file \"%s\"",
5161                                                                         statfile)));
5162                                         goto done;
5163                                 }
5164
5165                                 /*
5166                                  * Add to the DB hash
5167                                  */
5168                                 dbentry = (PgStat_StatDBEntry *) hash_search(dbhash,
5169                                                                                                                          (void *) &dbbuf.databaseid,
5170                                                                                                                          HASH_ENTER,
5171                                                                                                                          &found);
5172                                 if (found)
5173                                 {
5174                                         ereport(pgStatRunningInCollector ? LOG : WARNING,
5175                                                         (errmsg("corrupted statistics file \"%s\"",
5176                                                                         statfile)));
5177                                         goto done;
5178                                 }
5179
5180                                 memcpy(dbentry, &dbbuf, sizeof(PgStat_StatDBEntry));
5181                                 dbentry->tables = NULL;
5182                                 dbentry->functions = NULL;
5183
5184                                 /*
5185                                  * In the collector, disregard the timestamp we read from the
5186                                  * permanent stats file; we should be willing to write a temp
5187                                  * stats file immediately upon the first request from any
5188                                  * backend.
5189                                  */
5190                                 if (pgStatRunningInCollector)
5191                                         dbentry->stats_timestamp = 0;
5192
5193                                 /*
5194                                  * Don't create tables/functions hashtables for uninteresting
5195                                  * databases.
5196                                  */
5197                                 if (onlydb != InvalidOid)
5198                                 {
5199                                         if (dbbuf.databaseid != onlydb &&
5200                                                 dbbuf.databaseid != InvalidOid)
5201                                                 break;
5202                                 }
5203
5204                                 memset(&hash_ctl, 0, sizeof(hash_ctl));
5205                                 hash_ctl.keysize = sizeof(Oid);
5206                                 hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
5207                                 hash_ctl.hcxt = pgStatLocalContext;
5208                                 dbentry->tables = hash_create("Per-database table",
5209                                                                                           PGSTAT_TAB_HASH_SIZE,
5210                                                                                           &hash_ctl,
5211                                                                                           HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
5212
5213                                 hash_ctl.keysize = sizeof(Oid);
5214                                 hash_ctl.entrysize = sizeof(PgStat_StatFuncEntry);
5215                                 hash_ctl.hcxt = pgStatLocalContext;
5216                                 dbentry->functions = hash_create("Per-database function",
5217                                                                                                  PGSTAT_FUNCTION_HASH_SIZE,
5218                                                                                                  &hash_ctl,
5219                                                                                                  HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
5220
5221                                 /*
5222                                  * If requested, read the data from the database-specific
5223                                  * file.  Otherwise we just leave the hashtables empty.
5224                                  */
5225                                 if (deep)
5226                                         pgstat_read_db_statsfile(dbentry->databaseid,
5227                                                                                          dbentry->tables,
5228                                                                                          dbentry->functions,
5229                                                                                          permanent);
5230
5231                                 break;
5232
5233                         case 'E':
5234                                 goto done;
5235
5236                         default:
5237                                 ereport(pgStatRunningInCollector ? LOG : WARNING,
5238                                                 (errmsg("corrupted statistics file \"%s\"",
5239                                                                 statfile)));
5240                                 goto done;
5241                 }
5242         }
5243
5244 done:
5245         FreeFile(fpin);
5246
5247         /* If requested to read the permanent file, also get rid of it. */
5248         if (permanent)
5249         {
5250                 elog(DEBUG2, "removing permanent stats file \"%s\"", statfile);
5251                 unlink(statfile);
5252         }
5253
5254         return dbhash;
5255 }
5256
5257
5258 /* ----------
5259  * pgstat_read_db_statsfile() -
5260  *
5261  *      Reads in the existing statistics collector file for the given database,
5262  *      filling the passed-in tables and functions hash tables.
5263  *
5264  *      As in pgstat_read_statsfiles, if the permanent file is requested, it is
5265  *      removed after reading.
5266  *
5267  *      Note: this code has the ability to skip storing per-table or per-function
5268  *      data, if NULL is passed for the corresponding hashtable.  That's not used
5269  *      at the moment though.
5270  * ----------
5271  */
5272 static void
5273 pgstat_read_db_statsfile(Oid databaseid, HTAB *tabhash, HTAB *funchash,
5274                                                  bool permanent)
5275 {
5276         PgStat_StatTabEntry *tabentry;
5277         PgStat_StatTabEntry tabbuf;
5278         PgStat_StatFuncEntry funcbuf;
5279         PgStat_StatFuncEntry *funcentry;
5280         FILE       *fpin;
5281         int32           format_id;
5282         bool            found;
5283         char            statfile[MAXPGPATH];
5284
5285         get_dbstat_filename(permanent, false, databaseid, statfile, MAXPGPATH);
5286
5287         /*
5288          * Try to open the stats file. If it doesn't exist, the backends simply
5289          * return zero for anything and the collector simply starts from scratch
5290          * with empty counters.
5291          *
5292          * ENOENT is a possibility if the stats collector is not running or has
5293          * not yet written the stats file the first time.  Any other failure
5294          * condition is suspicious.
5295          */
5296         if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
5297         {
5298                 if (errno != ENOENT)
5299                         ereport(pgStatRunningInCollector ? LOG : WARNING,
5300                                         (errcode_for_file_access(),
5301                                          errmsg("could not open statistics file \"%s\": %m",
5302                                                         statfile)));
5303                 return;
5304         }
5305
5306         /*
5307          * Verify it's of the expected format.
5308          */
5309         if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id) ||
5310                 format_id != PGSTAT_FILE_FORMAT_ID)
5311         {
5312                 ereport(pgStatRunningInCollector ? LOG : WARNING,
5313                                 (errmsg("corrupted statistics file \"%s\"", statfile)));
5314                 goto done;
5315         }
5316
5317         /*
5318          * We found an existing collector stats file. Read it and put all the
5319          * hashtable entries into place.
5320          */
5321         for (;;)
5322         {
5323                 switch (fgetc(fpin))
5324                 {
5325                                 /*
5326                                  * 'T'  A PgStat_StatTabEntry follows.
5327                                  */
5328                         case 'T':
5329                                 if (fread(&tabbuf, 1, sizeof(PgStat_StatTabEntry),
5330                                                   fpin) != sizeof(PgStat_StatTabEntry))
5331                                 {
5332                                         ereport(pgStatRunningInCollector ? LOG : WARNING,
5333                                                         (errmsg("corrupted statistics file \"%s\"",
5334                                                                         statfile)));
5335                                         goto done;
5336                                 }
5337
5338                                 /*
5339                                  * Skip if table data not wanted.
5340                                  */
5341                                 if (tabhash == NULL)
5342                                         break;
5343
5344                                 tabentry = (PgStat_StatTabEntry *) hash_search(tabhash,
5345                                                                                                                            (void *) &tabbuf.tableid,
5346                                                                                                                            HASH_ENTER, &found);
5347
5348                                 if (found)
5349                                 {
5350                                         ereport(pgStatRunningInCollector ? LOG : WARNING,
5351                                                         (errmsg("corrupted statistics file \"%s\"",
5352                                                                         statfile)));
5353                                         goto done;
5354                                 }
5355
5356                                 memcpy(tabentry, &tabbuf, sizeof(tabbuf));
5357                                 break;
5358
5359                                 /*
5360                                  * 'F'  A PgStat_StatFuncEntry follows.
5361                                  */
5362                         case 'F':
5363                                 if (fread(&funcbuf, 1, sizeof(PgStat_StatFuncEntry),
5364                                                   fpin) != sizeof(PgStat_StatFuncEntry))
5365                                 {
5366                                         ereport(pgStatRunningInCollector ? LOG : WARNING,
5367                                                         (errmsg("corrupted statistics file \"%s\"",
5368                                                                         statfile)));
5369                                         goto done;
5370                                 }
5371
5372                                 /*
5373                                  * Skip if function data not wanted.
5374                                  */
5375                                 if (funchash == NULL)
5376                                         break;
5377
5378                                 funcentry = (PgStat_StatFuncEntry *) hash_search(funchash,
5379                                                                                                                                  (void *) &funcbuf.functionid,
5380                                                                                                                                  HASH_ENTER, &found);
5381
5382                                 if (found)
5383                                 {
5384                                         ereport(pgStatRunningInCollector ? LOG : WARNING,
5385                                                         (errmsg("corrupted statistics file \"%s\"",
5386                                                                         statfile)));
5387                                         goto done;
5388                                 }
5389
5390                                 memcpy(funcentry, &funcbuf, sizeof(funcbuf));
5391                                 break;
5392
5393                                 /*
5394                                  * 'E'  The EOF marker of a complete stats file.
5395                                  */
5396                         case 'E':
5397                                 goto done;
5398
5399                         default:
5400                                 ereport(pgStatRunningInCollector ? LOG : WARNING,
5401                                                 (errmsg("corrupted statistics file \"%s\"",
5402                                                                 statfile)));
5403                                 goto done;
5404                 }
5405         }
5406
5407 done:
5408         FreeFile(fpin);
5409
5410         if (permanent)
5411         {
5412                 elog(DEBUG2, "removing permanent stats file \"%s\"", statfile);
5413                 unlink(statfile);
5414         }
5415 }
5416
5417 /* ----------
5418  * pgstat_read_db_statsfile_timestamp() -
5419  *
5420  *      Attempt to determine the timestamp of the last db statfile write.
5421  *      Returns true if successful; the timestamp is stored in *ts.
5422  *
5423  *      This needs to be careful about handling databases for which no stats file
5424  *      exists, such as databases without a stat entry or those not yet written:
5425  *
5426  *      - if there's a database entry in the global file, return the corresponding
5427  *      stats_timestamp value.
5428  *
5429  *      - if there's no db stat entry (e.g. for a new or inactive database),
5430  *      there's no stats_timestamp value, but also nothing to write so we return
5431  *      the timestamp of the global statfile.
5432  * ----------
5433  */
5434 static bool
5435 pgstat_read_db_statsfile_timestamp(Oid databaseid, bool permanent,
5436                                                                    TimestampTz *ts)
5437 {
5438         PgStat_StatDBEntry dbentry;
5439         PgStat_GlobalStats myGlobalStats;
5440         PgStat_ArchiverStats myArchiverStats;
5441         FILE       *fpin;
5442         int32           format_id;
5443         const char *statfile = permanent ? PGSTAT_STAT_PERMANENT_FILENAME : pgstat_stat_filename;
5444
5445         /*
5446          * Try to open the stats file.  As above, anything but ENOENT is worthy of
5447          * complaining about.
5448          */
5449         if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
5450         {
5451                 if (errno != ENOENT)
5452                         ereport(pgStatRunningInCollector ? LOG : WARNING,
5453                                         (errcode_for_file_access(),
5454                                          errmsg("could not open statistics file \"%s\": %m",
5455                                                         statfile)));
5456                 return false;
5457         }
5458
5459         /*
5460          * Verify it's of the expected format.
5461          */
5462         if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id) ||
5463                 format_id != PGSTAT_FILE_FORMAT_ID)
5464         {
5465                 ereport(pgStatRunningInCollector ? LOG : WARNING,
5466                                 (errmsg("corrupted statistics file \"%s\"", statfile)));
5467                 FreeFile(fpin);
5468                 return false;
5469         }
5470
5471         /*
5472          * Read global stats struct
5473          */
5474         if (fread(&myGlobalStats, 1, sizeof(myGlobalStats),
5475                           fpin) != sizeof(myGlobalStats))
5476         {
5477                 ereport(pgStatRunningInCollector ? LOG : WARNING,
5478                                 (errmsg("corrupted statistics file \"%s\"", statfile)));
5479                 FreeFile(fpin);
5480                 return false;
5481         }
5482
5483         /*
5484          * Read archiver stats struct
5485          */
5486         if (fread(&myArchiverStats, 1, sizeof(myArchiverStats),
5487                           fpin) != sizeof(myArchiverStats))
5488         {
5489                 ereport(pgStatRunningInCollector ? LOG : WARNING,
5490                                 (errmsg("corrupted statistics file \"%s\"", statfile)));
5491                 FreeFile(fpin);
5492                 return false;
5493         }
5494
5495         /* By default, we're going to return the timestamp of the global file. */
5496         *ts = myGlobalStats.stats_timestamp;
5497
5498         /*
5499          * We found an existing collector stats file.  Read it and look for a
5500          * record for the requested database.  If found, use its timestamp.
5501          */
5502         for (;;)
5503         {
5504                 switch (fgetc(fpin))
5505                 {
5506                                 /*
5507                                  * 'D'  A PgStat_StatDBEntry struct describing a database
5508                                  * follows.
5509                                  */
5510                         case 'D':
5511                                 if (fread(&dbentry, 1, offsetof(PgStat_StatDBEntry, tables),
5512                                                   fpin) != offsetof(PgStat_StatDBEntry, tables))
5513                                 {
5514                                         ereport(pgStatRunningInCollector ? LOG : WARNING,
5515                                                         (errmsg("corrupted statistics file \"%s\"",
5516                                                                         statfile)));
5517                                         goto done;
5518                                 }
5519
5520                                 /*
5521                                  * If this is the DB we're looking for, save its timestamp and
5522                                  * we're done.
5523                                  */
5524                                 if (dbentry.databaseid == databaseid)
5525                                 {
5526                                         *ts = dbentry.stats_timestamp;
5527                                         goto done;
5528                                 }
5529
5530                                 break;
5531
5532                         case 'E':
5533                                 goto done;
5534
5535                         default:
5536                                 ereport(pgStatRunningInCollector ? LOG : WARNING,
5537                                                 (errmsg("corrupted statistics file \"%s\"",
5538                                                                 statfile)));
5539                                 goto done;
5540                 }
5541         }
5542
5543 done:
5544         FreeFile(fpin);
5545         return true;
5546 }
5547
5548 /*
5549  * If not already done, read the statistics collector stats file into
5550  * some hash tables.  The results will be kept until pgstat_clear_snapshot()
5551  * is called (typically, at end of transaction).
5552  */
5553 static void
5554 backend_read_statsfile(void)
5555 {
5556         TimestampTz min_ts = 0;
5557         TimestampTz ref_ts = 0;
5558         Oid                     inquiry_db;
5559         int                     count;
5560
5561         /* already read it? */
5562         if (pgStatDBHash)
5563                 return;
5564         Assert(!pgStatRunningInCollector);
5565
5566         /*
5567          * In a normal backend, we check staleness of the data for our own DB, and
5568          * so we send MyDatabaseId in inquiry messages.  In the autovac launcher,
5569          * check staleness of the shared-catalog data, and send InvalidOid in
5570          * inquiry messages so as not to force writing unnecessary data.
5571          */
5572         if (IsAutoVacuumLauncherProcess())
5573                 inquiry_db = InvalidOid;
5574         else
5575                 inquiry_db = MyDatabaseId;
5576
5577         /*
5578          * Loop until fresh enough stats file is available or we ran out of time.
5579          * The stats inquiry message is sent repeatedly in case collector drops
5580          * it; but not every single time, as that just swamps the collector.
5581          */
5582         for (count = 0; count < PGSTAT_POLL_LOOP_COUNT; count++)
5583         {
5584                 bool            ok;
5585                 TimestampTz file_ts = 0;
5586                 TimestampTz cur_ts;
5587
5588                 CHECK_FOR_INTERRUPTS();
5589
5590                 ok = pgstat_read_db_statsfile_timestamp(inquiry_db, false, &file_ts);
5591
5592                 cur_ts = GetCurrentTimestamp();
5593                 /* Calculate min acceptable timestamp, if we didn't already */
5594                 if (count == 0 || cur_ts < ref_ts)
5595                 {
5596                         /*
5597                          * We set the minimum acceptable timestamp to PGSTAT_STAT_INTERVAL
5598                          * msec before now.  This indirectly ensures that the collector
5599                          * needn't write the file more often than PGSTAT_STAT_INTERVAL. In
5600                          * an autovacuum worker, however, we want a lower delay to avoid
5601                          * using stale data, so we use PGSTAT_RETRY_DELAY (since the
5602                          * number of workers is low, this shouldn't be a problem).
5603                          *
5604                          * We don't recompute min_ts after sleeping, except in the
5605                          * unlikely case that cur_ts went backwards.  So we might end up
5606                          * accepting a file a bit older than PGSTAT_STAT_INTERVAL.  In
5607                          * practice that shouldn't happen, though, as long as the sleep
5608                          * time is less than PGSTAT_STAT_INTERVAL; and we don't want to
5609                          * tell the collector that our cutoff time is less than what we'd
5610                          * actually accept.
5611                          */
5612                         ref_ts = cur_ts;
5613                         if (IsAutoVacuumWorkerProcess())
5614                                 min_ts = TimestampTzPlusMilliseconds(ref_ts,
5615                                                                                                          -PGSTAT_RETRY_DELAY);
5616                         else
5617                                 min_ts = TimestampTzPlusMilliseconds(ref_ts,
5618                                                                                                          -PGSTAT_STAT_INTERVAL);
5619                 }
5620
5621                 /*
5622                  * If the file timestamp is actually newer than cur_ts, we must have
5623                  * had a clock glitch (system time went backwards) or there is clock
5624                  * skew between our processor and the stats collector's processor.
5625                  * Accept the file, but send an inquiry message anyway to make
5626                  * pgstat_recv_inquiry do a sanity check on the collector's time.
5627                  */
5628                 if (ok && file_ts > cur_ts)
5629                 {
5630                         /*
5631                          * A small amount of clock skew between processors isn't terribly
5632                          * surprising, but a large difference is worth logging.  We
5633                          * arbitrarily define "large" as 1000 msec.
5634                          */
5635                         if (file_ts >= TimestampTzPlusMilliseconds(cur_ts, 1000))
5636                         {
5637                                 char       *filetime;
5638                                 char       *mytime;
5639
5640                                 /* Copy because timestamptz_to_str returns a static buffer */
5641                                 filetime = pstrdup(timestamptz_to_str(file_ts));
5642                                 mytime = pstrdup(timestamptz_to_str(cur_ts));
5643                                 elog(LOG, "stats collector's time %s is later than backend local time %s",
5644                                          filetime, mytime);
5645                                 pfree(filetime);
5646                                 pfree(mytime);
5647                         }
5648
5649                         pgstat_send_inquiry(cur_ts, min_ts, inquiry_db);
5650                         break;
5651                 }
5652
5653                 /* Normal acceptance case: file is not older than cutoff time */
5654                 if (ok && file_ts >= min_ts)
5655                         break;
5656
5657                 /* Not there or too old, so kick the collector and wait a bit */
5658                 if ((count % PGSTAT_INQ_LOOP_COUNT) == 0)
5659                         pgstat_send_inquiry(cur_ts, min_ts, inquiry_db);
5660
5661                 pg_usleep(PGSTAT_RETRY_DELAY * 1000L);
5662         }
5663
5664         if (count >= PGSTAT_POLL_LOOP_COUNT)
5665                 ereport(LOG,
5666                                 (errmsg("using stale statistics instead of current ones "
5667                                                 "because stats collector is not responding")));
5668
5669         /*
5670          * Autovacuum launcher wants stats about all databases, but a shallow read
5671          * is sufficient.  Regular backends want a deep read for just the tables
5672          * they can see (MyDatabaseId + shared catalogs).
5673          */
5674         if (IsAutoVacuumLauncherProcess())
5675                 pgStatDBHash = pgstat_read_statsfiles(InvalidOid, false, false);
5676         else
5677                 pgStatDBHash = pgstat_read_statsfiles(MyDatabaseId, false, true);
5678 }
5679
5680
5681 /* ----------
5682  * pgstat_setup_memcxt() -
5683  *
5684  *      Create pgStatLocalContext, if not already done.
5685  * ----------
5686  */
5687 static void
5688 pgstat_setup_memcxt(void)
5689 {
5690         if (!pgStatLocalContext)
5691                 pgStatLocalContext = AllocSetContextCreate(TopMemoryContext,
5692                                                                                                    "Statistics snapshot",
5693                                                                                                    ALLOCSET_SMALL_SIZES);
5694 }
5695
5696
5697 /* ----------
5698  * pgstat_clear_snapshot() -
5699  *
5700  *      Discard any data collected in the current transaction.  Any subsequent
5701  *      request will cause new snapshots to be read.
5702  *
5703  *      This is also invoked during transaction commit or abort to discard
5704  *      the no-longer-wanted snapshot.
5705  * ----------
5706  */
5707 void
5708 pgstat_clear_snapshot(void)
5709 {
5710         /* Release memory, if any was allocated */
5711         if (pgStatLocalContext)
5712                 MemoryContextDelete(pgStatLocalContext);
5713
5714         /* Reset variables */
5715         pgStatLocalContext = NULL;
5716         pgStatDBHash = NULL;
5717         localBackendStatusTable = NULL;
5718         localNumBackends = 0;
5719 }
5720
5721
5722 /* ----------
5723  * pgstat_recv_inquiry() -
5724  *
5725  *      Process stat inquiry requests.
5726  * ----------
5727  */
5728 static void
5729 pgstat_recv_inquiry(PgStat_MsgInquiry *msg, int len)
5730 {
5731         PgStat_StatDBEntry *dbentry;
5732
5733         elog(DEBUG2, "received inquiry for database %u", msg->databaseid);
5734
5735         /*
5736          * If there's already a write request for this DB, there's nothing to do.
5737          *
5738          * Note that if a request is found, we return early and skip the below
5739          * check for clock skew.  This is okay, since the only way for a DB
5740          * request to be present in the list is that we have been here since the
5741          * last write round.  It seems sufficient to check for clock skew once per
5742          * write round.
5743          */
5744         if (list_member_oid(pending_write_requests, msg->databaseid))
5745                 return;
5746
5747         /*
5748          * Check to see if we last wrote this database at a time >= the requested
5749          * cutoff time.  If so, this is a stale request that was generated before
5750          * we updated the DB file, and we don't need to do so again.
5751          *
5752          * If the requestor's local clock time is older than stats_timestamp, we
5753          * should suspect a clock glitch, ie system time going backwards; though
5754          * the more likely explanation is just delayed message receipt.  It is
5755          * worth expending a GetCurrentTimestamp call to be sure, since a large
5756          * retreat in the system clock reading could otherwise cause us to neglect
5757          * to update the stats file for a long time.
5758          */
5759         dbentry = pgstat_get_db_entry(msg->databaseid, false);
5760         if (dbentry == NULL)
5761         {
5762                 /*
5763                  * We have no data for this DB.  Enter a write request anyway so that
5764                  * the global stats will get updated.  This is needed to prevent
5765                  * backend_read_statsfile from waiting for data that we cannot supply,
5766                  * in the case of a new DB that nobody has yet reported any stats for.
5767                  * See the behavior of pgstat_read_db_statsfile_timestamp.
5768                  */
5769         }
5770         else if (msg->clock_time < dbentry->stats_timestamp)
5771         {
5772                 TimestampTz cur_ts = GetCurrentTimestamp();
5773
5774                 if (cur_ts < dbentry->stats_timestamp)
5775                 {
5776                         /*
5777                          * Sure enough, time went backwards.  Force a new stats file write
5778                          * to get back in sync; but first, log a complaint.
5779                          */
5780                         char       *writetime;
5781                         char       *mytime;
5782
5783                         /* Copy because timestamptz_to_str returns a static buffer */
5784                         writetime = pstrdup(timestamptz_to_str(dbentry->stats_timestamp));
5785                         mytime = pstrdup(timestamptz_to_str(cur_ts));
5786                         elog(LOG,
5787                                  "stats_timestamp %s is later than collector's time %s for database %u",
5788                                  writetime, mytime, dbentry->databaseid);
5789                         pfree(writetime);
5790                         pfree(mytime);
5791                 }
5792                 else
5793                 {
5794                         /*
5795                          * Nope, it's just an old request.  Assuming msg's clock_time is
5796                          * >= its cutoff_time, it must be stale, so we can ignore it.
5797                          */
5798                         return;
5799                 }
5800         }
5801         else if (msg->cutoff_time <= dbentry->stats_timestamp)
5802         {
5803                 /* Stale request, ignore it */
5804                 return;
5805         }
5806
5807         /*
5808          * We need to write this DB, so create a request.
5809          */
5810         pending_write_requests = lappend_oid(pending_write_requests,
5811                                                                                  msg->databaseid);
5812 }
5813
5814
5815 /* ----------
5816  * pgstat_recv_tabstat() -
5817  *
5818  *      Count what the backend has done.
5819  * ----------
5820  */
5821 static void
5822 pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len)
5823 {
5824         PgStat_StatDBEntry *dbentry;
5825         PgStat_StatTabEntry *tabentry;
5826         int                     i;
5827         bool            found;
5828
5829         dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
5830
5831         /*
5832          * Update database-wide stats.
5833          */
5834         dbentry->n_xact_commit += (PgStat_Counter) (msg->m_xact_commit);
5835         dbentry->n_xact_rollback += (PgStat_Counter) (msg->m_xact_rollback);
5836         dbentry->n_block_read_time += msg->m_block_read_time;
5837         dbentry->n_block_write_time += msg->m_block_write_time;
5838
5839         /*
5840          * Process all table entries in the message.
5841          */
5842         for (i = 0; i < msg->m_nentries; i++)
5843         {
5844                 PgStat_TableEntry *tabmsg = &(msg->m_entry[i]);
5845
5846                 tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
5847                                                                                                            (void *) &(tabmsg->t_id),
5848                                                                                                            HASH_ENTER, &found);
5849
5850                 if (!found)
5851                 {
5852                         /*
5853                          * If it's a new table entry, initialize counters to the values we
5854                          * just got.
5855                          */
5856                         tabentry->numscans = tabmsg->t_counts.t_numscans;
5857                         tabentry->tuples_returned = tabmsg->t_counts.t_tuples_returned;
5858                         tabentry->tuples_fetched = tabmsg->t_counts.t_tuples_fetched;
5859                         tabentry->tuples_inserted = tabmsg->t_counts.t_tuples_inserted;
5860                         tabentry->tuples_updated = tabmsg->t_counts.t_tuples_updated;
5861                         tabentry->tuples_deleted = tabmsg->t_counts.t_tuples_deleted;
5862                         tabentry->tuples_hot_updated = tabmsg->t_counts.t_tuples_hot_updated;
5863                         tabentry->n_live_tuples = tabmsg->t_counts.t_delta_live_tuples;
5864                         tabentry->n_dead_tuples = tabmsg->t_counts.t_delta_dead_tuples;
5865                         tabentry->changes_since_analyze = tabmsg->t_counts.t_changed_tuples;
5866                         tabentry->blocks_fetched = tabmsg->t_counts.t_blocks_fetched;
5867                         tabentry->blocks_hit = tabmsg->t_counts.t_blocks_hit;
5868
5869                         tabentry->vacuum_timestamp = 0;
5870                         tabentry->vacuum_count = 0;
5871                         tabentry->autovac_vacuum_timestamp = 0;
5872                         tabentry->autovac_vacuum_count = 0;
5873                         tabentry->analyze_timestamp = 0;
5874                         tabentry->analyze_count = 0;
5875                         tabentry->autovac_analyze_timestamp = 0;
5876                         tabentry->autovac_analyze_count = 0;
5877                 }
5878                 else
5879                 {
5880                         /*
5881                          * Otherwise add the values to the existing entry.
5882                          */
5883                         tabentry->numscans += tabmsg->t_counts.t_numscans;
5884                         tabentry->tuples_returned += tabmsg->t_counts.t_tuples_returned;
5885                         tabentry->tuples_fetched += tabmsg->t_counts.t_tuples_fetched;
5886                         tabentry->tuples_inserted += tabmsg->t_counts.t_tuples_inserted;
5887                         tabentry->tuples_updated += tabmsg->t_counts.t_tuples_updated;
5888                         tabentry->tuples_deleted += tabmsg->t_counts.t_tuples_deleted;
5889                         tabentry->tuples_hot_updated += tabmsg->t_counts.t_tuples_hot_updated;
5890                         /* If table was truncated, first reset the live/dead counters */
5891                         if (tabmsg->t_counts.t_truncated)
5892                         {
5893                                 tabentry->n_live_tuples = 0;
5894                                 tabentry->n_dead_tuples = 0;
5895                         }
5896                         tabentry->n_live_tuples += tabmsg->t_counts.t_delta_live_tuples;
5897                         tabentry->n_dead_tuples += tabmsg->t_counts.t_delta_dead_tuples;
5898                         tabentry->changes_since_analyze += tabmsg->t_counts.t_changed_tuples;
5899                         tabentry->blocks_fetched += tabmsg->t_counts.t_blocks_fetched;
5900                         tabentry->blocks_hit += tabmsg->t_counts.t_blocks_hit;
5901                 }
5902
5903                 /* Clamp n_live_tuples in case of negative delta_live_tuples */
5904                 tabentry->n_live_tuples = Max(tabentry->n_live_tuples, 0);
5905                 /* Likewise for n_dead_tuples */
5906                 tabentry->n_dead_tuples = Max(tabentry->n_dead_tuples, 0);
5907
5908                 /*
5909                  * Add per-table stats to the per-database entry, too.
5910                  */
5911                 dbentry->n_tuples_returned += tabmsg->t_counts.t_tuples_returned;
5912                 dbentry->n_tuples_fetched += tabmsg->t_counts.t_tuples_fetched;
5913                 dbentry->n_tuples_inserted += tabmsg->t_counts.t_tuples_inserted;
5914                 dbentry->n_tuples_updated += tabmsg->t_counts.t_tuples_updated;
5915                 dbentry->n_tuples_deleted += tabmsg->t_counts.t_tuples_deleted;
5916                 dbentry->n_blocks_fetched += tabmsg->t_counts.t_blocks_fetched;
5917                 dbentry->n_blocks_hit += tabmsg->t_counts.t_blocks_hit;
5918         }
5919 }
5920
5921
5922 /* ----------
5923  * pgstat_recv_tabpurge() -
5924  *
5925  *      Arrange for dead table removal.
5926  * ----------
5927  */
5928 static void
5929 pgstat_recv_tabpurge(PgStat_MsgTabpurge *msg, int len)
5930 {
5931         PgStat_StatDBEntry *dbentry;
5932         int                     i;
5933
5934         dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
5935
5936         /*
5937          * No need to purge if we don't even know the database.
5938          */
5939         if (!dbentry || !dbentry->tables)
5940                 return;
5941
5942         /*
5943          * Process all table entries in the message.
5944          */
5945         for (i = 0; i < msg->m_nentries; i++)
5946         {
5947                 /* Remove from hashtable if present; we don't care if it's not. */
5948                 (void) hash_search(dbentry->tables,
5949                                                    (void *) &(msg->m_tableid[i]),
5950                                                    HASH_REMOVE, NULL);
5951         }
5952 }
5953
5954
5955 /* ----------
5956  * pgstat_recv_dropdb() -
5957  *
5958  *      Arrange for dead database removal
5959  * ----------
5960  */
5961 static void
5962 pgstat_recv_dropdb(PgStat_MsgDropdb *msg, int len)
5963 {
5964         Oid                     dbid = msg->m_databaseid;
5965         PgStat_StatDBEntry *dbentry;
5966
5967         /*
5968          * Lookup the database in the hashtable.
5969          */
5970         dbentry = pgstat_get_db_entry(dbid, false);
5971
5972         /*
5973          * If found, remove it (along with the db statfile).
5974          */
5975         if (dbentry)
5976         {
5977                 char            statfile[MAXPGPATH];
5978
5979                 get_dbstat_filename(false, false, dbid, statfile, MAXPGPATH);
5980
5981                 elog(DEBUG2, "removing stats file \"%s\"", statfile);
5982                 unlink(statfile);
5983
5984                 if (dbentry->tables != NULL)
5985                         hash_destroy(dbentry->tables);
5986                 if (dbentry->functions != NULL)
5987                         hash_destroy(dbentry->functions);
5988
5989                 if (hash_search(pgStatDBHash,
5990                                                 (void *) &dbid,
5991                                                 HASH_REMOVE, NULL) == NULL)
5992                         ereport(ERROR,
5993                                         (errmsg("database hash table corrupted during cleanup --- abort")));
5994         }
5995 }
5996
5997
5998 /* ----------
5999  * pgstat_recv_resetcounter() -
6000  *
6001  *      Reset the statistics for the specified database.
6002  * ----------
6003  */
6004 static void
6005 pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len)
6006 {
6007         PgStat_StatDBEntry *dbentry;
6008
6009         /*
6010          * Lookup the database in the hashtable.  Nothing to do if not there.
6011          */
6012         dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
6013
6014         if (!dbentry)
6015                 return;
6016
6017         /*
6018          * We simply throw away all the database's table entries by recreating a
6019          * new hash table for them.
6020          */
6021         if (dbentry->tables != NULL)
6022                 hash_destroy(dbentry->tables);
6023         if (dbentry->functions != NULL)
6024                 hash_destroy(dbentry->functions);
6025
6026         dbentry->tables = NULL;
6027         dbentry->functions = NULL;
6028
6029         /*
6030          * Reset database-level stats, too.  This creates empty hash tables for
6031          * tables and functions.
6032          */
6033         reset_dbentry_counters(dbentry);
6034 }
6035
6036 /* ----------
6037  * pgstat_recv_resetshared() -
6038  *
6039  *      Reset some shared statistics of the cluster.
6040  * ----------
6041  */
6042 static void
6043 pgstat_recv_resetsharedcounter(PgStat_MsgResetsharedcounter *msg, int len)
6044 {
6045         if (msg->m_resettarget == RESET_BGWRITER)
6046         {
6047                 /* Reset the global background writer statistics for the cluster. */
6048                 memset(&globalStats, 0, sizeof(globalStats));
6049                 globalStats.stat_reset_timestamp = GetCurrentTimestamp();
6050         }
6051         else if (msg->m_resettarget == RESET_ARCHIVER)
6052         {
6053                 /* Reset the archiver statistics for the cluster. */
6054                 memset(&archiverStats, 0, sizeof(archiverStats));
6055                 archiverStats.stat_reset_timestamp = GetCurrentTimestamp();
6056         }
6057
6058         /*
6059          * Presumably the sender of this message validated the target, don't
6060          * complain here if it's not valid
6061          */
6062 }
6063
6064 /* ----------
6065  * pgstat_recv_resetsinglecounter() -
6066  *
6067  *      Reset a statistics for a single object
6068  * ----------
6069  */
6070 static void
6071 pgstat_recv_resetsinglecounter(PgStat_MsgResetsinglecounter *msg, int len)
6072 {
6073         PgStat_StatDBEntry *dbentry;
6074
6075         dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
6076
6077         if (!dbentry)
6078                 return;
6079
6080         /* Set the reset timestamp for the whole database */
6081         dbentry->stat_reset_timestamp = GetCurrentTimestamp();
6082
6083         /* Remove object if it exists, ignore it if not */
6084         if (msg->m_resettype == RESET_TABLE)
6085                 (void) hash_search(dbentry->tables, (void *) &(msg->m_objectid),
6086                                                    HASH_REMOVE, NULL);
6087         else if (msg->m_resettype == RESET_FUNCTION)
6088                 (void) hash_search(dbentry->functions, (void *) &(msg->m_objectid),
6089                                                    HASH_REMOVE, NULL);
6090 }
6091
6092 /* ----------
6093  * pgstat_recv_autovac() -
6094  *
6095  *      Process an autovacuum signalling message.
6096  * ----------
6097  */
6098 static void
6099 pgstat_recv_autovac(PgStat_MsgAutovacStart *msg, int len)
6100 {
6101         PgStat_StatDBEntry *dbentry;
6102
6103         /*
6104          * Store the last autovacuum time in the database's hashtable entry.
6105          */
6106         dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
6107
6108         dbentry->last_autovac_time = msg->m_start_time;
6109 }
6110
6111 /* ----------
6112  * pgstat_recv_vacuum() -
6113  *
6114  *      Process a VACUUM message.
6115  * ----------
6116  */
6117 static void
6118 pgstat_recv_vacuum(PgStat_MsgVacuum *msg, int len)
6119 {
6120         PgStat_StatDBEntry *dbentry;
6121         PgStat_StatTabEntry *tabentry;
6122
6123         /*
6124          * Store the data in the table's hashtable entry.
6125          */
6126         dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
6127
6128         tabentry = pgstat_get_tab_entry(dbentry, msg->m_tableoid, true);
6129
6130         tabentry->n_live_tuples = msg->m_live_tuples;
6131         tabentry->n_dead_tuples = msg->m_dead_tuples;
6132
6133         if (msg->m_autovacuum)
6134         {
6135                 tabentry->autovac_vacuum_timestamp = msg->m_vacuumtime;
6136                 tabentry->autovac_vacuum_count++;
6137         }
6138         else
6139         {
6140                 tabentry->vacuum_timestamp = msg->m_vacuumtime;
6141                 tabentry->vacuum_count++;
6142         }
6143 }
6144
6145 /* ----------
6146  * pgstat_recv_analyze() -
6147  *
6148  *      Process an ANALYZE message.
6149  * ----------
6150  */
6151 static void
6152 pgstat_recv_analyze(PgStat_MsgAnalyze *msg, int len)
6153 {
6154         PgStat_StatDBEntry *dbentry;
6155         PgStat_StatTabEntry *tabentry;
6156
6157         /*
6158          * Store the data in the table's hashtable entry.
6159          */
6160         dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
6161
6162         tabentry = pgstat_get_tab_entry(dbentry, msg->m_tableoid, true);
6163
6164         tabentry->n_live_tuples = msg->m_live_tuples;
6165         tabentry->n_dead_tuples = msg->m_dead_tuples;
6166
6167         /*
6168          * If commanded, reset changes_since_analyze to zero.  This forgets any
6169          * changes that were committed while the ANALYZE was in progress, but we
6170          * have no good way to estimate how many of those there were.
6171          */
6172         if (msg->m_resetcounter)
6173                 tabentry->changes_since_analyze = 0;
6174
6175         if (msg->m_autovacuum)
6176         {
6177                 tabentry->autovac_analyze_timestamp = msg->m_analyzetime;
6178                 tabentry->autovac_analyze_count++;
6179         }
6180         else
6181         {
6182                 tabentry->analyze_timestamp = msg->m_analyzetime;
6183                 tabentry->analyze_count++;
6184         }
6185 }
6186
6187
6188 /* ----------
6189  * pgstat_recv_archiver() -
6190  *
6191  *      Process a ARCHIVER message.
6192  * ----------
6193  */
6194 static void
6195 pgstat_recv_archiver(PgStat_MsgArchiver *msg, int len)
6196 {
6197         if (msg->m_failed)
6198         {
6199                 /* Failed archival attempt */
6200                 ++archiverStats.failed_count;
6201                 memcpy(archiverStats.last_failed_wal, msg->m_xlog,
6202                            sizeof(archiverStats.last_failed_wal));
6203                 archiverStats.last_failed_timestamp = msg->m_timestamp;
6204         }
6205         else
6206         {
6207                 /* Successful archival operation */
6208                 ++archiverStats.archived_count;
6209                 memcpy(archiverStats.last_archived_wal, msg->m_xlog,
6210                            sizeof(archiverStats.last_archived_wal));
6211                 archiverStats.last_archived_timestamp = msg->m_timestamp;
6212         }
6213 }
6214
6215 /* ----------
6216  * pgstat_recv_bgwriter() -
6217  *
6218  *      Process a BGWRITER message.
6219  * ----------
6220  */
6221 static void
6222 pgstat_recv_bgwriter(PgStat_MsgBgWriter *msg, int len)
6223 {
6224         globalStats.timed_checkpoints += msg->m_timed_checkpoints;
6225         globalStats.requested_checkpoints += msg->m_requested_checkpoints;
6226         globalStats.checkpoint_write_time += msg->m_checkpoint_write_time;
6227         globalStats.checkpoint_sync_time += msg->m_checkpoint_sync_time;
6228         globalStats.buf_written_checkpoints += msg->m_buf_written_checkpoints;
6229         globalStats.buf_written_clean += msg->m_buf_written_clean;
6230         globalStats.maxwritten_clean += msg->m_maxwritten_clean;
6231         globalStats.buf_written_backend += msg->m_buf_written_backend;
6232         globalStats.buf_fsync_backend += msg->m_buf_fsync_backend;
6233         globalStats.buf_alloc += msg->m_buf_alloc;
6234 }
6235
6236 /* ----------
6237  * pgstat_recv_recoveryconflict() -
6238  *
6239  *      Process a RECOVERYCONFLICT message.
6240  * ----------
6241  */
6242 static void
6243 pgstat_recv_recoveryconflict(PgStat_MsgRecoveryConflict *msg, int len)
6244 {
6245         PgStat_StatDBEntry *dbentry;
6246
6247         dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
6248
6249         switch (msg->m_reason)
6250         {
6251                 case PROCSIG_RECOVERY_CONFLICT_DATABASE:
6252
6253                         /*
6254                          * Since we drop the information about the database as soon as it
6255                          * replicates, there is no point in counting these conflicts.
6256                          */
6257                         break;
6258                 case PROCSIG_RECOVERY_CONFLICT_TABLESPACE:
6259                         dbentry->n_conflict_tablespace++;
6260                         break;
6261                 case PROCSIG_RECOVERY_CONFLICT_LOCK:
6262                         dbentry->n_conflict_lock++;
6263                         break;
6264                 case PROCSIG_RECOVERY_CONFLICT_SNAPSHOT:
6265                         dbentry->n_conflict_snapshot++;
6266                         break;
6267                 case PROCSIG_RECOVERY_CONFLICT_BUFFERPIN:
6268                         dbentry->n_conflict_bufferpin++;
6269                         break;
6270                 case PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK:
6271                         dbentry->n_conflict_startup_deadlock++;
6272                         break;
6273         }
6274 }
6275
6276 /* ----------
6277  * pgstat_recv_deadlock() -
6278  *
6279  *      Process a DEADLOCK message.
6280  * ----------
6281  */
6282 static void
6283 pgstat_recv_deadlock(PgStat_MsgDeadlock *msg, int len)
6284 {
6285         PgStat_StatDBEntry *dbentry;
6286
6287         dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
6288
6289         dbentry->n_deadlocks++;
6290 }
6291
6292 /* ----------
6293  * pgstat_recv_checksum_failure() -
6294  *
6295  *      Process a CHECKSUMFAILURE message.
6296  * ----------
6297  */
6298 static void
6299 pgstat_recv_checksum_failure(PgStat_MsgChecksumFailure *msg, int len)
6300 {
6301         PgStat_StatDBEntry *dbentry;
6302
6303         dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
6304
6305         dbentry->n_checksum_failures += msg->m_failurecount;
6306 }
6307
6308 /* ----------
6309  * pgstat_recv_tempfile() -
6310  *
6311  *      Process a TEMPFILE message.
6312  * ----------
6313  */
6314 static void
6315 pgstat_recv_tempfile(PgStat_MsgTempFile *msg, int len)
6316 {
6317         PgStat_StatDBEntry *dbentry;
6318
6319         dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
6320
6321         dbentry->n_temp_bytes += msg->m_filesize;
6322         dbentry->n_temp_files += 1;
6323 }
6324
6325 /* ----------
6326  * pgstat_recv_funcstat() -
6327  *
6328  *      Count what the backend has done.
6329  * ----------
6330  */
6331 static void
6332 pgstat_recv_funcstat(PgStat_MsgFuncstat *msg, int len)
6333 {
6334         PgStat_FunctionEntry *funcmsg = &(msg->m_entry[0]);
6335         PgStat_StatDBEntry *dbentry;
6336         PgStat_StatFuncEntry *funcentry;
6337         int                     i;
6338         bool            found;
6339
6340         dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
6341
6342         /*
6343          * Process all function entries in the message.
6344          */
6345         for (i = 0; i < msg->m_nentries; i++, funcmsg++)
6346         {
6347                 funcentry = (PgStat_StatFuncEntry *) hash_search(dbentry->functions,
6348                                                                                                                  (void *) &(funcmsg->f_id),
6349                                                                                                                  HASH_ENTER, &found);
6350
6351                 if (!found)
6352                 {
6353                         /*
6354                          * If it's a new function entry, initialize counters to the values
6355                          * we just got.
6356                          */
6357                         funcentry->f_numcalls = funcmsg->f_numcalls;
6358                         funcentry->f_total_time = funcmsg->f_total_time;
6359                         funcentry->f_self_time = funcmsg->f_self_time;
6360                 }
6361                 else
6362                 {
6363                         /*
6364                          * Otherwise add the values to the existing entry.
6365                          */
6366                         funcentry->f_numcalls += funcmsg->f_numcalls;
6367                         funcentry->f_total_time += funcmsg->f_total_time;
6368                         funcentry->f_self_time += funcmsg->f_self_time;
6369                 }
6370         }
6371 }
6372
6373 /* ----------
6374  * pgstat_recv_funcpurge() -
6375  *
6376  *      Arrange for dead function removal.
6377  * ----------
6378  */
6379 static void
6380 pgstat_recv_funcpurge(PgStat_MsgFuncpurge *msg, int len)
6381 {
6382         PgStat_StatDBEntry *dbentry;
6383         int                     i;
6384
6385         dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
6386
6387         /*
6388          * No need to purge if we don't even know the database.
6389          */
6390         if (!dbentry || !dbentry->functions)
6391                 return;
6392
6393         /*
6394          * Process all function entries in the message.
6395          */
6396         for (i = 0; i < msg->m_nentries; i++)
6397         {
6398                 /* Remove from hashtable if present; we don't care if it's not. */
6399                 (void) hash_search(dbentry->functions,
6400                                                    (void *) &(msg->m_functionid[i]),
6401                                                    HASH_REMOVE, NULL);
6402         }
6403 }
6404
6405 /* ----------
6406  * pgstat_write_statsfile_needed() -
6407  *
6408  *      Do we need to write out any stats files?
6409  * ----------
6410  */
6411 static bool
6412 pgstat_write_statsfile_needed(void)
6413 {
6414         if (pending_write_requests != NIL)
6415                 return true;
6416
6417         /* Everything was written recently */
6418         return false;
6419 }
6420
6421 /* ----------
6422  * pgstat_db_requested() -
6423  *
6424  *      Checks whether stats for a particular DB need to be written to a file.
6425  * ----------
6426  */
6427 static bool
6428 pgstat_db_requested(Oid databaseid)
6429 {
6430         /*
6431          * If any requests are outstanding at all, we should write the stats for
6432          * shared catalogs (the "database" with OID 0).  This ensures that
6433          * backends will see up-to-date stats for shared catalogs, even though
6434          * they send inquiry messages mentioning only their own DB.
6435          */
6436         if (databaseid == InvalidOid && pending_write_requests != NIL)
6437                 return true;
6438
6439         /* Search to see if there's an open request to write this database. */
6440         if (list_member_oid(pending_write_requests, databaseid))
6441                 return true;
6442
6443         return false;
6444 }
6445
6446 /*
6447  * Convert a potentially unsafely truncated activity string (see
6448  * PgBackendStatus.st_activity_raw's documentation) into a correctly truncated
6449  * one.
6450  *
6451  * The returned string is allocated in the caller's memory context and may be
6452  * freed.
6453  */
6454 char *
6455 pgstat_clip_activity(const char *raw_activity)
6456 {
6457         char       *activity;
6458         int                     rawlen;
6459         int                     cliplen;
6460
6461         /*
6462          * Some callers, like pgstat_get_backend_current_activity(), do not
6463          * guarantee that the buffer isn't concurrently modified. We try to take
6464          * care that the buffer is always terminated by a NUL byte regardless, but
6465          * let's still be paranoid about the string's length. In those cases the
6466          * underlying buffer is guaranteed to be pgstat_track_activity_query_size
6467          * large.
6468          */
6469         activity = pnstrdup(raw_activity, pgstat_track_activity_query_size - 1);
6470
6471         /* now double-guaranteed to be NUL terminated */
6472         rawlen = strlen(activity);
6473
6474         /*
6475          * All supported server-encodings make it possible to determine the length
6476          * of a multi-byte character from its first byte (this is not the case for
6477          * client encodings, see GB18030). As st_activity is always stored using
6478          * server encoding, this allows us to perform multi-byte aware truncation,
6479          * even if the string earlier was truncated in the middle of a multi-byte
6480          * character.
6481          */
6482         cliplen = pg_mbcliplen(activity, rawlen,
6483                                                    pgstat_track_activity_query_size - 1);
6484
6485         activity[cliplen] = '\0';
6486
6487         return activity;
6488 }