]> granicus.if.org Git - postgresql/blob - src/backend/postmaster/pgstat.c
Add views and functions to monitor hot standby query conflicts
[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-2011, 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_POLL_H
32 #include <poll.h>
33 #endif
34 #ifdef HAVE_SYS_POLL_H
35 #include <sys/poll.h>
36 #endif
37
38 #include "pgstat.h"
39
40 #include "access/heapam.h"
41 #include "access/transam.h"
42 #include "access/twophase_rmgr.h"
43 #include "access/xact.h"
44 #include "catalog/pg_database.h"
45 #include "catalog/pg_proc.h"
46 #include "libpq/ip.h"
47 #include "libpq/libpq.h"
48 #include "libpq/pqsignal.h"
49 #include "mb/pg_wchar.h"
50 #include "miscadmin.h"
51 #include "pg_trace.h"
52 #include "postmaster/autovacuum.h"
53 #include "postmaster/fork_process.h"
54 #include "postmaster/postmaster.h"
55 #include "storage/backendid.h"
56 #include "storage/fd.h"
57 #include "storage/ipc.h"
58 #include "storage/pg_shmem.h"
59 #include "storage/pmsignal.h"
60 #include "storage/procsignal.h"
61 #include "utils/guc.h"
62 #include "utils/memutils.h"
63 #include "utils/ps_status.h"
64 #include "utils/rel.h"
65 #include "utils/tqual.h"
66
67
68 /* ----------
69  * Paths for the statistics files (relative to installation's $PGDATA).
70  * ----------
71  */
72 #define PGSTAT_STAT_PERMANENT_FILENAME          "global/pgstat.stat"
73 #define PGSTAT_STAT_PERMANENT_TMPFILE           "global/pgstat.tmp"
74
75 /* ----------
76  * Timer definitions.
77  * ----------
78  */
79 #define PGSTAT_STAT_INTERVAL    500             /* Minimum time between stats file
80                                                                                  * updates; in milliseconds. */
81
82 #define PGSTAT_RETRY_DELAY              10              /* How long to wait between statistics
83                                                                                  * update requests; in milliseconds. */
84
85 #define PGSTAT_MAX_WAIT_TIME    5000    /* Maximum time to wait for a stats
86                                                                                  * file update; in milliseconds. */
87
88 #define PGSTAT_RESTART_INTERVAL 60              /* How often to attempt to restart a
89                                                                                  * failed statistics collector; in
90                                                                                  * seconds. */
91
92 #define PGSTAT_SELECT_TIMEOUT   2               /* How often to check for postmaster
93                                                                                  * death; in seconds. */
94
95 #define PGSTAT_POLL_LOOP_COUNT  (PGSTAT_MAX_WAIT_TIME / PGSTAT_RETRY_DELAY)
96
97
98 /* ----------
99  * The initial size hints for the hash tables used in the collector.
100  * ----------
101  */
102 #define PGSTAT_DB_HASH_SIZE             16
103 #define PGSTAT_TAB_HASH_SIZE    512
104 #define PGSTAT_FUNCTION_HASH_SIZE       512
105
106
107 /* ----------
108  * GUC parameters
109  * ----------
110  */
111 bool            pgstat_track_activities = false;
112 bool            pgstat_track_counts = false;
113 int                     pgstat_track_functions = TRACK_FUNC_OFF;
114 int                     pgstat_track_activity_query_size = 1024;
115
116 /* ----------
117  * Built from GUC parameter
118  * ----------
119  */
120 char       *pgstat_stat_filename = NULL;
121 char       *pgstat_stat_tmpname = NULL;
122
123 /*
124  * BgWriter global statistics counters (unused in other processes).
125  * Stored directly in a stats message structure so it can be sent
126  * without needing to copy things around.  We assume this inits to zeroes.
127  */
128 PgStat_MsgBgWriter BgWriterStats;
129
130 /* ----------
131  * Local data
132  * ----------
133  */
134 NON_EXEC_STATIC pgsocket pgStatSock = PGINVALID_SOCKET;
135
136 static struct sockaddr_storage pgStatAddr;
137
138 static time_t last_pgstat_start_time;
139
140 static bool pgStatRunningInCollector = false;
141
142 /*
143  * Structures in which backends store per-table info that's waiting to be
144  * sent to the collector.
145  *
146  * NOTE: once allocated, TabStatusArray structures are never moved or deleted
147  * for the life of the backend.  Also, we zero out the t_id fields of the
148  * contained PgStat_TableStatus structs whenever they are not actively in use.
149  * This allows relcache pgstat_info pointers to be treated as long-lived data,
150  * avoiding repeated searches in pgstat_initstats() when a relation is
151  * repeatedly opened during a transaction.
152  */
153 #define TABSTAT_QUANTUM         100 /* we alloc this many at a time */
154
155 typedef struct TabStatusArray
156 {
157         struct TabStatusArray *tsa_next;        /* link to next array, if any */
158         int                     tsa_used;               /* # entries currently used */
159         PgStat_TableStatus tsa_entries[TABSTAT_QUANTUM];        /* per-table data */
160 } TabStatusArray;
161
162 static TabStatusArray *pgStatTabList = NULL;
163
164 /*
165  * Backends store per-function info that's waiting to be sent to the collector
166  * in this hash table (indexed by function OID).
167  */
168 static HTAB *pgStatFunctions = NULL;
169
170 /*
171  * Indicates if backend has some function stats that it hasn't yet
172  * sent to the collector.
173  */
174 static bool have_function_stats = false;
175
176 /*
177  * Tuple insertion/deletion counts for an open transaction can't be propagated
178  * into PgStat_TableStatus counters until we know if it is going to commit
179  * or abort.  Hence, we keep these counts in per-subxact structs that live
180  * in TopTransactionContext.  This data structure is designed on the assumption
181  * that subxacts won't usually modify very many tables.
182  */
183 typedef struct PgStat_SubXactStatus
184 {
185         int                     nest_level;             /* subtransaction nest level */
186         struct PgStat_SubXactStatus *prev;      /* higher-level subxact if any */
187         PgStat_TableXactStatus *first;          /* head of list for this subxact */
188 } PgStat_SubXactStatus;
189
190 static PgStat_SubXactStatus *pgStatXactStack = NULL;
191
192 static int      pgStatXactCommit = 0;
193 static int      pgStatXactRollback = 0;
194
195 /* Record that's written to 2PC state file when pgstat state is persisted */
196 typedef struct TwoPhasePgStatRecord
197 {
198         PgStat_Counter tuples_inserted;         /* tuples inserted in xact */
199         PgStat_Counter tuples_updated;          /* tuples updated in xact */
200         PgStat_Counter tuples_deleted;          /* tuples deleted in xact */
201         Oid                     t_id;                   /* table's OID */
202         bool            t_shared;               /* is it a shared catalog? */
203 } TwoPhasePgStatRecord;
204
205 /*
206  * Info about current "snapshot" of stats file
207  */
208 static MemoryContext pgStatLocalContext = NULL;
209 static HTAB *pgStatDBHash = NULL;
210 static PgBackendStatus *localBackendStatusTable = NULL;
211 static int      localNumBackends = 0;
212
213 /*
214  * Cluster wide statistics, kept in the stats collector.
215  * Contains statistics that are not collected per database
216  * or per table.
217  */
218 static PgStat_GlobalStats globalStats;
219
220 /* Last time the collector successfully wrote the stats file */
221 static TimestampTz last_statwrite;
222
223 /* Latest statistics request time from backends */
224 static TimestampTz last_statrequest;
225
226 static volatile bool need_exit = false;
227 static volatile bool got_SIGHUP = false;
228
229 /*
230  * Total time charged to functions so far in the current backend.
231  * We use this to help separate "self" and "other" time charges.
232  * (We assume this initializes to zero.)
233  */
234 static instr_time total_func_time;
235
236
237 /* ----------
238  * Local function forward declarations
239  * ----------
240  */
241 #ifdef EXEC_BACKEND
242 static pid_t pgstat_forkexec(void);
243 #endif
244
245 NON_EXEC_STATIC void PgstatCollectorMain(int argc, char *argv[]);
246 static void pgstat_exit(SIGNAL_ARGS);
247 static void pgstat_beshutdown_hook(int code, Datum arg);
248 static void pgstat_sighup_handler(SIGNAL_ARGS);
249
250 static PgStat_StatDBEntry *pgstat_get_db_entry(Oid databaseid, bool create);
251 static PgStat_StatTabEntry *pgstat_get_tab_entry(PgStat_StatDBEntry *dbentry,
252                                          Oid tableoid, bool create);
253 static void pgstat_write_statsfile(bool permanent);
254 static HTAB *pgstat_read_statsfile(Oid onlydb, bool permanent);
255 static void backend_read_statsfile(void);
256 static void pgstat_read_current_status(void);
257
258 static void pgstat_send_tabstat(PgStat_MsgTabstat *tsmsg);
259 static void pgstat_send_funcstats(void);
260 static HTAB *pgstat_collect_oids(Oid catalogid);
261
262 static PgStat_TableStatus *get_tabstat_entry(Oid rel_id, bool isshared);
263
264 static void pgstat_setup_memcxt(void);
265
266 static void pgstat_setheader(PgStat_MsgHdr *hdr, StatMsgType mtype);
267 static void pgstat_send(void *msg, int len);
268
269 static void pgstat_recv_inquiry(PgStat_MsgInquiry *msg, int len);
270 static void pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len);
271 static void pgstat_recv_tabpurge(PgStat_MsgTabpurge *msg, int len);
272 static void pgstat_recv_dropdb(PgStat_MsgDropdb *msg, int len);
273 static void pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len);
274 static void pgstat_recv_resetsharedcounter(PgStat_MsgResetsharedcounter *msg, int len);
275 static void pgstat_recv_resetsinglecounter(PgStat_MsgResetsinglecounter *msg, int len);
276 static void pgstat_recv_autovac(PgStat_MsgAutovacStart *msg, int len);
277 static void pgstat_recv_vacuum(PgStat_MsgVacuum *msg, int len);
278 static void pgstat_recv_analyze(PgStat_MsgAnalyze *msg, int len);
279 static void pgstat_recv_bgwriter(PgStat_MsgBgWriter *msg, int len);
280 static void pgstat_recv_funcstat(PgStat_MsgFuncstat *msg, int len);
281 static void pgstat_recv_funcpurge(PgStat_MsgFuncpurge *msg, int len);
282 static void pgstat_recv_recoveryconflict(PgStat_MsgRecoveryConflict *msg, int len);
283
284
285 /* ------------------------------------------------------------
286  * Public functions called from postmaster follow
287  * ------------------------------------------------------------
288  */
289
290 /* ----------
291  * pgstat_init() -
292  *
293  *      Called from postmaster at startup. Create the resources required
294  *      by the statistics collector process.  If unable to do so, do not
295  *      fail --- better to let the postmaster start with stats collection
296  *      disabled.
297  * ----------
298  */
299 void
300 pgstat_init(void)
301 {
302         ACCEPT_TYPE_ARG3 alen;
303         struct addrinfo *addrs = NULL,
304                            *addr,
305                                 hints;
306         int                     ret;
307         fd_set          rset;
308         struct timeval tv;
309         char            test_byte;
310         int                     sel_res;
311         int                     tries = 0;
312
313 #define TESTBYTEVAL ((char) 199)
314
315         /*
316          * Create the UDP socket for sending and receiving statistic messages
317          */
318         hints.ai_flags = AI_PASSIVE;
319         hints.ai_family = PF_UNSPEC;
320         hints.ai_socktype = SOCK_DGRAM;
321         hints.ai_protocol = 0;
322         hints.ai_addrlen = 0;
323         hints.ai_addr = NULL;
324         hints.ai_canonname = NULL;
325         hints.ai_next = NULL;
326         ret = pg_getaddrinfo_all("localhost", NULL, &hints, &addrs);
327         if (ret || !addrs)
328         {
329                 ereport(LOG,
330                                 (errmsg("could not resolve \"localhost\": %s",
331                                                 gai_strerror(ret))));
332                 goto startup_failed;
333         }
334
335         /*
336          * On some platforms, pg_getaddrinfo_all() may return multiple addresses
337          * only one of which will actually work (eg, both IPv6 and IPv4 addresses
338          * when kernel will reject IPv6).  Worse, the failure may occur at the
339          * bind() or perhaps even connect() stage.      So we must loop through the
340          * results till we find a working combination. We will generate LOG
341          * messages, but no error, for bogus combinations.
342          */
343         for (addr = addrs; addr; addr = addr->ai_next)
344         {
345 #ifdef HAVE_UNIX_SOCKETS
346                 /* Ignore AF_UNIX sockets, if any are returned. */
347                 if (addr->ai_family == AF_UNIX)
348                         continue;
349 #endif
350
351                 if (++tries > 1)
352                         ereport(LOG,
353                         (errmsg("trying another address for the statistics collector")));
354
355                 /*
356                  * Create the socket.
357                  */
358                 if ((pgStatSock = socket(addr->ai_family, SOCK_DGRAM, 0)) == PGINVALID_SOCKET)
359                 {
360                         ereport(LOG,
361                                         (errcode_for_socket_access(),
362                         errmsg("could not create socket for statistics collector: %m")));
363                         continue;
364                 }
365
366                 /*
367                  * Bind it to a kernel assigned port on localhost and get the assigned
368                  * port via getsockname().
369                  */
370                 if (bind(pgStatSock, addr->ai_addr, addr->ai_addrlen) < 0)
371                 {
372                         ereport(LOG,
373                                         (errcode_for_socket_access(),
374                           errmsg("could not bind socket for statistics collector: %m")));
375                         closesocket(pgStatSock);
376                         pgStatSock = PGINVALID_SOCKET;
377                         continue;
378                 }
379
380                 alen = sizeof(pgStatAddr);
381                 if (getsockname(pgStatSock, (struct sockaddr *) & pgStatAddr, &alen) < 0)
382                 {
383                         ereport(LOG,
384                                         (errcode_for_socket_access(),
385                                          errmsg("could not get address of socket for statistics collector: %m")));
386                         closesocket(pgStatSock);
387                         pgStatSock = PGINVALID_SOCKET;
388                         continue;
389                 }
390
391                 /*
392                  * Connect the socket to its own address.  This saves a few cycles by
393                  * not having to respecify the target address on every send. This also
394                  * provides a kernel-level check that only packets from this same
395                  * address will be received.
396                  */
397                 if (connect(pgStatSock, (struct sockaddr *) & pgStatAddr, alen) < 0)
398                 {
399                         ereport(LOG,
400                                         (errcode_for_socket_access(),
401                         errmsg("could not connect socket for statistics collector: %m")));
402                         closesocket(pgStatSock);
403                         pgStatSock = PGINVALID_SOCKET;
404                         continue;
405                 }
406
407                 /*
408                  * Try to send and receive a one-byte test message on the socket. This
409                  * is to catch situations where the socket can be created but will not
410                  * actually pass data (for instance, because kernel packet filtering
411                  * rules prevent it).
412                  */
413                 test_byte = TESTBYTEVAL;
414
415 retry1:
416                 if (send(pgStatSock, &test_byte, 1, 0) != 1)
417                 {
418                         if (errno == EINTR)
419                                 goto retry1;    /* if interrupted, just retry */
420                         ereport(LOG,
421                                         (errcode_for_socket_access(),
422                                          errmsg("could not send test message on socket for statistics collector: %m")));
423                         closesocket(pgStatSock);
424                         pgStatSock = PGINVALID_SOCKET;
425                         continue;
426                 }
427
428                 /*
429                  * There could possibly be a little delay before the message can be
430                  * received.  We arbitrarily allow up to half a second before deciding
431                  * it's broken.
432                  */
433                 for (;;)                                /* need a loop to handle EINTR */
434                 {
435                         FD_ZERO(&rset);
436                         FD_SET(pgStatSock, &rset);
437
438                         tv.tv_sec = 0;
439                         tv.tv_usec = 500000;
440                         sel_res = select(pgStatSock + 1, &rset, NULL, NULL, &tv);
441                         if (sel_res >= 0 || errno != EINTR)
442                                 break;
443                 }
444                 if (sel_res < 0)
445                 {
446                         ereport(LOG,
447                                         (errcode_for_socket_access(),
448                                          errmsg("select() failed in statistics collector: %m")));
449                         closesocket(pgStatSock);
450                         pgStatSock = PGINVALID_SOCKET;
451                         continue;
452                 }
453                 if (sel_res == 0 || !FD_ISSET(pgStatSock, &rset))
454                 {
455                         /*
456                          * This is the case we actually think is likely, so take pains to
457                          * give a specific message for it.
458                          *
459                          * errno will not be set meaningfully here, so don't use it.
460                          */
461                         ereport(LOG,
462                                         (errcode(ERRCODE_CONNECTION_FAILURE),
463                                          errmsg("test message did not get through on socket for statistics collector")));
464                         closesocket(pgStatSock);
465                         pgStatSock = PGINVALID_SOCKET;
466                         continue;
467                 }
468
469                 test_byte++;                    /* just make sure variable is changed */
470
471 retry2:
472                 if (recv(pgStatSock, &test_byte, 1, 0) != 1)
473                 {
474                         if (errno == EINTR)
475                                 goto retry2;    /* if interrupted, just retry */
476                         ereport(LOG,
477                                         (errcode_for_socket_access(),
478                                          errmsg("could not receive test message on socket for statistics collector: %m")));
479                         closesocket(pgStatSock);
480                         pgStatSock = PGINVALID_SOCKET;
481                         continue;
482                 }
483
484                 if (test_byte != TESTBYTEVAL)   /* strictly paranoia ... */
485                 {
486                         ereport(LOG,
487                                         (errcode(ERRCODE_INTERNAL_ERROR),
488                                          errmsg("incorrect test message transmission on socket for statistics collector")));
489                         closesocket(pgStatSock);
490                         pgStatSock = PGINVALID_SOCKET;
491                         continue;
492                 }
493
494                 /* If we get here, we have a working socket */
495                 break;
496         }
497
498         /* Did we find a working address? */
499         if (!addr || pgStatSock == PGINVALID_SOCKET)
500                 goto startup_failed;
501
502         /*
503          * Set the socket to non-blocking IO.  This ensures that if the collector
504          * falls behind, statistics messages will be discarded; backends won't
505          * block waiting to send messages to the collector.
506          */
507         if (!pg_set_noblock(pgStatSock))
508         {
509                 ereport(LOG,
510                                 (errcode_for_socket_access(),
511                                  errmsg("could not set statistics collector socket to nonblocking mode: %m")));
512                 goto startup_failed;
513         }
514
515         pg_freeaddrinfo_all(hints.ai_family, addrs);
516
517         return;
518
519 startup_failed:
520         ereport(LOG,
521           (errmsg("disabling statistics collector for lack of working socket")));
522
523         if (addrs)
524                 pg_freeaddrinfo_all(hints.ai_family, addrs);
525
526         if (pgStatSock != PGINVALID_SOCKET)
527                 closesocket(pgStatSock);
528         pgStatSock = PGINVALID_SOCKET;
529
530         /*
531          * Adjust GUC variables to suppress useless activity, and for debugging
532          * purposes (seeing track_counts off is a clue that we failed here). We
533          * use PGC_S_OVERRIDE because there is no point in trying to turn it back
534          * on from postgresql.conf without a restart.
535          */
536         SetConfigOption("track_counts", "off", PGC_INTERNAL, PGC_S_OVERRIDE);
537 }
538
539 /*
540  * pgstat_reset_all() -
541  *
542  * Remove the stats file.  This is currently used only if WAL
543  * recovery is needed after a crash.
544  */
545 void
546 pgstat_reset_all(void)
547 {
548         unlink(pgstat_stat_filename);
549         unlink(PGSTAT_STAT_PERMANENT_FILENAME);
550 }
551
552 #ifdef EXEC_BACKEND
553
554 /*
555  * pgstat_forkexec() -
556  *
557  * Format up the arglist for, then fork and exec, statistics collector process
558  */
559 static pid_t
560 pgstat_forkexec(void)
561 {
562         char       *av[10];
563         int                     ac = 0;
564
565         av[ac++] = "postgres";
566         av[ac++] = "--forkcol";
567         av[ac++] = NULL;                        /* filled in by postmaster_forkexec */
568
569         av[ac] = NULL;
570         Assert(ac < lengthof(av));
571
572         return postmaster_forkexec(ac, av);
573 }
574 #endif   /* EXEC_BACKEND */
575
576
577 /*
578  * pgstat_start() -
579  *
580  *      Called from postmaster at startup or after an existing collector
581  *      died.  Attempt to fire up a fresh statistics collector.
582  *
583  *      Returns PID of child process, or 0 if fail.
584  *
585  *      Note: if fail, we will be called again from the postmaster main loop.
586  */
587 int
588 pgstat_start(void)
589 {
590         time_t          curtime;
591         pid_t           pgStatPid;
592
593         /*
594          * Check that the socket is there, else pgstat_init failed and we can do
595          * nothing useful.
596          */
597         if (pgStatSock == PGINVALID_SOCKET)
598                 return 0;
599
600         /*
601          * Do nothing if too soon since last collector start.  This is a safety
602          * valve to protect against continuous respawn attempts if the collector
603          * is dying immediately at launch.      Note that since we will be re-called
604          * from the postmaster main loop, we will get another chance later.
605          */
606         curtime = time(NULL);
607         if ((unsigned int) (curtime - last_pgstat_start_time) <
608                 (unsigned int) PGSTAT_RESTART_INTERVAL)
609                 return 0;
610         last_pgstat_start_time = curtime;
611
612         /*
613          * Okay, fork off the collector.
614          */
615 #ifdef EXEC_BACKEND
616         switch ((pgStatPid = pgstat_forkexec()))
617 #else
618         switch ((pgStatPid = fork_process()))
619 #endif
620         {
621                 case -1:
622                         ereport(LOG,
623                                         (errmsg("could not fork statistics collector: %m")));
624                         return 0;
625
626 #ifndef EXEC_BACKEND
627                 case 0:
628                         /* in postmaster child ... */
629                         /* Close the postmaster's sockets */
630                         ClosePostmasterPorts(false);
631
632                         /* Lose the postmaster's on-exit routines */
633                         on_exit_reset();
634
635                         /* Drop our connection to postmaster's shared memory, as well */
636                         PGSharedMemoryDetach();
637
638                         PgstatCollectorMain(0, NULL);
639                         break;
640 #endif
641
642                 default:
643                         return (int) pgStatPid;
644         }
645
646         /* shouldn't get here */
647         return 0;
648 }
649
650 void
651 allow_immediate_pgstat_restart(void)
652 {
653         last_pgstat_start_time = 0;
654 }
655
656 /* ------------------------------------------------------------
657  * Public functions used by backends follow
658  *------------------------------------------------------------
659  */
660
661
662 /* ----------
663  * pgstat_report_stat() -
664  *
665  *      Called from tcop/postgres.c to send the so far collected per-table
666  *      and function usage statistics to the collector.  Note that this is
667  *      called only when not within a transaction, so it is fair to use
668  *      transaction stop time as an approximation of current time.
669  * ----------
670  */
671 void
672 pgstat_report_stat(bool force)
673 {
674         /* we assume this inits to all zeroes: */
675         static const PgStat_TableCounts all_zeroes;
676         static TimestampTz last_report = 0;
677
678         TimestampTz now;
679         PgStat_MsgTabstat regular_msg;
680         PgStat_MsgTabstat shared_msg;
681         TabStatusArray *tsa;
682         int                     i;
683
684         /* Don't expend a clock check if nothing to do */
685         if ((pgStatTabList == NULL || pgStatTabList->tsa_used == 0)
686                 && !have_function_stats)
687                 return;
688
689         /*
690          * Don't send a message unless it's been at least PGSTAT_STAT_INTERVAL
691          * msec since we last sent one, or the caller wants to force stats out.
692          */
693         now = GetCurrentTransactionStopTimestamp();
694         if (!force &&
695                 !TimestampDifferenceExceeds(last_report, now, PGSTAT_STAT_INTERVAL))
696                 return;
697         last_report = now;
698
699         /*
700          * Scan through the TabStatusArray struct(s) to find tables that actually
701          * have counts, and build messages to send.  We have to separate shared
702          * relations from regular ones because the databaseid field in the message
703          * header has to depend on that.
704          */
705         regular_msg.m_databaseid = MyDatabaseId;
706         shared_msg.m_databaseid = InvalidOid;
707         regular_msg.m_nentries = 0;
708         shared_msg.m_nentries = 0;
709
710         for (tsa = pgStatTabList; tsa != NULL; tsa = tsa->tsa_next)
711         {
712                 for (i = 0; i < tsa->tsa_used; i++)
713                 {
714                         PgStat_TableStatus *entry = &tsa->tsa_entries[i];
715                         PgStat_MsgTabstat *this_msg;
716                         PgStat_TableEntry *this_ent;
717
718                         /* Shouldn't have any pending transaction-dependent counts */
719                         Assert(entry->trans == NULL);
720
721                         /*
722                          * Ignore entries that didn't accumulate any actual counts, such
723                          * as indexes that were opened by the planner but not used.
724                          */
725                         if (memcmp(&entry->t_counts, &all_zeroes,
726                                            sizeof(PgStat_TableCounts)) == 0)
727                                 continue;
728
729                         /*
730                          * OK, insert data into the appropriate message, and send if full.
731                          */
732                         this_msg = entry->t_shared ? &shared_msg : &regular_msg;
733                         this_ent = &this_msg->m_entry[this_msg->m_nentries];
734                         this_ent->t_id = entry->t_id;
735                         memcpy(&this_ent->t_counts, &entry->t_counts,
736                                    sizeof(PgStat_TableCounts));
737                         if (++this_msg->m_nentries >= PGSTAT_NUM_TABENTRIES)
738                         {
739                                 pgstat_send_tabstat(this_msg);
740                                 this_msg->m_nentries = 0;
741                         }
742                 }
743                 /* zero out TableStatus structs after use */
744                 MemSet(tsa->tsa_entries, 0,
745                            tsa->tsa_used * sizeof(PgStat_TableStatus));
746                 tsa->tsa_used = 0;
747         }
748
749         /*
750          * Send partial messages.  If force is true, make sure that any pending
751          * xact commit/abort gets counted, even if no table stats to send.
752          */
753         if (regular_msg.m_nentries > 0 ||
754                 (force && (pgStatXactCommit > 0 || pgStatXactRollback > 0)))
755                 pgstat_send_tabstat(&regular_msg);
756         if (shared_msg.m_nentries > 0)
757                 pgstat_send_tabstat(&shared_msg);
758
759         /* Now, send function statistics */
760         pgstat_send_funcstats();
761 }
762
763 /*
764  * Subroutine for pgstat_report_stat: finish and send a tabstat message
765  */
766 static void
767 pgstat_send_tabstat(PgStat_MsgTabstat *tsmsg)
768 {
769         int                     n;
770         int                     len;
771
772         /* It's unlikely we'd get here with no socket, but maybe not impossible */
773         if (pgStatSock == PGINVALID_SOCKET)
774                 return;
775
776         /*
777          * Report accumulated xact commit/rollback whenever we send a normal
778          * tabstat message
779          */
780         if (OidIsValid(tsmsg->m_databaseid))
781         {
782                 tsmsg->m_xact_commit = pgStatXactCommit;
783                 tsmsg->m_xact_rollback = pgStatXactRollback;
784                 pgStatXactCommit = 0;
785                 pgStatXactRollback = 0;
786         }
787         else
788         {
789                 tsmsg->m_xact_commit = 0;
790                 tsmsg->m_xact_rollback = 0;
791         }
792
793         n = tsmsg->m_nentries;
794         len = offsetof(PgStat_MsgTabstat, m_entry[0]) +
795                 n * sizeof(PgStat_TableEntry);
796
797         pgstat_setheader(&tsmsg->m_hdr, PGSTAT_MTYPE_TABSTAT);
798         pgstat_send(tsmsg, len);
799 }
800
801 /*
802  * Subroutine for pgstat_report_stat: populate and send a function stat message
803  */
804 static void
805 pgstat_send_funcstats(void)
806 {
807         /* we assume this inits to all zeroes: */
808         static const PgStat_FunctionCounts all_zeroes;
809
810         PgStat_MsgFuncstat msg;
811         PgStat_BackendFunctionEntry *entry;
812         HASH_SEQ_STATUS fstat;
813
814         if (pgStatFunctions == NULL)
815                 return;
816
817         pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_FUNCSTAT);
818         msg.m_databaseid = MyDatabaseId;
819         msg.m_nentries = 0;
820
821         hash_seq_init(&fstat, pgStatFunctions);
822         while ((entry = (PgStat_BackendFunctionEntry *) hash_seq_search(&fstat)) != NULL)
823         {
824                 PgStat_FunctionEntry *m_ent;
825
826                 /* Skip it if no counts accumulated since last time */
827                 if (memcmp(&entry->f_counts, &all_zeroes,
828                                    sizeof(PgStat_FunctionCounts)) == 0)
829                         continue;
830
831                 /* need to convert format of time accumulators */
832                 m_ent = &msg.m_entry[msg.m_nentries];
833                 m_ent->f_id = entry->f_id;
834                 m_ent->f_numcalls = entry->f_counts.f_numcalls;
835                 m_ent->f_time = INSTR_TIME_GET_MICROSEC(entry->f_counts.f_time);
836                 m_ent->f_time_self = INSTR_TIME_GET_MICROSEC(entry->f_counts.f_time_self);
837
838                 if (++msg.m_nentries >= PGSTAT_NUM_FUNCENTRIES)
839                 {
840                         pgstat_send(&msg, offsetof(PgStat_MsgFuncstat, m_entry[0]) +
841                                                 msg.m_nentries * sizeof(PgStat_FunctionEntry));
842                         msg.m_nentries = 0;
843                 }
844
845                 /* reset the entry's counts */
846                 MemSet(&entry->f_counts, 0, sizeof(PgStat_FunctionCounts));
847         }
848
849         if (msg.m_nentries > 0)
850                 pgstat_send(&msg, offsetof(PgStat_MsgFuncstat, m_entry[0]) +
851                                         msg.m_nentries * sizeof(PgStat_FunctionEntry));
852
853         have_function_stats = false;
854 }
855
856
857 /* ----------
858  * pgstat_vacuum_stat() -
859  *
860  *      Will tell the collector about objects he can get rid of.
861  * ----------
862  */
863 void
864 pgstat_vacuum_stat(void)
865 {
866         HTAB       *htab;
867         PgStat_MsgTabpurge msg;
868         PgStat_MsgFuncpurge f_msg;
869         HASH_SEQ_STATUS hstat;
870         PgStat_StatDBEntry *dbentry;
871         PgStat_StatTabEntry *tabentry;
872         PgStat_StatFuncEntry *funcentry;
873         int                     len;
874
875         if (pgStatSock == PGINVALID_SOCKET)
876                 return;
877
878         /*
879          * If not done for this transaction, read the statistics collector stats
880          * file into some hash tables.
881          */
882         backend_read_statsfile();
883
884         /*
885          * Read pg_database and make a list of OIDs of all existing databases
886          */
887         htab = pgstat_collect_oids(DatabaseRelationId);
888
889         /*
890          * Search the database hash table for dead databases and tell the
891          * collector to drop them.
892          */
893         hash_seq_init(&hstat, pgStatDBHash);
894         while ((dbentry = (PgStat_StatDBEntry *) hash_seq_search(&hstat)) != NULL)
895         {
896                 Oid                     dbid = dbentry->databaseid;
897
898                 CHECK_FOR_INTERRUPTS();
899
900                 /* the DB entry for shared tables (with InvalidOid) is never dropped */
901                 if (OidIsValid(dbid) &&
902                         hash_search(htab, (void *) &dbid, HASH_FIND, NULL) == NULL)
903                         pgstat_drop_database(dbid);
904         }
905
906         /* Clean up */
907         hash_destroy(htab);
908
909         /*
910          * Lookup our own database entry; if not found, nothing more to do.
911          */
912         dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
913                                                                                                  (void *) &MyDatabaseId,
914                                                                                                  HASH_FIND, NULL);
915         if (dbentry == NULL || dbentry->tables == NULL)
916                 return;
917
918         /*
919          * Similarly to above, make a list of all known relations in this DB.
920          */
921         htab = pgstat_collect_oids(RelationRelationId);
922
923         /*
924          * Initialize our messages table counter to zero
925          */
926         msg.m_nentries = 0;
927
928         /*
929          * Check for all tables listed in stats hashtable if they still exist.
930          */
931         hash_seq_init(&hstat, dbentry->tables);
932         while ((tabentry = (PgStat_StatTabEntry *) hash_seq_search(&hstat)) != NULL)
933         {
934                 Oid                     tabid = tabentry->tableid;
935
936                 CHECK_FOR_INTERRUPTS();
937
938                 if (hash_search(htab, (void *) &tabid, HASH_FIND, NULL) != NULL)
939                         continue;
940
941                 /*
942                  * Not there, so add this table's Oid to the message
943                  */
944                 msg.m_tableid[msg.m_nentries++] = tabid;
945
946                 /*
947                  * If the message is full, send it out and reinitialize to empty
948                  */
949                 if (msg.m_nentries >= PGSTAT_NUM_TABPURGE)
950                 {
951                         len = offsetof(PgStat_MsgTabpurge, m_tableid[0])
952                                 +msg.m_nentries * sizeof(Oid);
953
954                         pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
955                         msg.m_databaseid = MyDatabaseId;
956                         pgstat_send(&msg, len);
957
958                         msg.m_nentries = 0;
959                 }
960         }
961
962         /*
963          * Send the rest
964          */
965         if (msg.m_nentries > 0)
966         {
967                 len = offsetof(PgStat_MsgTabpurge, m_tableid[0])
968                         +msg.m_nentries * sizeof(Oid);
969
970                 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
971                 msg.m_databaseid = MyDatabaseId;
972                 pgstat_send(&msg, len);
973         }
974
975         /* Clean up */
976         hash_destroy(htab);
977
978         /*
979          * Now repeat the above steps for functions.  However, we needn't bother
980          * in the common case where no function stats are being collected.
981          */
982         if (dbentry->functions != NULL &&
983                 hash_get_num_entries(dbentry->functions) > 0)
984         {
985                 htab = pgstat_collect_oids(ProcedureRelationId);
986
987                 pgstat_setheader(&f_msg.m_hdr, PGSTAT_MTYPE_FUNCPURGE);
988                 f_msg.m_databaseid = MyDatabaseId;
989                 f_msg.m_nentries = 0;
990
991                 hash_seq_init(&hstat, dbentry->functions);
992                 while ((funcentry = (PgStat_StatFuncEntry *) hash_seq_search(&hstat)) != NULL)
993                 {
994                         Oid                     funcid = funcentry->functionid;
995
996                         CHECK_FOR_INTERRUPTS();
997
998                         if (hash_search(htab, (void *) &funcid, HASH_FIND, NULL) != NULL)
999                                 continue;
1000
1001                         /*
1002                          * Not there, so add this function's Oid to the message
1003                          */
1004                         f_msg.m_functionid[f_msg.m_nentries++] = funcid;
1005
1006                         /*
1007                          * If the message is full, send it out and reinitialize to empty
1008                          */
1009                         if (f_msg.m_nentries >= PGSTAT_NUM_FUNCPURGE)
1010                         {
1011                                 len = offsetof(PgStat_MsgFuncpurge, m_functionid[0])
1012                                         +f_msg.m_nentries * sizeof(Oid);
1013
1014                                 pgstat_send(&f_msg, len);
1015
1016                                 f_msg.m_nentries = 0;
1017                         }
1018                 }
1019
1020                 /*
1021                  * Send the rest
1022                  */
1023                 if (f_msg.m_nentries > 0)
1024                 {
1025                         len = offsetof(PgStat_MsgFuncpurge, m_functionid[0])
1026                                 +f_msg.m_nentries * sizeof(Oid);
1027
1028                         pgstat_send(&f_msg, len);
1029                 }
1030
1031                 hash_destroy(htab);
1032         }
1033 }
1034
1035
1036 /* ----------
1037  * pgstat_collect_oids() -
1038  *
1039  *      Collect the OIDs of all objects listed in the specified system catalog
1040  *      into a temporary hash table.  Caller should hash_destroy the result
1041  *      when done with it.      (However, we make the table in CurrentMemoryContext
1042  *      so that it will be freed properly in event of an error.)
1043  * ----------
1044  */
1045 static HTAB *
1046 pgstat_collect_oids(Oid catalogid)
1047 {
1048         HTAB       *htab;
1049         HASHCTL         hash_ctl;
1050         Relation        rel;
1051         HeapScanDesc scan;
1052         HeapTuple       tup;
1053
1054         memset(&hash_ctl, 0, sizeof(hash_ctl));
1055         hash_ctl.keysize = sizeof(Oid);
1056         hash_ctl.entrysize = sizeof(Oid);
1057         hash_ctl.hash = oid_hash;
1058         hash_ctl.hcxt = CurrentMemoryContext;
1059         htab = hash_create("Temporary table of OIDs",
1060                                            PGSTAT_TAB_HASH_SIZE,
1061                                            &hash_ctl,
1062                                            HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT);
1063
1064         rel = heap_open(catalogid, AccessShareLock);
1065         scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
1066         while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
1067         {
1068                 Oid                     thisoid = HeapTupleGetOid(tup);
1069
1070                 CHECK_FOR_INTERRUPTS();
1071
1072                 (void) hash_search(htab, (void *) &thisoid, HASH_ENTER, NULL);
1073         }
1074         heap_endscan(scan);
1075         heap_close(rel, AccessShareLock);
1076
1077         return htab;
1078 }
1079
1080
1081 /* ----------
1082  * pgstat_drop_database() -
1083  *
1084  *      Tell the collector that we just dropped a database.
1085  *      (If the message gets lost, we will still clean the dead DB eventually
1086  *      via future invocations of pgstat_vacuum_stat().)
1087  * ----------
1088  */
1089 void
1090 pgstat_drop_database(Oid databaseid)
1091 {
1092         PgStat_MsgDropdb msg;
1093
1094         if (pgStatSock == PGINVALID_SOCKET)
1095                 return;
1096
1097         pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_DROPDB);
1098         msg.m_databaseid = databaseid;
1099         pgstat_send(&msg, sizeof(msg));
1100 }
1101
1102
1103 /* ----------
1104  * pgstat_drop_relation() -
1105  *
1106  *      Tell the collector that we just dropped a relation.
1107  *      (If the message gets lost, we will still clean the dead entry eventually
1108  *      via future invocations of pgstat_vacuum_stat().)
1109  *
1110  *      Currently not used for lack of any good place to call it; we rely
1111  *      entirely on pgstat_vacuum_stat() to clean out stats for dead rels.
1112  * ----------
1113  */
1114 #ifdef NOT_USED
1115 void
1116 pgstat_drop_relation(Oid relid)
1117 {
1118         PgStat_MsgTabpurge msg;
1119         int                     len;
1120
1121         if (pgStatSock == PGINVALID_SOCKET)
1122                 return;
1123
1124         msg.m_tableid[0] = relid;
1125         msg.m_nentries = 1;
1126
1127         len = offsetof(PgStat_MsgTabpurge, m_tableid[0]) +sizeof(Oid);
1128
1129         pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
1130         msg.m_databaseid = MyDatabaseId;
1131         pgstat_send(&msg, len);
1132 }
1133 #endif   /* NOT_USED */
1134
1135
1136 /* ----------
1137  * pgstat_reset_counters() -
1138  *
1139  *      Tell the statistics collector to reset counters for our database.
1140  * ----------
1141  */
1142 void
1143 pgstat_reset_counters(void)
1144 {
1145         PgStat_MsgResetcounter msg;
1146
1147         if (pgStatSock == PGINVALID_SOCKET)
1148                 return;
1149
1150         if (!superuser())
1151                 ereport(ERROR,
1152                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1153                                  errmsg("must be superuser to reset statistics counters")));
1154
1155         pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RESETCOUNTER);
1156         msg.m_databaseid = MyDatabaseId;
1157         pgstat_send(&msg, sizeof(msg));
1158 }
1159
1160 /* ----------
1161  * pgstat_reset_shared_counters() -
1162  *
1163  *      Tell the statistics collector to reset cluster-wide shared counters.
1164  * ----------
1165  */
1166 void
1167 pgstat_reset_shared_counters(const char *target)
1168 {
1169         PgStat_MsgResetsharedcounter msg;
1170
1171         if (pgStatSock == PGINVALID_SOCKET)
1172                 return;
1173
1174         if (!superuser())
1175                 ereport(ERROR,
1176                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1177                                  errmsg("must be superuser to reset statistics counters")));
1178
1179         if (strcmp(target, "bgwriter") == 0)
1180                 msg.m_resettarget = RESET_BGWRITER;
1181         else
1182                 ereport(ERROR,
1183                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1184                                  errmsg("unrecognized reset target: \"%s\"", target),
1185                                  errhint("Target must be \"bgwriter\".")));
1186
1187         pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RESETSHAREDCOUNTER);
1188         pgstat_send(&msg, sizeof(msg));
1189 }
1190
1191 /* ----------
1192  * pgstat_reset_single_counter() -
1193  *
1194  *      Tell the statistics collector to reset a single counter.
1195  * ----------
1196  */
1197 void
1198 pgstat_reset_single_counter(Oid objoid, PgStat_Single_Reset_Type type)
1199 {
1200         PgStat_MsgResetsinglecounter msg;
1201
1202         if (pgStatSock == PGINVALID_SOCKET)
1203                 return;
1204
1205         if (!superuser())
1206                 ereport(ERROR,
1207                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1208                                  errmsg("must be superuser to reset statistics counters")));
1209
1210         pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RESETSINGLECOUNTER);
1211         msg.m_databaseid = MyDatabaseId;
1212         msg.m_resettype = type;
1213         msg.m_objectid = objoid;
1214
1215         pgstat_send(&msg, sizeof(msg));
1216 }
1217
1218 /* ----------
1219  * pgstat_report_autovac() -
1220  *
1221  *      Called from autovacuum.c to report startup of an autovacuum process.
1222  *      We are called before InitPostgres is done, so can't rely on MyDatabaseId;
1223  *      the db OID must be passed in, instead.
1224  * ----------
1225  */
1226 void
1227 pgstat_report_autovac(Oid dboid)
1228 {
1229         PgStat_MsgAutovacStart msg;
1230
1231         if (pgStatSock == PGINVALID_SOCKET)
1232                 return;
1233
1234         pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_AUTOVAC_START);
1235         msg.m_databaseid = dboid;
1236         msg.m_start_time = GetCurrentTimestamp();
1237
1238         pgstat_send(&msg, sizeof(msg));
1239 }
1240
1241
1242 /* ---------
1243  * pgstat_report_vacuum() -
1244  *
1245  *      Tell the collector about the table we just vacuumed.
1246  * ---------
1247  */
1248 void
1249 pgstat_report_vacuum(Oid tableoid, bool shared, bool adopt_counts,
1250                                          PgStat_Counter tuples)
1251 {
1252         PgStat_MsgVacuum msg;
1253
1254         if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
1255                 return;
1256
1257         pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_VACUUM);
1258         msg.m_databaseid = shared ? InvalidOid : MyDatabaseId;
1259         msg.m_tableoid = tableoid;
1260         msg.m_adopt_counts = adopt_counts;
1261         msg.m_autovacuum = IsAutoVacuumWorkerProcess();
1262         msg.m_vacuumtime = GetCurrentTimestamp();
1263         msg.m_tuples = tuples;
1264         pgstat_send(&msg, sizeof(msg));
1265 }
1266
1267 /* --------
1268  * pgstat_report_analyze() -
1269  *
1270  *      Tell the collector about the table we just analyzed.
1271  * --------
1272  */
1273 void
1274 pgstat_report_analyze(Relation rel, bool adopt_counts,
1275                                           PgStat_Counter livetuples, PgStat_Counter deadtuples)
1276 {
1277         PgStat_MsgAnalyze msg;
1278
1279         if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
1280                 return;
1281
1282         /*
1283          * Unlike VACUUM, ANALYZE might be running inside a transaction that has
1284          * already inserted and/or deleted rows in the target table. ANALYZE will
1285          * have counted such rows as live or dead respectively. Because we will
1286          * report our counts of such rows at transaction end, we should subtract
1287          * off these counts from what we send to the collector now, else they'll
1288          * be double-counted after commit.      (This approach also ensures that the
1289          * collector ends up with the right numbers if we abort instead of
1290          * committing.)
1291          */
1292         if (rel->pgstat_info != NULL)
1293         {
1294                 PgStat_TableXactStatus *trans;
1295
1296                 for (trans = rel->pgstat_info->trans; trans; trans = trans->upper)
1297                 {
1298                         livetuples -= trans->tuples_inserted - trans->tuples_deleted;
1299                         deadtuples -= trans->tuples_updated + trans->tuples_deleted;
1300                 }
1301                 /* count stuff inserted by already-aborted subxacts, too */
1302                 deadtuples -= rel->pgstat_info->t_counts.t_delta_dead_tuples;
1303                 /* Since ANALYZE's counts are estimates, we could have underflowed */
1304                 livetuples = Max(livetuples, 0);
1305                 deadtuples = Max(deadtuples, 0);
1306         }
1307
1308         pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_ANALYZE);
1309         msg.m_databaseid = rel->rd_rel->relisshared ? InvalidOid : MyDatabaseId;
1310         msg.m_tableoid = RelationGetRelid(rel);
1311         msg.m_adopt_counts = adopt_counts;
1312         msg.m_autovacuum = IsAutoVacuumWorkerProcess();
1313         msg.m_analyzetime = GetCurrentTimestamp();
1314         msg.m_live_tuples = livetuples;
1315         msg.m_dead_tuples = deadtuples;
1316         pgstat_send(&msg, sizeof(msg));
1317 }
1318
1319 /* --------
1320  * pgstat_report_recovery_conflict() -
1321  *
1322  *  Tell the collector about a Hot Standby recovery conflict.
1323  * --------
1324  */
1325 void
1326 pgstat_report_recovery_conflict(int reason)
1327 {
1328         PgStat_MsgRecoveryConflict msg;
1329
1330         if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
1331                 return;
1332
1333         pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RECOVERYCONFLICT);
1334         msg.m_databaseid = MyDatabaseId;
1335         msg.m_reason = reason;
1336         pgstat_send(&msg, sizeof(msg));
1337 }
1338
1339 /* ----------
1340  * pgstat_ping() -
1341  *
1342  *      Send some junk data to the collector to increase traffic.
1343  * ----------
1344  */
1345 void
1346 pgstat_ping(void)
1347 {
1348         PgStat_MsgDummy msg;
1349
1350         if (pgStatSock == PGINVALID_SOCKET)
1351                 return;
1352
1353         pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_DUMMY);
1354         pgstat_send(&msg, sizeof(msg));
1355 }
1356
1357 /* ----------
1358  * pgstat_send_inquiry() -
1359  *
1360  *      Notify collector that we need fresh data.
1361  *      ts specifies the minimum acceptable timestamp for the stats file.
1362  * ----------
1363  */
1364 static void
1365 pgstat_send_inquiry(TimestampTz ts)
1366 {
1367         PgStat_MsgInquiry msg;
1368
1369         pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_INQUIRY);
1370         msg.inquiry_time = ts;
1371         pgstat_send(&msg, sizeof(msg));
1372 }
1373
1374
1375 /*
1376  * Initialize function call usage data.
1377  * Called by the executor before invoking a function.
1378  */
1379 void
1380 pgstat_init_function_usage(FunctionCallInfoData *fcinfo,
1381                                                    PgStat_FunctionCallUsage *fcu)
1382 {
1383         PgStat_BackendFunctionEntry *htabent;
1384         bool            found;
1385
1386         if (pgstat_track_functions <= fcinfo->flinfo->fn_stats)
1387         {
1388                 /* stats not wanted */
1389                 fcu->fs = NULL;
1390                 return;
1391         }
1392
1393         if (!pgStatFunctions)
1394         {
1395                 /* First time through - initialize function stat table */
1396                 HASHCTL         hash_ctl;
1397
1398                 memset(&hash_ctl, 0, sizeof(hash_ctl));
1399                 hash_ctl.keysize = sizeof(Oid);
1400                 hash_ctl.entrysize = sizeof(PgStat_BackendFunctionEntry);
1401                 hash_ctl.hash = oid_hash;
1402                 pgStatFunctions = hash_create("Function stat entries",
1403                                                                           PGSTAT_FUNCTION_HASH_SIZE,
1404                                                                           &hash_ctl,
1405                                                                           HASH_ELEM | HASH_FUNCTION);
1406         }
1407
1408         /* Get the stats entry for this function, create if necessary */
1409         htabent = hash_search(pgStatFunctions, &fcinfo->flinfo->fn_oid,
1410                                                   HASH_ENTER, &found);
1411         if (!found)
1412                 MemSet(&htabent->f_counts, 0, sizeof(PgStat_FunctionCounts));
1413
1414         fcu->fs = &htabent->f_counts;
1415
1416         /* save stats for this function, later used to compensate for recursion */
1417         fcu->save_f_time = htabent->f_counts.f_time;
1418
1419         /* save current backend-wide total time */
1420         fcu->save_total = total_func_time;
1421
1422         /* get clock time as of function start */
1423         INSTR_TIME_SET_CURRENT(fcu->f_start);
1424 }
1425
1426 /*
1427  * find_funcstat_entry - find any existing PgStat_BackendFunctionEntry entry
1428  *              for specified function
1429  *
1430  * If no entry, return NULL, don't create a new one
1431  */
1432 PgStat_BackendFunctionEntry *
1433 find_funcstat_entry(Oid func_id)
1434 {
1435         if (pgStatFunctions == NULL)
1436                 return NULL;
1437
1438         return (PgStat_BackendFunctionEntry *) hash_search(pgStatFunctions,
1439                                                                                                            (void *) &func_id,
1440                                                                                                            HASH_FIND, NULL);
1441 }
1442
1443 /*
1444  * Calculate function call usage and update stat counters.
1445  * Called by the executor after invoking a function.
1446  *
1447  * In the case of a set-returning function that runs in value-per-call mode,
1448  * we will see multiple pgstat_init_function_usage/pgstat_end_function_usage
1449  * calls for what the user considers a single call of the function.  The
1450  * finalize flag should be TRUE on the last call.
1451  */
1452 void
1453 pgstat_end_function_usage(PgStat_FunctionCallUsage *fcu, bool finalize)
1454 {
1455         PgStat_FunctionCounts *fs = fcu->fs;
1456         instr_time      f_total;
1457         instr_time      f_others;
1458         instr_time      f_self;
1459
1460         /* stats not wanted? */
1461         if (fs == NULL)
1462                 return;
1463
1464         /* total elapsed time in this function call */
1465         INSTR_TIME_SET_CURRENT(f_total);
1466         INSTR_TIME_SUBTRACT(f_total, fcu->f_start);
1467
1468         /* self usage: elapsed minus anything already charged to other calls */
1469         f_others = total_func_time;
1470         INSTR_TIME_SUBTRACT(f_others, fcu->save_total);
1471         f_self = f_total;
1472         INSTR_TIME_SUBTRACT(f_self, f_others);
1473
1474         /* update backend-wide total time */
1475         INSTR_TIME_ADD(total_func_time, f_self);
1476
1477         /*
1478          * Compute the new total f_time as the total elapsed time added to the
1479          * pre-call value of f_time.  This is necessary to avoid double-counting
1480          * any time taken by recursive calls of myself.  (We do not need any
1481          * similar kluge for self time, since that already excludes any recursive
1482          * calls.)
1483          */
1484         INSTR_TIME_ADD(f_total, fcu->save_f_time);
1485
1486         /* update counters in function stats table */
1487         if (finalize)
1488                 fs->f_numcalls++;
1489         fs->f_time = f_total;
1490         INSTR_TIME_ADD(fs->f_time_self, f_self);
1491
1492         /* indicate that we have something to send */
1493         have_function_stats = true;
1494 }
1495
1496
1497 /* ----------
1498  * pgstat_initstats() -
1499  *
1500  *      Initialize a relcache entry to count access statistics.
1501  *      Called whenever a relation is opened.
1502  *
1503  *      We assume that a relcache entry's pgstat_info field is zeroed by
1504  *      relcache.c when the relcache entry is made; thereafter it is long-lived
1505  *      data.  We can avoid repeated searches of the TabStatus arrays when the
1506  *      same relation is touched repeatedly within a transaction.
1507  * ----------
1508  */
1509 void
1510 pgstat_initstats(Relation rel)
1511 {
1512         Oid                     rel_id = rel->rd_id;
1513         char            relkind = rel->rd_rel->relkind;
1514
1515         /* We only count stats for things that have storage */
1516         if (!(relkind == RELKIND_RELATION ||
1517                   relkind == RELKIND_INDEX ||
1518                   relkind == RELKIND_TOASTVALUE ||
1519                   relkind == RELKIND_SEQUENCE))
1520         {
1521                 rel->pgstat_info = NULL;
1522                 return;
1523         }
1524
1525         if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
1526         {
1527                 /* We're not counting at all */
1528                 rel->pgstat_info = NULL;
1529                 return;
1530         }
1531
1532         /*
1533          * If we already set up this relation in the current transaction, nothing
1534          * to do.
1535          */
1536         if (rel->pgstat_info != NULL &&
1537                 rel->pgstat_info->t_id == rel_id)
1538                 return;
1539
1540         /* Else find or make the PgStat_TableStatus entry, and update link */
1541         rel->pgstat_info = get_tabstat_entry(rel_id, rel->rd_rel->relisshared);
1542 }
1543
1544 /*
1545  * get_tabstat_entry - find or create a PgStat_TableStatus entry for rel
1546  */
1547 static PgStat_TableStatus *
1548 get_tabstat_entry(Oid rel_id, bool isshared)
1549 {
1550         PgStat_TableStatus *entry;
1551         TabStatusArray *tsa;
1552         TabStatusArray *prev_tsa;
1553         int                     i;
1554
1555         /*
1556          * Search the already-used tabstat slots for this relation.
1557          */
1558         prev_tsa = NULL;
1559         for (tsa = pgStatTabList; tsa != NULL; prev_tsa = tsa, tsa = tsa->tsa_next)
1560         {
1561                 for (i = 0; i < tsa->tsa_used; i++)
1562                 {
1563                         entry = &tsa->tsa_entries[i];
1564                         if (entry->t_id == rel_id)
1565                                 return entry;
1566                 }
1567
1568                 if (tsa->tsa_used < TABSTAT_QUANTUM)
1569                 {
1570                         /*
1571                          * It must not be present, but we found a free slot instead. Fine,
1572                          * let's use this one.  We assume the entry was already zeroed,
1573                          * either at creation or after last use.
1574                          */
1575                         entry = &tsa->tsa_entries[tsa->tsa_used++];
1576                         entry->t_id = rel_id;
1577                         entry->t_shared = isshared;
1578                         return entry;
1579                 }
1580         }
1581
1582         /*
1583          * We ran out of tabstat slots, so allocate more.  Be sure they're zeroed.
1584          */
1585         tsa = (TabStatusArray *) MemoryContextAllocZero(TopMemoryContext,
1586                                                                                                         sizeof(TabStatusArray));
1587         if (prev_tsa)
1588                 prev_tsa->tsa_next = tsa;
1589         else
1590                 pgStatTabList = tsa;
1591
1592         /*
1593          * Use the first entry of the new TabStatusArray.
1594          */
1595         entry = &tsa->tsa_entries[tsa->tsa_used++];
1596         entry->t_id = rel_id;
1597         entry->t_shared = isshared;
1598         return entry;
1599 }
1600
1601 /*
1602  * find_tabstat_entry - find any existing PgStat_TableStatus entry for rel
1603  *
1604  * If no entry, return NULL, don't create a new one
1605  */
1606 PgStat_TableStatus *
1607 find_tabstat_entry(Oid rel_id)
1608 {
1609         PgStat_TableStatus *entry;
1610         TabStatusArray *tsa;
1611         int                     i;
1612
1613         for (tsa = pgStatTabList; tsa != NULL; tsa = tsa->tsa_next)
1614         {
1615                 for (i = 0; i < tsa->tsa_used; i++)
1616                 {
1617                         entry = &tsa->tsa_entries[i];
1618                         if (entry->t_id == rel_id)
1619                                 return entry;
1620                 }
1621         }
1622
1623         /* Not present */
1624         return NULL;
1625 }
1626
1627 /*
1628  * get_tabstat_stack_level - add a new (sub)transaction stack entry if needed
1629  */
1630 static PgStat_SubXactStatus *
1631 get_tabstat_stack_level(int nest_level)
1632 {
1633         PgStat_SubXactStatus *xact_state;
1634
1635         xact_state = pgStatXactStack;
1636         if (xact_state == NULL || xact_state->nest_level != nest_level)
1637         {
1638                 xact_state = (PgStat_SubXactStatus *)
1639                         MemoryContextAlloc(TopTransactionContext,
1640                                                            sizeof(PgStat_SubXactStatus));
1641                 xact_state->nest_level = nest_level;
1642                 xact_state->prev = pgStatXactStack;
1643                 xact_state->first = NULL;
1644                 pgStatXactStack = xact_state;
1645         }
1646         return xact_state;
1647 }
1648
1649 /*
1650  * add_tabstat_xact_level - add a new (sub)transaction state record
1651  */
1652 static void
1653 add_tabstat_xact_level(PgStat_TableStatus *pgstat_info, int nest_level)
1654 {
1655         PgStat_SubXactStatus *xact_state;
1656         PgStat_TableXactStatus *trans;
1657
1658         /*
1659          * If this is the first rel to be modified at the current nest level, we
1660          * first have to push a transaction stack entry.
1661          */
1662         xact_state = get_tabstat_stack_level(nest_level);
1663
1664         /* Now make a per-table stack entry */
1665         trans = (PgStat_TableXactStatus *)
1666                 MemoryContextAllocZero(TopTransactionContext,
1667                                                            sizeof(PgStat_TableXactStatus));
1668         trans->nest_level = nest_level;
1669         trans->upper = pgstat_info->trans;
1670         trans->parent = pgstat_info;
1671         trans->next = xact_state->first;
1672         xact_state->first = trans;
1673         pgstat_info->trans = trans;
1674 }
1675
1676 /*
1677  * pgstat_count_heap_insert - count a tuple insertion
1678  */
1679 void
1680 pgstat_count_heap_insert(Relation rel)
1681 {
1682         PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1683
1684         if (pgstat_info != NULL)
1685         {
1686                 /* We have to log the effect at the proper transactional level */
1687                 int                     nest_level = GetCurrentTransactionNestLevel();
1688
1689                 if (pgstat_info->trans == NULL ||
1690                         pgstat_info->trans->nest_level != nest_level)
1691                         add_tabstat_xact_level(pgstat_info, nest_level);
1692
1693                 pgstat_info->trans->tuples_inserted++;
1694         }
1695 }
1696
1697 /*
1698  * pgstat_count_heap_update - count a tuple update
1699  */
1700 void
1701 pgstat_count_heap_update(Relation rel, bool hot)
1702 {
1703         PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1704
1705         if (pgstat_info != NULL)
1706         {
1707                 /* We have to log the effect at the proper transactional level */
1708                 int                     nest_level = GetCurrentTransactionNestLevel();
1709
1710                 if (pgstat_info->trans == NULL ||
1711                         pgstat_info->trans->nest_level != nest_level)
1712                         add_tabstat_xact_level(pgstat_info, nest_level);
1713
1714                 pgstat_info->trans->tuples_updated++;
1715
1716                 /* t_tuples_hot_updated is nontransactional, so just advance it */
1717                 if (hot)
1718                         pgstat_info->t_counts.t_tuples_hot_updated++;
1719         }
1720 }
1721
1722 /*
1723  * pgstat_count_heap_delete - count a tuple deletion
1724  */
1725 void
1726 pgstat_count_heap_delete(Relation rel)
1727 {
1728         PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1729
1730         if (pgstat_info != NULL)
1731         {
1732                 /* We have to log the effect at the proper transactional level */
1733                 int                     nest_level = GetCurrentTransactionNestLevel();
1734
1735                 if (pgstat_info->trans == NULL ||
1736                         pgstat_info->trans->nest_level != nest_level)
1737                         add_tabstat_xact_level(pgstat_info, nest_level);
1738
1739                 pgstat_info->trans->tuples_deleted++;
1740         }
1741 }
1742
1743 /*
1744  * pgstat_update_heap_dead_tuples - update dead-tuples count
1745  *
1746  * The semantics of this are that we are reporting the nontransactional
1747  * recovery of "delta" dead tuples; so t_delta_dead_tuples decreases
1748  * rather than increasing, and the change goes straight into the per-table
1749  * counter, not into transactional state.
1750  */
1751 void
1752 pgstat_update_heap_dead_tuples(Relation rel, int delta)
1753 {
1754         PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1755
1756         if (pgstat_info != NULL)
1757                 pgstat_info->t_counts.t_delta_dead_tuples -= delta;
1758 }
1759
1760
1761 /* ----------
1762  * AtEOXact_PgStat
1763  *
1764  *      Called from access/transam/xact.c at top-level transaction commit/abort.
1765  * ----------
1766  */
1767 void
1768 AtEOXact_PgStat(bool isCommit)
1769 {
1770         PgStat_SubXactStatus *xact_state;
1771
1772         /*
1773          * Count transaction commit or abort.  (We use counters, not just bools,
1774          * in case the reporting message isn't sent right away.)
1775          */
1776         if (isCommit)
1777                 pgStatXactCommit++;
1778         else
1779                 pgStatXactRollback++;
1780
1781         /*
1782          * Transfer transactional insert/update counts into the base tabstat
1783          * entries.  We don't bother to free any of the transactional state, since
1784          * it's all in TopTransactionContext and will go away anyway.
1785          */
1786         xact_state = pgStatXactStack;
1787         if (xact_state != NULL)
1788         {
1789                 PgStat_TableXactStatus *trans;
1790
1791                 Assert(xact_state->nest_level == 1);
1792                 Assert(xact_state->prev == NULL);
1793                 for (trans = xact_state->first; trans != NULL; trans = trans->next)
1794                 {
1795                         PgStat_TableStatus *tabstat;
1796
1797                         Assert(trans->nest_level == 1);
1798                         Assert(trans->upper == NULL);
1799                         tabstat = trans->parent;
1800                         Assert(tabstat->trans == trans);
1801                         /* count attempted actions regardless of commit/abort */
1802                         tabstat->t_counts.t_tuples_inserted += trans->tuples_inserted;
1803                         tabstat->t_counts.t_tuples_updated += trans->tuples_updated;
1804                         tabstat->t_counts.t_tuples_deleted += trans->tuples_deleted;
1805                         if (isCommit)
1806                         {
1807                                 /* insert adds a live tuple, delete removes one */
1808                                 tabstat->t_counts.t_delta_live_tuples +=
1809                                         trans->tuples_inserted - trans->tuples_deleted;
1810                                 /* update and delete each create a dead tuple */
1811                                 tabstat->t_counts.t_delta_dead_tuples +=
1812                                         trans->tuples_updated + trans->tuples_deleted;
1813                                 /* insert, update, delete each count as one change event */
1814                                 tabstat->t_counts.t_changed_tuples +=
1815                                         trans->tuples_inserted + trans->tuples_updated +
1816                                         trans->tuples_deleted;
1817                         }
1818                         else
1819                         {
1820                                 /* inserted tuples are dead, deleted tuples are unaffected */
1821                                 tabstat->t_counts.t_delta_dead_tuples +=
1822                                         trans->tuples_inserted + trans->tuples_updated;
1823                                 /* an aborted xact generates no changed_tuple events */
1824                         }
1825                         tabstat->trans = NULL;
1826                 }
1827         }
1828         pgStatXactStack = NULL;
1829
1830         /* Make sure any stats snapshot is thrown away */
1831         pgstat_clear_snapshot();
1832 }
1833
1834 /* ----------
1835  * AtEOSubXact_PgStat
1836  *
1837  *      Called from access/transam/xact.c at subtransaction commit/abort.
1838  * ----------
1839  */
1840 void
1841 AtEOSubXact_PgStat(bool isCommit, int nestDepth)
1842 {
1843         PgStat_SubXactStatus *xact_state;
1844
1845         /*
1846          * Transfer transactional insert/update counts into the next higher
1847          * subtransaction state.
1848          */
1849         xact_state = pgStatXactStack;
1850         if (xact_state != NULL &&
1851                 xact_state->nest_level >= nestDepth)
1852         {
1853                 PgStat_TableXactStatus *trans;
1854                 PgStat_TableXactStatus *next_trans;
1855
1856                 /* delink xact_state from stack immediately to simplify reuse case */
1857                 pgStatXactStack = xact_state->prev;
1858
1859                 for (trans = xact_state->first; trans != NULL; trans = next_trans)
1860                 {
1861                         PgStat_TableStatus *tabstat;
1862
1863                         next_trans = trans->next;
1864                         Assert(trans->nest_level == nestDepth);
1865                         tabstat = trans->parent;
1866                         Assert(tabstat->trans == trans);
1867                         if (isCommit)
1868                         {
1869                                 if (trans->upper && trans->upper->nest_level == nestDepth - 1)
1870                                 {
1871                                         trans->upper->tuples_inserted += trans->tuples_inserted;
1872                                         trans->upper->tuples_updated += trans->tuples_updated;
1873                                         trans->upper->tuples_deleted += trans->tuples_deleted;
1874                                         tabstat->trans = trans->upper;
1875                                         pfree(trans);
1876                                 }
1877                                 else
1878                                 {
1879                                         /*
1880                                          * When there isn't an immediate parent state, we can just
1881                                          * reuse the record instead of going through a
1882                                          * palloc/pfree pushup (this works since it's all in
1883                                          * TopTransactionContext anyway).  We have to re-link it
1884                                          * into the parent level, though, and that might mean
1885                                          * pushing a new entry into the pgStatXactStack.
1886                                          */
1887                                         PgStat_SubXactStatus *upper_xact_state;
1888
1889                                         upper_xact_state = get_tabstat_stack_level(nestDepth - 1);
1890                                         trans->next = upper_xact_state->first;
1891                                         upper_xact_state->first = trans;
1892                                         trans->nest_level = nestDepth - 1;
1893                                 }
1894                         }
1895                         else
1896                         {
1897                                 /*
1898                                  * On abort, update top-level tabstat counts, then forget the
1899                                  * subtransaction
1900                                  */
1901
1902                                 /* count attempted actions regardless of commit/abort */
1903                                 tabstat->t_counts.t_tuples_inserted += trans->tuples_inserted;
1904                                 tabstat->t_counts.t_tuples_updated += trans->tuples_updated;
1905                                 tabstat->t_counts.t_tuples_deleted += trans->tuples_deleted;
1906                                 /* inserted tuples are dead, deleted tuples are unaffected */
1907                                 tabstat->t_counts.t_delta_dead_tuples +=
1908                                         trans->tuples_inserted + trans->tuples_updated;
1909                                 tabstat->trans = trans->upper;
1910                                 pfree(trans);
1911                         }
1912                 }
1913                 pfree(xact_state);
1914         }
1915 }
1916
1917
1918 /*
1919  * AtPrepare_PgStat
1920  *              Save the transactional stats state at 2PC transaction prepare.
1921  *
1922  * In this phase we just generate 2PC records for all the pending
1923  * transaction-dependent stats work.
1924  */
1925 void
1926 AtPrepare_PgStat(void)
1927 {
1928         PgStat_SubXactStatus *xact_state;
1929
1930         xact_state = pgStatXactStack;
1931         if (xact_state != NULL)
1932         {
1933                 PgStat_TableXactStatus *trans;
1934
1935                 Assert(xact_state->nest_level == 1);
1936                 Assert(xact_state->prev == NULL);
1937                 for (trans = xact_state->first; trans != NULL; trans = trans->next)
1938                 {
1939                         PgStat_TableStatus *tabstat;
1940                         TwoPhasePgStatRecord record;
1941
1942                         Assert(trans->nest_level == 1);
1943                         Assert(trans->upper == NULL);
1944                         tabstat = trans->parent;
1945                         Assert(tabstat->trans == trans);
1946
1947                         record.tuples_inserted = trans->tuples_inserted;
1948                         record.tuples_updated = trans->tuples_updated;
1949                         record.tuples_deleted = trans->tuples_deleted;
1950                         record.t_id = tabstat->t_id;
1951                         record.t_shared = tabstat->t_shared;
1952
1953                         RegisterTwoPhaseRecord(TWOPHASE_RM_PGSTAT_ID, 0,
1954                                                                    &record, sizeof(TwoPhasePgStatRecord));
1955                 }
1956         }
1957 }
1958
1959 /*
1960  * PostPrepare_PgStat
1961  *              Clean up after successful PREPARE.
1962  *
1963  * All we need do here is unlink the transaction stats state from the
1964  * nontransactional state.      The nontransactional action counts will be
1965  * reported to the stats collector immediately, while the effects on live
1966  * and dead tuple counts are preserved in the 2PC state file.
1967  *
1968  * Note: AtEOXact_PgStat is not called during PREPARE.
1969  */
1970 void
1971 PostPrepare_PgStat(void)
1972 {
1973         PgStat_SubXactStatus *xact_state;
1974
1975         /*
1976          * We don't bother to free any of the transactional state, since it's all
1977          * in TopTransactionContext and will go away anyway.
1978          */
1979         xact_state = pgStatXactStack;
1980         if (xact_state != NULL)
1981         {
1982                 PgStat_TableXactStatus *trans;
1983
1984                 for (trans = xact_state->first; trans != NULL; trans = trans->next)
1985                 {
1986                         PgStat_TableStatus *tabstat;
1987
1988                         tabstat = trans->parent;
1989                         tabstat->trans = NULL;
1990                 }
1991         }
1992         pgStatXactStack = NULL;
1993
1994         /* Make sure any stats snapshot is thrown away */
1995         pgstat_clear_snapshot();
1996 }
1997
1998 /*
1999  * 2PC processing routine for COMMIT PREPARED case.
2000  *
2001  * Load the saved counts into our local pgstats state.
2002  */
2003 void
2004 pgstat_twophase_postcommit(TransactionId xid, uint16 info,
2005                                                    void *recdata, uint32 len)
2006 {
2007         TwoPhasePgStatRecord *rec = (TwoPhasePgStatRecord *) recdata;
2008         PgStat_TableStatus *pgstat_info;
2009
2010         /* Find or create a tabstat entry for the rel */
2011         pgstat_info = get_tabstat_entry(rec->t_id, rec->t_shared);
2012
2013         /* Same math as in AtEOXact_PgStat, commit case */
2014         pgstat_info->t_counts.t_tuples_inserted += rec->tuples_inserted;
2015         pgstat_info->t_counts.t_tuples_updated += rec->tuples_updated;
2016         pgstat_info->t_counts.t_tuples_deleted += rec->tuples_deleted;
2017         pgstat_info->t_counts.t_delta_live_tuples +=
2018                 rec->tuples_inserted - rec->tuples_deleted;
2019         pgstat_info->t_counts.t_delta_dead_tuples +=
2020                 rec->tuples_updated + rec->tuples_deleted;
2021         pgstat_info->t_counts.t_changed_tuples +=
2022                 rec->tuples_inserted + rec->tuples_updated +
2023                 rec->tuples_deleted;
2024 }
2025
2026 /*
2027  * 2PC processing routine for ROLLBACK PREPARED case.
2028  *
2029  * Load the saved counts into our local pgstats state, but treat them
2030  * as aborted.
2031  */
2032 void
2033 pgstat_twophase_postabort(TransactionId xid, uint16 info,
2034                                                   void *recdata, uint32 len)
2035 {
2036         TwoPhasePgStatRecord *rec = (TwoPhasePgStatRecord *) recdata;
2037         PgStat_TableStatus *pgstat_info;
2038
2039         /* Find or create a tabstat entry for the rel */
2040         pgstat_info = get_tabstat_entry(rec->t_id, rec->t_shared);
2041
2042         /* Same math as in AtEOXact_PgStat, abort case */
2043         pgstat_info->t_counts.t_tuples_inserted += rec->tuples_inserted;
2044         pgstat_info->t_counts.t_tuples_updated += rec->tuples_updated;
2045         pgstat_info->t_counts.t_tuples_deleted += rec->tuples_deleted;
2046         pgstat_info->t_counts.t_delta_dead_tuples +=
2047                 rec->tuples_inserted + rec->tuples_updated;
2048 }
2049
2050
2051 /* ----------
2052  * pgstat_fetch_stat_dbentry() -
2053  *
2054  *      Support function for the SQL-callable pgstat* functions. Returns
2055  *      the collected statistics for one database or NULL. NULL doesn't mean
2056  *      that the database doesn't exist, it is just not yet known by the
2057  *      collector, so the caller is better off to report ZERO instead.
2058  * ----------
2059  */
2060 PgStat_StatDBEntry *
2061 pgstat_fetch_stat_dbentry(Oid dbid)
2062 {
2063         /*
2064          * If not done for this transaction, read the statistics collector stats
2065          * file into some hash tables.
2066          */
2067         backend_read_statsfile();
2068
2069         /*
2070          * Lookup the requested database; return NULL if not found
2071          */
2072         return (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
2073                                                                                           (void *) &dbid,
2074                                                                                           HASH_FIND, NULL);
2075 }
2076
2077
2078 /* ----------
2079  * pgstat_fetch_stat_tabentry() -
2080  *
2081  *      Support function for the SQL-callable pgstat* functions. Returns
2082  *      the collected statistics for one table or NULL. NULL doesn't mean
2083  *      that the table doesn't exist, it is just not yet known by the
2084  *      collector, so the caller is better off to report ZERO instead.
2085  * ----------
2086  */
2087 PgStat_StatTabEntry *
2088 pgstat_fetch_stat_tabentry(Oid relid)
2089 {
2090         Oid                     dbid;
2091         PgStat_StatDBEntry *dbentry;
2092         PgStat_StatTabEntry *tabentry;
2093
2094         /*
2095          * If not done for this transaction, read the statistics collector stats
2096          * file into some hash tables.
2097          */
2098         backend_read_statsfile();
2099
2100         /*
2101          * Lookup our database, then look in its table hash table.
2102          */
2103         dbid = MyDatabaseId;
2104         dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
2105                                                                                                  (void *) &dbid,
2106                                                                                                  HASH_FIND, NULL);
2107         if (dbentry != NULL && dbentry->tables != NULL)
2108         {
2109                 tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
2110                                                                                                            (void *) &relid,
2111                                                                                                            HASH_FIND, NULL);
2112                 if (tabentry)
2113                         return tabentry;
2114         }
2115
2116         /*
2117          * If we didn't find it, maybe it's a shared table.
2118          */
2119         dbid = InvalidOid;
2120         dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
2121                                                                                                  (void *) &dbid,
2122                                                                                                  HASH_FIND, NULL);
2123         if (dbentry != NULL && dbentry->tables != NULL)
2124         {
2125                 tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
2126                                                                                                            (void *) &relid,
2127                                                                                                            HASH_FIND, NULL);
2128                 if (tabentry)
2129                         return tabentry;
2130         }
2131
2132         return NULL;
2133 }
2134
2135
2136 /* ----------
2137  * pgstat_fetch_stat_funcentry() -
2138  *
2139  *      Support function for the SQL-callable pgstat* functions. Returns
2140  *      the collected statistics for one function or NULL.
2141  * ----------
2142  */
2143 PgStat_StatFuncEntry *
2144 pgstat_fetch_stat_funcentry(Oid func_id)
2145 {
2146         PgStat_StatDBEntry *dbentry;
2147         PgStat_StatFuncEntry *funcentry = NULL;
2148
2149         /* load the stats file if needed */
2150         backend_read_statsfile();
2151
2152         /* Lookup our database, then find the requested function.  */
2153         dbentry = pgstat_fetch_stat_dbentry(MyDatabaseId);
2154         if (dbentry != NULL && dbentry->functions != NULL)
2155         {
2156                 funcentry = (PgStat_StatFuncEntry *) hash_search(dbentry->functions,
2157                                                                                                                  (void *) &func_id,
2158                                                                                                                  HASH_FIND, NULL);
2159         }
2160
2161         return funcentry;
2162 }
2163
2164
2165 /* ----------
2166  * pgstat_fetch_stat_beentry() -
2167  *
2168  *      Support function for the SQL-callable pgstat* functions. Returns
2169  *      our local copy of the current-activity entry for one backend.
2170  *
2171  *      NB: caller is responsible for a check if the user is permitted to see
2172  *      this info (especially the querystring).
2173  * ----------
2174  */
2175 PgBackendStatus *
2176 pgstat_fetch_stat_beentry(int beid)
2177 {
2178         pgstat_read_current_status();
2179
2180         if (beid < 1 || beid > localNumBackends)
2181                 return NULL;
2182
2183         return &localBackendStatusTable[beid - 1];
2184 }
2185
2186
2187 /* ----------
2188  * pgstat_fetch_stat_numbackends() -
2189  *
2190  *      Support function for the SQL-callable pgstat* functions. Returns
2191  *      the maximum current backend id.
2192  * ----------
2193  */
2194 int
2195 pgstat_fetch_stat_numbackends(void)
2196 {
2197         pgstat_read_current_status();
2198
2199         return localNumBackends;
2200 }
2201
2202 /*
2203  * ---------
2204  * pgstat_fetch_global() -
2205  *
2206  *      Support function for the SQL-callable pgstat* functions. Returns
2207  *      a pointer to the global statistics struct.
2208  * ---------
2209  */
2210 PgStat_GlobalStats *
2211 pgstat_fetch_global(void)
2212 {
2213         backend_read_statsfile();
2214
2215         return &globalStats;
2216 }
2217
2218
2219 /* ------------------------------------------------------------
2220  * Functions for management of the shared-memory PgBackendStatus array
2221  * ------------------------------------------------------------
2222  */
2223
2224 static PgBackendStatus *BackendStatusArray = NULL;
2225 static PgBackendStatus *MyBEEntry = NULL;
2226 static char *BackendAppnameBuffer = NULL;
2227 static char *BackendActivityBuffer = NULL;
2228
2229
2230 /*
2231  * Report shared-memory space needed by CreateSharedBackendStatus.
2232  */
2233 Size
2234 BackendStatusShmemSize(void)
2235 {
2236         Size            size;
2237
2238         size = mul_size(sizeof(PgBackendStatus), MaxBackends);
2239         size = add_size(size,
2240                                         mul_size(NAMEDATALEN, MaxBackends));
2241         size = add_size(size,
2242                                         mul_size(pgstat_track_activity_query_size, MaxBackends));
2243         return size;
2244 }
2245
2246 /*
2247  * Initialize the shared status array and activity/appname string buffers
2248  * during postmaster startup.
2249  */
2250 void
2251 CreateSharedBackendStatus(void)
2252 {
2253         Size            size;
2254         bool            found;
2255         int                     i;
2256         char       *buffer;
2257
2258         /* Create or attach to the shared array */
2259         size = mul_size(sizeof(PgBackendStatus), MaxBackends);
2260         BackendStatusArray = (PgBackendStatus *)
2261                 ShmemInitStruct("Backend Status Array", size, &found);
2262
2263         if (!found)
2264         {
2265                 /*
2266                  * We're the first - initialize.
2267                  */
2268                 MemSet(BackendStatusArray, 0, size);
2269         }
2270
2271         /* Create or attach to the shared appname buffer */
2272         size = mul_size(NAMEDATALEN, MaxBackends);
2273         BackendAppnameBuffer = (char *)
2274                 ShmemInitStruct("Backend Application Name Buffer", size, &found);
2275
2276         if (!found)
2277         {
2278                 MemSet(BackendAppnameBuffer, 0, size);
2279
2280                 /* Initialize st_appname pointers. */
2281                 buffer = BackendAppnameBuffer;
2282                 for (i = 0; i < MaxBackends; i++)
2283                 {
2284                         BackendStatusArray[i].st_appname = buffer;
2285                         buffer += NAMEDATALEN;
2286                 }
2287         }
2288
2289         /* Create or attach to the shared activity buffer */
2290         size = mul_size(pgstat_track_activity_query_size, MaxBackends);
2291         BackendActivityBuffer = (char *)
2292                 ShmemInitStruct("Backend Activity Buffer", size, &found);
2293
2294         if (!found)
2295         {
2296                 MemSet(BackendActivityBuffer, 0, size);
2297
2298                 /* Initialize st_activity pointers. */
2299                 buffer = BackendActivityBuffer;
2300                 for (i = 0; i < MaxBackends; i++)
2301                 {
2302                         BackendStatusArray[i].st_activity = buffer;
2303                         buffer += pgstat_track_activity_query_size;
2304                 }
2305         }
2306 }
2307
2308
2309 /* ----------
2310  * pgstat_initialize() -
2311  *
2312  *      Initialize pgstats state, and set up our on-proc-exit hook.
2313  *      Called from InitPostgres.  MyBackendId must be set,
2314  *      but we must not have started any transaction yet (since the
2315  *      exit hook must run after the last transaction exit).
2316  *      NOTE: MyDatabaseId isn't set yet; so the shutdown hook has to be careful.
2317  * ----------
2318  */
2319 void
2320 pgstat_initialize(void)
2321 {
2322         /* Initialize MyBEEntry */
2323         Assert(MyBackendId >= 1 && MyBackendId <= MaxBackends);
2324         MyBEEntry = &BackendStatusArray[MyBackendId - 1];
2325
2326         /* Set up a process-exit hook to clean up */
2327         on_shmem_exit(pgstat_beshutdown_hook, 0);
2328 }
2329
2330 /* ----------
2331  * pgstat_bestart() -
2332  *
2333  *      Initialize this backend's entry in the PgBackendStatus array.
2334  *      Called from InitPostgres.
2335  *      MyDatabaseId, session userid, and application_name must be set
2336  *      (hence, this cannot be combined with pgstat_initialize).
2337  * ----------
2338  */
2339 void
2340 pgstat_bestart(void)
2341 {
2342         TimestampTz proc_start_timestamp;
2343         Oid                     userid;
2344         SockAddr        clientaddr;
2345         volatile PgBackendStatus *beentry;
2346
2347         /*
2348          * To minimize the time spent modifying the PgBackendStatus entry, fetch
2349          * all the needed data first.
2350          *
2351          * If we have a MyProcPort, use its session start time (for consistency,
2352          * and to save a kernel call).
2353          */
2354         if (MyProcPort)
2355                 proc_start_timestamp = MyProcPort->SessionStartTime;
2356         else
2357                 proc_start_timestamp = GetCurrentTimestamp();
2358         userid = GetSessionUserId();
2359
2360         /*
2361          * We may not have a MyProcPort (eg, if this is the autovacuum process).
2362          * If so, use all-zeroes client address, which is dealt with specially in
2363          * pg_stat_get_backend_client_addr and pg_stat_get_backend_client_port.
2364          */
2365         if (MyProcPort)
2366                 memcpy(&clientaddr, &MyProcPort->raddr, sizeof(clientaddr));
2367         else
2368                 MemSet(&clientaddr, 0, sizeof(clientaddr));
2369
2370         /*
2371          * Initialize my status entry, following the protocol of bumping
2372          * st_changecount before and after; and make sure it's even afterwards. We
2373          * use a volatile pointer here to ensure the compiler doesn't try to get
2374          * cute.
2375          */
2376         beentry = MyBEEntry;
2377         do
2378         {
2379                 beentry->st_changecount++;
2380         } while ((beentry->st_changecount & 1) == 0);
2381
2382         beentry->st_procpid = MyProcPid;
2383         beentry->st_proc_start_timestamp = proc_start_timestamp;
2384         beentry->st_activity_start_timestamp = 0;
2385         beentry->st_xact_start_timestamp = 0;
2386         beentry->st_databaseid = MyDatabaseId;
2387         beentry->st_userid = userid;
2388         beentry->st_clientaddr = clientaddr;
2389         beentry->st_waiting = false;
2390         beentry->st_appname[0] = '\0';
2391         beentry->st_activity[0] = '\0';
2392         /* Also make sure the last byte in each string area is always 0 */
2393         beentry->st_appname[NAMEDATALEN - 1] = '\0';
2394         beentry->st_activity[pgstat_track_activity_query_size - 1] = '\0';
2395
2396         beentry->st_changecount++;
2397         Assert((beentry->st_changecount & 1) == 0);
2398
2399         /* Update app name to current GUC setting */
2400         if (application_name)
2401                 pgstat_report_appname(application_name);
2402 }
2403
2404 /*
2405  * Shut down a single backend's statistics reporting at process exit.
2406  *
2407  * Flush any remaining statistics counts out to the collector.
2408  * Without this, operations triggered during backend exit (such as
2409  * temp table deletions) won't be counted.
2410  *
2411  * Lastly, clear out our entry in the PgBackendStatus array.
2412  */
2413 static void
2414 pgstat_beshutdown_hook(int code, Datum arg)
2415 {
2416         volatile PgBackendStatus *beentry = MyBEEntry;
2417
2418         /*
2419          * If we got as far as discovering our own database ID, we can report what
2420          * we did to the collector.  Otherwise, we'd be sending an invalid
2421          * database ID, so forget it.  (This means that accesses to pg_database
2422          * during failed backend starts might never get counted.)
2423          */
2424         if (OidIsValid(MyDatabaseId))
2425                 pgstat_report_stat(true);
2426
2427         /*
2428          * Clear my status entry, following the protocol of bumping st_changecount
2429          * before and after.  We use a volatile pointer here to ensure the
2430          * compiler doesn't try to get cute.
2431          */
2432         beentry->st_changecount++;
2433
2434         beentry->st_procpid = 0;        /* mark invalid */
2435
2436         beentry->st_changecount++;
2437         Assert((beentry->st_changecount & 1) == 0);
2438 }
2439
2440
2441 /* ----------
2442  * pgstat_report_activity() -
2443  *
2444  *      Called from tcop/postgres.c to report what the backend is actually doing
2445  *      (usually "<IDLE>" or the start of the query to be executed).
2446  * ----------
2447  */
2448 void
2449 pgstat_report_activity(const char *cmd_str)
2450 {
2451         volatile PgBackendStatus *beentry = MyBEEntry;
2452         TimestampTz start_timestamp;
2453         int                     len;
2454
2455         TRACE_POSTGRESQL_STATEMENT_STATUS(cmd_str);
2456
2457         if (!pgstat_track_activities || !beentry)
2458                 return;
2459
2460         /*
2461          * To minimize the time spent modifying the entry, fetch all the needed
2462          * data first.
2463          */
2464         start_timestamp = GetCurrentStatementStartTimestamp();
2465
2466         len = strlen(cmd_str);
2467         len = pg_mbcliplen(cmd_str, len, pgstat_track_activity_query_size - 1);
2468
2469         /*
2470          * Update my status entry, following the protocol of bumping
2471          * st_changecount before and after.  We use a volatile pointer here to
2472          * ensure the compiler doesn't try to get cute.
2473          */
2474         beentry->st_changecount++;
2475
2476         beentry->st_activity_start_timestamp = start_timestamp;
2477         memcpy((char *) beentry->st_activity, cmd_str, len);
2478         beentry->st_activity[len] = '\0';
2479
2480         beentry->st_changecount++;
2481         Assert((beentry->st_changecount & 1) == 0);
2482 }
2483
2484 /* ----------
2485  * pgstat_report_appname() -
2486  *
2487  *      Called to update our application name.
2488  * ----------
2489  */
2490 void
2491 pgstat_report_appname(const char *appname)
2492 {
2493         volatile PgBackendStatus *beentry = MyBEEntry;
2494         int                     len;
2495
2496         if (!beentry)
2497                 return;
2498
2499         /* This should be unnecessary if GUC did its job, but be safe */
2500         len = pg_mbcliplen(appname, strlen(appname), NAMEDATALEN - 1);
2501
2502         /*
2503          * Update my status entry, following the protocol of bumping
2504          * st_changecount before and after.  We use a volatile pointer here to
2505          * ensure the compiler doesn't try to get cute.
2506          */
2507         beentry->st_changecount++;
2508
2509         memcpy((char *) beentry->st_appname, appname, len);
2510         beentry->st_appname[len] = '\0';
2511
2512         beentry->st_changecount++;
2513         Assert((beentry->st_changecount & 1) == 0);
2514 }
2515
2516 /*
2517  * Report current transaction start timestamp as the specified value.
2518  * Zero means there is no active transaction.
2519  */
2520 void
2521 pgstat_report_xact_timestamp(TimestampTz tstamp)
2522 {
2523         volatile PgBackendStatus *beentry = MyBEEntry;
2524
2525         if (!pgstat_track_activities || !beentry)
2526                 return;
2527
2528         /*
2529          * Update my status entry, following the protocol of bumping
2530          * st_changecount before and after.  We use a volatile pointer here to
2531          * ensure the compiler doesn't try to get cute.
2532          */
2533         beentry->st_changecount++;
2534         beentry->st_xact_start_timestamp = tstamp;
2535         beentry->st_changecount++;
2536         Assert((beentry->st_changecount & 1) == 0);
2537 }
2538
2539 /* ----------
2540  * pgstat_report_waiting() -
2541  *
2542  *      Called from lock manager to report beginning or end of a lock wait.
2543  *
2544  * NB: this *must* be able to survive being called before MyBEEntry has been
2545  * initialized.
2546  * ----------
2547  */
2548 void
2549 pgstat_report_waiting(bool waiting)
2550 {
2551         volatile PgBackendStatus *beentry = MyBEEntry;
2552
2553         if (!pgstat_track_activities || !beentry)
2554                 return;
2555
2556         /*
2557          * Since this is a single-byte field in a struct that only this process
2558          * may modify, there seems no need to bother with the st_changecount
2559          * protocol.  The update must appear atomic in any case.
2560          */
2561         beentry->st_waiting = waiting;
2562 }
2563
2564
2565 /* ----------
2566  * pgstat_read_current_status() -
2567  *
2568  *      Copy the current contents of the PgBackendStatus array to local memory,
2569  *      if not already done in this transaction.
2570  * ----------
2571  */
2572 static void
2573 pgstat_read_current_status(void)
2574 {
2575         volatile PgBackendStatus *beentry;
2576         PgBackendStatus *localtable;
2577         PgBackendStatus *localentry;
2578         char       *localappname,
2579                            *localactivity;
2580         int                     i;
2581
2582         Assert(!pgStatRunningInCollector);
2583         if (localBackendStatusTable)
2584                 return;                                 /* already done */
2585
2586         pgstat_setup_memcxt();
2587
2588         localtable = (PgBackendStatus *)
2589                 MemoryContextAlloc(pgStatLocalContext,
2590                                                    sizeof(PgBackendStatus) * MaxBackends);
2591         localappname = (char *)
2592                 MemoryContextAlloc(pgStatLocalContext,
2593                                                    NAMEDATALEN * MaxBackends);
2594         localactivity = (char *)
2595                 MemoryContextAlloc(pgStatLocalContext,
2596                                                    pgstat_track_activity_query_size * MaxBackends);
2597         localNumBackends = 0;
2598
2599         beentry = BackendStatusArray;
2600         localentry = localtable;
2601         for (i = 1; i <= MaxBackends; i++)
2602         {
2603                 /*
2604                  * Follow the protocol of retrying if st_changecount changes while we
2605                  * copy the entry, or if it's odd.  (The check for odd is needed to
2606                  * cover the case where we are able to completely copy the entry while
2607                  * the source backend is between increment steps.)      We use a volatile
2608                  * pointer here to ensure the compiler doesn't try to get cute.
2609                  */
2610                 for (;;)
2611                 {
2612                         int                     save_changecount = beentry->st_changecount;
2613
2614                         localentry->st_procpid = beentry->st_procpid;
2615                         if (localentry->st_procpid > 0)
2616                         {
2617                                 memcpy(localentry, (char *) beentry, sizeof(PgBackendStatus));
2618
2619                                 /*
2620                                  * strcpy is safe even if the string is modified concurrently,
2621                                  * because there's always a \0 at the end of the buffer.
2622                                  */
2623                                 strcpy(localappname, (char *) beentry->st_appname);
2624                                 localentry->st_appname = localappname;
2625                                 strcpy(localactivity, (char *) beentry->st_activity);
2626                                 localentry->st_activity = localactivity;
2627                         }
2628
2629                         if (save_changecount == beentry->st_changecount &&
2630                                 (save_changecount & 1) == 0)
2631                                 break;
2632
2633                         /* Make sure we can break out of loop if stuck... */
2634                         CHECK_FOR_INTERRUPTS();
2635                 }
2636
2637                 beentry++;
2638                 /* Only valid entries get included into the local array */
2639                 if (localentry->st_procpid > 0)
2640                 {
2641                         localentry++;
2642                         localappname += NAMEDATALEN;
2643                         localactivity += pgstat_track_activity_query_size;
2644                         localNumBackends++;
2645                 }
2646         }
2647
2648         /* Set the pointer only after completion of a valid table */
2649         localBackendStatusTable = localtable;
2650 }
2651
2652
2653 /* ----------
2654  * pgstat_get_backend_current_activity() -
2655  *
2656  *      Return a string representing the current activity of the backend with
2657  *      the specified PID.      This looks directly at the BackendStatusArray,
2658  *      and so will provide current information regardless of the age of our
2659  *      transaction's snapshot of the status array.
2660  *
2661  *      It is the caller's responsibility to invoke this only for backends whose
2662  *      state is expected to remain stable while the result is in use.  The
2663  *      only current use is in deadlock reporting, where we can expect that
2664  *      the target backend is blocked on a lock.  (There are corner cases
2665  *      where the target's wait could get aborted while we are looking at it,
2666  *      but the very worst consequence is to return a pointer to a string
2667  *      that's been changed, so we won't worry too much.)
2668  *
2669  *      Note: return strings for special cases match pg_stat_get_backend_activity.
2670  * ----------
2671  */
2672 const char *
2673 pgstat_get_backend_current_activity(int pid, bool checkUser)
2674 {
2675         PgBackendStatus *beentry;
2676         int                     i;
2677
2678         beentry = BackendStatusArray;
2679         for (i = 1; i <= MaxBackends; i++)
2680         {
2681                 /*
2682                  * Although we expect the target backend's entry to be stable, that
2683                  * doesn't imply that anyone else's is.  To avoid identifying the
2684                  * wrong backend, while we check for a match to the desired PID we
2685                  * must follow the protocol of retrying if st_changecount changes
2686                  * while we examine the entry, or if it's odd.  (This might be
2687                  * unnecessary, since fetching or storing an int is almost certainly
2688                  * atomic, but let's play it safe.)  We use a volatile pointer here to
2689                  * ensure the compiler doesn't try to get cute.
2690                  */
2691                 volatile PgBackendStatus *vbeentry = beentry;
2692                 bool            found;
2693
2694                 for (;;)
2695                 {
2696                         int                     save_changecount = vbeentry->st_changecount;
2697
2698                         found = (vbeentry->st_procpid == pid);
2699
2700                         if (save_changecount == vbeentry->st_changecount &&
2701                                 (save_changecount & 1) == 0)
2702                                 break;
2703
2704                         /* Make sure we can break out of loop if stuck... */
2705                         CHECK_FOR_INTERRUPTS();
2706                 }
2707
2708                 if (found)
2709                 {
2710                         /* Now it is safe to use the non-volatile pointer */
2711                         if (checkUser && !superuser() && beentry->st_userid != GetUserId())
2712                                 return "<insufficient privilege>";
2713                         else if (*(beentry->st_activity) == '\0')
2714                                 return "<command string not enabled>";
2715                         else
2716                                 return beentry->st_activity;
2717                 }
2718
2719                 beentry++;
2720         }
2721
2722         /* If we get here, caller is in error ... */
2723         return "<backend information not available>";
2724 }
2725
2726
2727 /* ------------------------------------------------------------
2728  * Local support functions follow
2729  * ------------------------------------------------------------
2730  */
2731
2732
2733 /* ----------
2734  * pgstat_setheader() -
2735  *
2736  *              Set common header fields in a statistics message
2737  * ----------
2738  */
2739 static void
2740 pgstat_setheader(PgStat_MsgHdr *hdr, StatMsgType mtype)
2741 {
2742         hdr->m_type = mtype;
2743 }
2744
2745
2746 /* ----------
2747  * pgstat_send() -
2748  *
2749  *              Send out one statistics message to the collector
2750  * ----------
2751  */
2752 static void
2753 pgstat_send(void *msg, int len)
2754 {
2755         int                     rc;
2756
2757         if (pgStatSock == PGINVALID_SOCKET)
2758                 return;
2759
2760         ((PgStat_MsgHdr *) msg)->m_size = len;
2761
2762         /* We'll retry after EINTR, but ignore all other failures */
2763         do
2764         {
2765                 rc = send(pgStatSock, msg, len, 0);
2766         } while (rc < 0 && errno == EINTR);
2767
2768 #ifdef USE_ASSERT_CHECKING
2769         /* In debug builds, log send failures ... */
2770         if (rc < 0)
2771                 elog(LOG, "could not send to statistics collector: %m");
2772 #endif
2773 }
2774
2775 /* ----------
2776  * pgstat_send_bgwriter() -
2777  *
2778  *              Send bgwriter statistics to the collector
2779  * ----------
2780  */
2781 void
2782 pgstat_send_bgwriter(void)
2783 {
2784         /* We assume this initializes to zeroes */
2785         static const PgStat_MsgBgWriter all_zeroes;
2786
2787         /*
2788          * This function can be called even if nothing at all has happened. In
2789          * this case, avoid sending a completely empty message to the stats
2790          * collector.
2791          */
2792         if (memcmp(&BgWriterStats, &all_zeroes, sizeof(PgStat_MsgBgWriter)) == 0)
2793                 return;
2794
2795         /*
2796          * Prepare and send the message
2797          */
2798         pgstat_setheader(&BgWriterStats.m_hdr, PGSTAT_MTYPE_BGWRITER);
2799         pgstat_send(&BgWriterStats, sizeof(BgWriterStats));
2800
2801         /*
2802          * Clear out the statistics buffer, so it can be re-used.
2803          */
2804         MemSet(&BgWriterStats, 0, sizeof(BgWriterStats));
2805 }
2806
2807
2808 /* ----------
2809  * PgstatCollectorMain() -
2810  *
2811  *      Start up the statistics collector process.      This is the body of the
2812  *      postmaster child process.
2813  *
2814  *      The argc/argv parameters are valid only in EXEC_BACKEND case.
2815  * ----------
2816  */
2817 NON_EXEC_STATIC void
2818 PgstatCollectorMain(int argc, char *argv[])
2819 {
2820         int                     len;
2821         PgStat_Msg      msg;
2822
2823 #ifndef WIN32
2824 #ifdef HAVE_POLL
2825         struct pollfd input_fd;
2826 #else
2827         struct timeval sel_timeout;
2828         fd_set          rfds;
2829 #endif
2830 #endif
2831
2832         IsUnderPostmaster = true;       /* we are a postmaster subprocess now */
2833
2834         MyProcPid = getpid();           /* reset MyProcPid */
2835
2836         MyStartTime = time(NULL);       /* record Start Time for logging */
2837
2838         /*
2839          * If possible, make this process a group leader, so that the postmaster
2840          * can signal any child processes too.  (pgstat probably never has any
2841          * child processes, but for consistency we make all postmaster child
2842          * processes do this.)
2843          */
2844 #ifdef HAVE_SETSID
2845         if (setsid() < 0)
2846                 elog(FATAL, "setsid() failed: %m");
2847 #endif
2848
2849         /*
2850          * Ignore all signals usually bound to some action in the postmaster,
2851          * except SIGQUIT.
2852          */
2853         pqsignal(SIGHUP, pgstat_sighup_handler);
2854         pqsignal(SIGINT, SIG_IGN);
2855         pqsignal(SIGTERM, SIG_IGN);
2856         pqsignal(SIGQUIT, pgstat_exit);
2857         pqsignal(SIGALRM, SIG_IGN);
2858         pqsignal(SIGPIPE, SIG_IGN);
2859         pqsignal(SIGUSR1, SIG_IGN);
2860         pqsignal(SIGUSR2, SIG_IGN);
2861         pqsignal(SIGCHLD, SIG_DFL);
2862         pqsignal(SIGTTIN, SIG_DFL);
2863         pqsignal(SIGTTOU, SIG_DFL);
2864         pqsignal(SIGCONT, SIG_DFL);
2865         pqsignal(SIGWINCH, SIG_DFL);
2866         PG_SETMASK(&UnBlockSig);
2867
2868         /*
2869          * Identify myself via ps
2870          */
2871         init_ps_display("stats collector process", "", "", "");
2872
2873         /*
2874          * Arrange to write the initial status file right away
2875          */
2876         last_statrequest = GetCurrentTimestamp();
2877         last_statwrite = last_statrequest - 1;
2878
2879         /*
2880          * Read in an existing statistics stats file or initialize the stats to
2881          * zero.
2882          */
2883         pgStatRunningInCollector = true;
2884         pgStatDBHash = pgstat_read_statsfile(InvalidOid, true);
2885
2886         /*
2887          * Setup the descriptor set for select(2).      Since only one bit in the set
2888          * ever changes, we need not repeat FD_ZERO each time.
2889          */
2890 #if !defined(HAVE_POLL) && !defined(WIN32)
2891         FD_ZERO(&rfds);
2892 #endif
2893
2894         /*
2895          * Loop to process messages until we get SIGQUIT or detect ungraceful
2896          * death of our parent postmaster.
2897          *
2898          * For performance reasons, we don't want to do a PostmasterIsAlive() test
2899          * after every message; instead, do it only when select()/poll() is
2900          * interrupted by timeout.      In essence, we'll stay alive as long as
2901          * backends keep sending us stuff often, even if the postmaster is gone.
2902          */
2903         for (;;)
2904         {
2905                 int                     got_data;
2906
2907                 /*
2908                  * Quit if we get SIGQUIT from the postmaster.
2909                  */
2910                 if (need_exit)
2911                         break;
2912
2913                 /*
2914                  * Reload configuration if we got SIGHUP from the postmaster.
2915                  */
2916                 if (got_SIGHUP)
2917                 {
2918                         ProcessConfigFile(PGC_SIGHUP);
2919                         got_SIGHUP = false;
2920                 }
2921
2922                 /*
2923                  * Write the stats file if a new request has arrived that is not
2924                  * satisfied by existing file.
2925                  */
2926                 if (last_statwrite < last_statrequest)
2927                         pgstat_write_statsfile(false);
2928
2929                 /*
2930                  * Wait for a message to arrive; but not for more than
2931                  * PGSTAT_SELECT_TIMEOUT seconds. (This determines how quickly we will
2932                  * shut down after an ungraceful postmaster termination; so it needn't
2933                  * be very fast.  However, on some systems SIGQUIT won't interrupt the
2934                  * poll/select call, so this also limits speed of response to SIGQUIT,
2935                  * which is more important.)
2936                  *
2937                  * We use poll(2) if available, otherwise select(2). Win32 has its own
2938                  * implementation.
2939                  */
2940 #ifndef WIN32
2941 #ifdef HAVE_POLL
2942                 input_fd.fd = pgStatSock;
2943                 input_fd.events = POLLIN | POLLERR;
2944                 input_fd.revents = 0;
2945
2946                 if (poll(&input_fd, 1, PGSTAT_SELECT_TIMEOUT * 1000) < 0)
2947                 {
2948                         if (errno == EINTR)
2949                                 continue;
2950                         ereport(ERROR,
2951                                         (errcode_for_socket_access(),
2952                                          errmsg("poll() failed in statistics collector: %m")));
2953                 }
2954
2955                 got_data = (input_fd.revents != 0);
2956 #else                                                   /* !HAVE_POLL */
2957
2958                 FD_SET(pgStatSock, &rfds);
2959
2960                 /*
2961                  * timeout struct is modified by select() on some operating systems,
2962                  * so re-fill it each time.
2963                  */
2964                 sel_timeout.tv_sec = PGSTAT_SELECT_TIMEOUT;
2965                 sel_timeout.tv_usec = 0;
2966
2967                 if (select(pgStatSock + 1, &rfds, NULL, NULL, &sel_timeout) < 0)
2968                 {
2969                         if (errno == EINTR)
2970                                 continue;
2971                         ereport(ERROR,
2972                                         (errcode_for_socket_access(),
2973                                          errmsg("select() failed in statistics collector: %m")));
2974                 }
2975
2976                 got_data = FD_ISSET(pgStatSock, &rfds);
2977 #endif   /* HAVE_POLL */
2978 #else                                                   /* WIN32 */
2979                 got_data = pgwin32_waitforsinglesocket(pgStatSock, FD_READ,
2980                                                                                            PGSTAT_SELECT_TIMEOUT * 1000);
2981 #endif
2982
2983                 /*
2984                  * If there is a message on the socket, read it and check for
2985                  * validity.
2986                  */
2987                 if (got_data)
2988                 {
2989                         len = recv(pgStatSock, (char *) &msg,
2990                                            sizeof(PgStat_Msg), 0);
2991                         if (len < 0)
2992                         {
2993                                 if (errno == EINTR)
2994                                         continue;
2995                                 ereport(ERROR,
2996                                                 (errcode_for_socket_access(),
2997                                                  errmsg("could not read statistics message: %m")));
2998                         }
2999
3000                         /*
3001                          * We ignore messages that are smaller than our common header
3002                          */
3003                         if (len < sizeof(PgStat_MsgHdr))
3004                                 continue;
3005
3006                         /*
3007                          * The received length must match the length in the header
3008                          */
3009                         if (msg.msg_hdr.m_size != len)
3010                                 continue;
3011
3012                         /*
3013                          * O.K. - we accept this message.  Process it.
3014                          */
3015                         switch (msg.msg_hdr.m_type)
3016                         {
3017                                 case PGSTAT_MTYPE_DUMMY:
3018                                         break;
3019
3020                                 case PGSTAT_MTYPE_INQUIRY:
3021                                         pgstat_recv_inquiry((PgStat_MsgInquiry *) &msg, len);
3022                                         break;
3023
3024                                 case PGSTAT_MTYPE_TABSTAT:
3025                                         pgstat_recv_tabstat((PgStat_MsgTabstat *) &msg, len);
3026                                         break;
3027
3028                                 case PGSTAT_MTYPE_TABPURGE:
3029                                         pgstat_recv_tabpurge((PgStat_MsgTabpurge *) &msg, len);
3030                                         break;
3031
3032                                 case PGSTAT_MTYPE_DROPDB:
3033                                         pgstat_recv_dropdb((PgStat_MsgDropdb *) &msg, len);
3034                                         break;
3035
3036                                 case PGSTAT_MTYPE_RESETCOUNTER:
3037                                         pgstat_recv_resetcounter((PgStat_MsgResetcounter *) &msg,
3038                                                                                          len);
3039                                         break;
3040
3041                                 case PGSTAT_MTYPE_RESETSHAREDCOUNTER:
3042                                         pgstat_recv_resetsharedcounter(
3043                                                                            (PgStat_MsgResetsharedcounter *) &msg,
3044                                                                                                    len);
3045                                         break;
3046
3047                                 case PGSTAT_MTYPE_RESETSINGLECOUNTER:
3048                                         pgstat_recv_resetsinglecounter(
3049                                                                            (PgStat_MsgResetsinglecounter *) &msg,
3050                                                                                                    len);
3051                                         break;
3052
3053                                 case PGSTAT_MTYPE_AUTOVAC_START:
3054                                         pgstat_recv_autovac((PgStat_MsgAutovacStart *) &msg, len);
3055                                         break;
3056
3057                                 case PGSTAT_MTYPE_VACUUM:
3058                                         pgstat_recv_vacuum((PgStat_MsgVacuum *) &msg, len);
3059                                         break;
3060
3061                                 case PGSTAT_MTYPE_ANALYZE:
3062                                         pgstat_recv_analyze((PgStat_MsgAnalyze *) &msg, len);
3063                                         break;
3064
3065                                 case PGSTAT_MTYPE_BGWRITER:
3066                                         pgstat_recv_bgwriter((PgStat_MsgBgWriter *) &msg, len);
3067                                         break;
3068
3069                                 case PGSTAT_MTYPE_FUNCSTAT:
3070                                         pgstat_recv_funcstat((PgStat_MsgFuncstat *) &msg, len);
3071                                         break;
3072
3073                                 case PGSTAT_MTYPE_FUNCPURGE:
3074                                         pgstat_recv_funcpurge((PgStat_MsgFuncpurge *) &msg, len);
3075                                         break;
3076
3077                                 case PGSTAT_MTYPE_RECOVERYCONFLICT:
3078                                         pgstat_recv_recoveryconflict((PgStat_MsgRecoveryConflict *) &msg, len);
3079                                         break;
3080
3081                                 default:
3082                                         break;
3083                         }
3084                 }
3085                 else
3086                 {
3087                         /*
3088                          * We can only get here if the select/poll timeout elapsed. Check
3089                          * for postmaster death.
3090                          */
3091                         if (!PostmasterIsAlive(true))
3092                                 break;
3093                 }
3094         }                                                       /* end of message-processing loop */
3095
3096         /*
3097          * Save the final stats to reuse at next startup.
3098          */
3099         pgstat_write_statsfile(true);
3100
3101         exit(0);
3102 }
3103
3104
3105 /* SIGQUIT signal handler for collector process */
3106 static void
3107 pgstat_exit(SIGNAL_ARGS)
3108 {
3109         need_exit = true;
3110 }
3111
3112 /* SIGHUP handler for collector process */
3113 static void
3114 pgstat_sighup_handler(SIGNAL_ARGS)
3115 {
3116         got_SIGHUP = true;
3117 }
3118
3119
3120 /*
3121  * Lookup the hash table entry for the specified database. If no hash
3122  * table entry exists, initialize it, if the create parameter is true.
3123  * Else, return NULL.
3124  */
3125 static PgStat_StatDBEntry *
3126 pgstat_get_db_entry(Oid databaseid, bool create)
3127 {
3128         PgStat_StatDBEntry *result;
3129         bool            found;
3130         HASHACTION      action = (create ? HASH_ENTER : HASH_FIND);
3131
3132         /* Lookup or create the hash table entry for this database */
3133         result = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
3134                                                                                                 &databaseid,
3135                                                                                                 action, &found);
3136
3137         if (!create && !found)
3138                 return NULL;
3139
3140         /* If not found, initialize the new one. */
3141         if (!found)
3142         {
3143                 HASHCTL         hash_ctl;
3144
3145                 result->tables = NULL;
3146                 result->functions = NULL;
3147                 result->n_xact_commit = 0;
3148                 result->n_xact_rollback = 0;
3149                 result->n_blocks_fetched = 0;
3150                 result->n_blocks_hit = 0;
3151                 result->n_tuples_returned = 0;
3152                 result->n_tuples_fetched = 0;
3153                 result->n_tuples_inserted = 0;
3154                 result->n_tuples_updated = 0;
3155                 result->n_tuples_deleted = 0;
3156                 result->last_autovac_time = 0;
3157                 result->n_conflict_tablespace = 0;
3158                 result->n_conflict_lock = 0;
3159                 result->n_conflict_snapshot = 0;
3160                 result->n_conflict_bufferpin = 0;
3161                 result->n_conflict_startup_deadlock = 0;
3162
3163                 memset(&hash_ctl, 0, sizeof(hash_ctl));
3164                 hash_ctl.keysize = sizeof(Oid);
3165                 hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
3166                 hash_ctl.hash = oid_hash;
3167                 result->tables = hash_create("Per-database table",
3168                                                                          PGSTAT_TAB_HASH_SIZE,
3169                                                                          &hash_ctl,
3170                                                                          HASH_ELEM | HASH_FUNCTION);
3171
3172                 hash_ctl.keysize = sizeof(Oid);
3173                 hash_ctl.entrysize = sizeof(PgStat_StatFuncEntry);
3174                 hash_ctl.hash = oid_hash;
3175                 result->functions = hash_create("Per-database function",
3176                                                                                 PGSTAT_FUNCTION_HASH_SIZE,
3177                                                                                 &hash_ctl,
3178                                                                                 HASH_ELEM | HASH_FUNCTION);
3179         }
3180
3181         return result;
3182 }
3183
3184
3185 /*
3186  * Lookup the hash table entry for the specified table. If no hash
3187  * table entry exists, initialize it, if the create parameter is true.
3188  * Else, return NULL.
3189  */
3190 static PgStat_StatTabEntry *
3191 pgstat_get_tab_entry(PgStat_StatDBEntry *dbentry, Oid tableoid, bool create)
3192 {
3193         PgStat_StatTabEntry *result;
3194         bool            found;
3195         HASHACTION      action = (create ? HASH_ENTER : HASH_FIND);
3196
3197         /* Lookup or create the hash table entry for this table */
3198         result = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
3199                                                                                                  &tableoid,
3200                                                                                                  action, &found);
3201
3202         if (!create && !found)
3203                 return NULL;
3204
3205         /* If not found, initialize the new one. */
3206         if (!found)
3207         {
3208                 result->numscans = 0;
3209                 result->tuples_returned = 0;
3210                 result->tuples_fetched = 0;
3211                 result->tuples_inserted = 0;
3212                 result->tuples_updated = 0;
3213                 result->tuples_deleted = 0;
3214                 result->tuples_hot_updated = 0;
3215                 result->n_live_tuples = 0;
3216                 result->n_dead_tuples = 0;
3217                 result->changes_since_analyze = 0;
3218                 result->blocks_fetched = 0;
3219                 result->blocks_hit = 0;
3220
3221                 result->vacuum_timestamp = 0;
3222                 result->autovac_vacuum_timestamp = 0;
3223                 result->analyze_timestamp = 0;
3224                 result->autovac_analyze_timestamp = 0;
3225                 result->vacuum_count = 0;
3226                 result->autovac_vacuum_count = 0;
3227                 result->analyze_count = 0;
3228                 result->autovac_analyze_count = 0;
3229         }
3230
3231         return result;
3232 }
3233
3234
3235 /* ----------
3236  * pgstat_write_statsfile() -
3237  *
3238  *      Tell the news.
3239  *      If writing to the permanent file (happens when the collector is
3240  *      shutting down only), remove the temporary file so that backends
3241  *      starting up under a new postmaster can't read the old data before
3242  *      the new collector is ready.
3243  * ----------
3244  */
3245 static void
3246 pgstat_write_statsfile(bool permanent)
3247 {
3248         HASH_SEQ_STATUS hstat;
3249         HASH_SEQ_STATUS tstat;
3250         HASH_SEQ_STATUS fstat;
3251         PgStat_StatDBEntry *dbentry;
3252         PgStat_StatTabEntry *tabentry;
3253         PgStat_StatFuncEntry *funcentry;
3254         FILE       *fpout;
3255         int32           format_id;
3256         const char *tmpfile = permanent ? PGSTAT_STAT_PERMANENT_TMPFILE : pgstat_stat_tmpname;
3257         const char *statfile = permanent ? PGSTAT_STAT_PERMANENT_FILENAME : pgstat_stat_filename;
3258
3259         /*
3260          * Open the statistics temp file to write out the current values.
3261          */
3262         fpout = AllocateFile(tmpfile, PG_BINARY_W);
3263         if (fpout == NULL)
3264         {
3265                 ereport(LOG,
3266                                 (errcode_for_file_access(),
3267                                  errmsg("could not open temporary statistics file \"%s\": %m",
3268                                                 tmpfile)));
3269                 return;
3270         }
3271
3272         /*
3273          * Set the timestamp of the stats file.
3274          */
3275         globalStats.stats_timestamp = GetCurrentTimestamp();
3276
3277         /*
3278          * Write the file header --- currently just a format ID.
3279          */
3280         format_id = PGSTAT_FILE_FORMAT_ID;
3281         fwrite(&format_id, sizeof(format_id), 1, fpout);
3282
3283         /*
3284          * Write global stats struct
3285          */
3286         fwrite(&globalStats, sizeof(globalStats), 1, fpout);
3287
3288         /*
3289          * Walk through the database table.
3290          */
3291         hash_seq_init(&hstat, pgStatDBHash);
3292         while ((dbentry = (PgStat_StatDBEntry *) hash_seq_search(&hstat)) != NULL)
3293         {
3294                 /*
3295                  * Write out the DB entry including the number of live backends. We
3296                  * don't write the tables or functions pointers, since they're of no
3297                  * use to any other process.
3298                  */
3299                 fputc('D', fpout);
3300                 fwrite(dbentry, offsetof(PgStat_StatDBEntry, tables), 1, fpout);
3301
3302                 /*
3303                  * Walk through the database's access stats per table.
3304                  */
3305                 hash_seq_init(&tstat, dbentry->tables);
3306                 while ((tabentry = (PgStat_StatTabEntry *) hash_seq_search(&tstat)) != NULL)
3307                 {
3308                         fputc('T', fpout);
3309                         fwrite(tabentry, sizeof(PgStat_StatTabEntry), 1, fpout);
3310                 }
3311
3312                 /*
3313                  * Walk through the database's function stats table.
3314                  */
3315                 hash_seq_init(&fstat, dbentry->functions);
3316                 while ((funcentry = (PgStat_StatFuncEntry *) hash_seq_search(&fstat)) != NULL)
3317                 {
3318                         fputc('F', fpout);
3319                         fwrite(funcentry, sizeof(PgStat_StatFuncEntry), 1, fpout);
3320                 }
3321
3322                 /*
3323                  * Mark the end of this DB
3324                  */
3325                 fputc('d', fpout);
3326         }
3327
3328         /*
3329          * No more output to be done. Close the temp file and replace the old
3330          * pgstat.stat with it.  The ferror() check replaces testing for error
3331          * after each individual fputc or fwrite above.
3332          */
3333         fputc('E', fpout);
3334
3335         if (ferror(fpout))
3336         {
3337                 ereport(LOG,
3338                                 (errcode_for_file_access(),
3339                            errmsg("could not write temporary statistics file \"%s\": %m",
3340                                           tmpfile)));
3341                 FreeFile(fpout);
3342                 unlink(tmpfile);
3343         }
3344         else if (FreeFile(fpout) < 0)
3345         {
3346                 ereport(LOG,
3347                                 (errcode_for_file_access(),
3348                            errmsg("could not close temporary statistics file \"%s\": %m",
3349                                           tmpfile)));
3350                 unlink(tmpfile);
3351         }
3352         else if (rename(tmpfile, statfile) < 0)
3353         {
3354                 ereport(LOG,
3355                                 (errcode_for_file_access(),
3356                                  errmsg("could not rename temporary statistics file \"%s\" to \"%s\": %m",
3357                                                 tmpfile, statfile)));
3358                 unlink(tmpfile);
3359         }
3360         else
3361         {
3362                 /*
3363                  * Successful write, so update last_statwrite.
3364                  */
3365                 last_statwrite = globalStats.stats_timestamp;
3366
3367                 /*
3368                  * If there is clock skew between backends and the collector, we could
3369                  * receive a stats request time that's in the future.  If so, complain
3370                  * and reset last_statrequest.  Resetting ensures that no inquiry
3371                  * message can cause more than one stats file write to occur.
3372                  */
3373                 if (last_statrequest > last_statwrite)
3374                 {
3375                         char       *reqtime;
3376                         char       *mytime;
3377
3378                         /* Copy because timestamptz_to_str returns a static buffer */
3379                         reqtime = pstrdup(timestamptz_to_str(last_statrequest));
3380                         mytime = pstrdup(timestamptz_to_str(last_statwrite));
3381                         elog(LOG, "last_statrequest %s is later than collector's time %s",
3382                                  reqtime, mytime);
3383                         pfree(reqtime);
3384                         pfree(mytime);
3385
3386                         last_statrequest = last_statwrite;
3387                 }
3388         }
3389
3390         if (permanent)
3391                 unlink(pgstat_stat_filename);
3392 }
3393
3394
3395 /* ----------
3396  * pgstat_read_statsfile() -
3397  *
3398  *      Reads in an existing statistics collector file and initializes the
3399  *      databases' hash table (whose entries point to the tables' hash tables).
3400  * ----------
3401  */
3402 static HTAB *
3403 pgstat_read_statsfile(Oid onlydb, bool permanent)
3404 {
3405         PgStat_StatDBEntry *dbentry;
3406         PgStat_StatDBEntry dbbuf;
3407         PgStat_StatTabEntry *tabentry;
3408         PgStat_StatTabEntry tabbuf;
3409         PgStat_StatFuncEntry funcbuf;
3410         PgStat_StatFuncEntry *funcentry;
3411         HASHCTL         hash_ctl;
3412         HTAB       *dbhash;
3413         HTAB       *tabhash = NULL;
3414         HTAB       *funchash = NULL;
3415         FILE       *fpin;
3416         int32           format_id;
3417         bool            found;
3418         const char *statfile = permanent ? PGSTAT_STAT_PERMANENT_FILENAME : pgstat_stat_filename;
3419
3420         /*
3421          * The tables will live in pgStatLocalContext.
3422          */
3423         pgstat_setup_memcxt();
3424
3425         /*
3426          * Create the DB hashtable
3427          */
3428         memset(&hash_ctl, 0, sizeof(hash_ctl));
3429         hash_ctl.keysize = sizeof(Oid);
3430         hash_ctl.entrysize = sizeof(PgStat_StatDBEntry);
3431         hash_ctl.hash = oid_hash;
3432         hash_ctl.hcxt = pgStatLocalContext;
3433         dbhash = hash_create("Databases hash", PGSTAT_DB_HASH_SIZE, &hash_ctl,
3434                                                  HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT);
3435
3436         /*
3437          * Clear out global statistics so they start from zero in case we can't
3438          * load an existing statsfile.
3439          */
3440         memset(&globalStats, 0, sizeof(globalStats));
3441
3442         /*
3443          * Try to open the status file. If it doesn't exist, the backends simply
3444          * return zero for anything and the collector simply starts from scratch
3445          * with empty counters.
3446          *
3447          * ENOENT is a possibility if the stats collector is not running or has
3448          * not yet written the stats file the first time.  Any other failure
3449          * condition is suspicious.
3450          */
3451         if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
3452         {
3453                 if (errno != ENOENT)
3454                         ereport(pgStatRunningInCollector ? LOG : WARNING,
3455                                         (errcode_for_file_access(),
3456                                          errmsg("could not open statistics file \"%s\": %m",
3457                                                         statfile)));
3458                 return dbhash;
3459         }
3460
3461         /*
3462          * Verify it's of the expected format.
3463          */
3464         if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id)
3465                 || format_id != PGSTAT_FILE_FORMAT_ID)
3466         {
3467                 ereport(pgStatRunningInCollector ? LOG : WARNING,
3468                                 (errmsg("corrupted statistics file \"%s\"", statfile)));
3469                 goto done;
3470         }
3471
3472         /*
3473          * Read global stats struct
3474          */
3475         if (fread(&globalStats, 1, sizeof(globalStats), fpin) != sizeof(globalStats))
3476         {
3477                 ereport(pgStatRunningInCollector ? LOG : WARNING,
3478                                 (errmsg("corrupted statistics file \"%s\"", statfile)));
3479                 goto done;
3480         }
3481
3482         /*
3483          * We found an existing collector stats file. Read it and put all the
3484          * hashtable entries into place.
3485          */
3486         for (;;)
3487         {
3488                 switch (fgetc(fpin))
3489                 {
3490                                 /*
3491                                  * 'D'  A PgStat_StatDBEntry struct describing a database
3492                                  * follows. Subsequently, zero to many 'T' and 'F' entries
3493                                  * will follow until a 'd' is encountered.
3494                                  */
3495                         case 'D':
3496                                 if (fread(&dbbuf, 1, offsetof(PgStat_StatDBEntry, tables),
3497                                                   fpin) != offsetof(PgStat_StatDBEntry, tables))
3498                                 {
3499                                         ereport(pgStatRunningInCollector ? LOG : WARNING,
3500                                                         (errmsg("corrupted statistics file \"%s\"",
3501                                                                         statfile)));
3502                                         goto done;
3503                                 }
3504
3505                                 /*
3506                                  * Add to the DB hash
3507                                  */
3508                                 dbentry = (PgStat_StatDBEntry *) hash_search(dbhash,
3509                                                                                                   (void *) &dbbuf.databaseid,
3510                                                                                                                          HASH_ENTER,
3511                                                                                                                          &found);
3512                                 if (found)
3513                                 {
3514                                         ereport(pgStatRunningInCollector ? LOG : WARNING,
3515                                                         (errmsg("corrupted statistics file \"%s\"",
3516                                                                         statfile)));
3517                                         goto done;
3518                                 }
3519
3520                                 memcpy(dbentry, &dbbuf, sizeof(PgStat_StatDBEntry));
3521                                 dbentry->tables = NULL;
3522                                 dbentry->functions = NULL;
3523
3524                                 /*
3525                                  * Don't collect tables if not the requested DB (or the
3526                                  * shared-table info)
3527                                  */
3528                                 if (onlydb != InvalidOid)
3529                                 {
3530                                         if (dbbuf.databaseid != onlydb &&
3531                                                 dbbuf.databaseid != InvalidOid)
3532                                                 break;
3533                                 }
3534
3535                                 memset(&hash_ctl, 0, sizeof(hash_ctl));
3536                                 hash_ctl.keysize = sizeof(Oid);
3537                                 hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
3538                                 hash_ctl.hash = oid_hash;
3539                                 hash_ctl.hcxt = pgStatLocalContext;
3540                                 dbentry->tables = hash_create("Per-database table",
3541                                                                                           PGSTAT_TAB_HASH_SIZE,
3542                                                                                           &hash_ctl,
3543                                                                    HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT);
3544
3545                                 hash_ctl.keysize = sizeof(Oid);
3546                                 hash_ctl.entrysize = sizeof(PgStat_StatFuncEntry);
3547                                 hash_ctl.hash = oid_hash;
3548                                 hash_ctl.hcxt = pgStatLocalContext;
3549                                 dbentry->functions = hash_create("Per-database function",
3550                                                                                                  PGSTAT_FUNCTION_HASH_SIZE,
3551                                                                                                  &hash_ctl,
3552                                                                    HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT);
3553
3554                                 /*
3555                                  * Arrange that following records add entries to this
3556                                  * database's hash tables.
3557                                  */
3558                                 tabhash = dbentry->tables;
3559                                 funchash = dbentry->functions;
3560                                 break;
3561
3562                                 /*
3563                                  * 'd'  End of this database.
3564                                  */
3565                         case 'd':
3566                                 tabhash = NULL;
3567                                 funchash = NULL;
3568                                 break;
3569
3570                                 /*
3571                                  * 'T'  A PgStat_StatTabEntry follows.
3572                                  */
3573                         case 'T':
3574                                 if (fread(&tabbuf, 1, sizeof(PgStat_StatTabEntry),
3575                                                   fpin) != sizeof(PgStat_StatTabEntry))
3576                                 {
3577                                         ereport(pgStatRunningInCollector ? LOG : WARNING,
3578                                                         (errmsg("corrupted statistics file \"%s\"",
3579                                                                         statfile)));
3580                                         goto done;
3581                                 }
3582
3583                                 /*
3584                                  * Skip if table belongs to a not requested database.
3585                                  */
3586                                 if (tabhash == NULL)
3587                                         break;
3588
3589                                 tabentry = (PgStat_StatTabEntry *) hash_search(tabhash,
3590                                                                                                         (void *) &tabbuf.tableid,
3591                                                                                                                  HASH_ENTER, &found);
3592
3593                                 if (found)
3594                                 {
3595                                         ereport(pgStatRunningInCollector ? LOG : WARNING,
3596                                                         (errmsg("corrupted statistics file \"%s\"",
3597                                                                         statfile)));
3598                                         goto done;
3599                                 }
3600
3601                                 memcpy(tabentry, &tabbuf, sizeof(tabbuf));
3602                                 break;
3603
3604                                 /*
3605                                  * 'F'  A PgStat_StatFuncEntry follows.
3606                                  */
3607                         case 'F':
3608                                 if (fread(&funcbuf, 1, sizeof(PgStat_StatFuncEntry),
3609                                                   fpin) != sizeof(PgStat_StatFuncEntry))
3610                                 {
3611                                         ereport(pgStatRunningInCollector ? LOG : WARNING,
3612                                                         (errmsg("corrupted statistics file \"%s\"",
3613                                                                         statfile)));
3614                                         goto done;
3615                                 }
3616
3617                                 /*
3618                                  * Skip if function belongs to a not requested database.
3619                                  */
3620                                 if (funchash == NULL)
3621                                         break;
3622
3623                                 funcentry = (PgStat_StatFuncEntry *) hash_search(funchash,
3624                                                                                                 (void *) &funcbuf.functionid,
3625                                                                                                                  HASH_ENTER, &found);
3626
3627                                 if (found)
3628                                 {
3629                                         ereport(pgStatRunningInCollector ? LOG : WARNING,
3630                                                         (errmsg("corrupted statistics file \"%s\"",
3631                                                                         statfile)));
3632                                         goto done;
3633                                 }
3634
3635                                 memcpy(funcentry, &funcbuf, sizeof(funcbuf));
3636                                 break;
3637
3638                                 /*
3639                                  * 'E'  The EOF marker of a complete stats file.
3640                                  */
3641                         case 'E':
3642                                 goto done;
3643
3644                         default:
3645                                 ereport(pgStatRunningInCollector ? LOG : WARNING,
3646                                                 (errmsg("corrupted statistics file \"%s\"",
3647                                                                 statfile)));
3648                                 goto done;
3649                 }
3650         }
3651
3652 done:
3653         FreeFile(fpin);
3654
3655         if (permanent)
3656                 unlink(PGSTAT_STAT_PERMANENT_FILENAME);
3657
3658         return dbhash;
3659 }
3660
3661 /* ----------
3662  * pgstat_read_statsfile_timestamp() -
3663  *
3664  *      Attempt to fetch the timestamp of an existing stats file.
3665  *      Returns TRUE if successful (timestamp is stored at *ts).
3666  * ----------
3667  */
3668 static bool
3669 pgstat_read_statsfile_timestamp(bool permanent, TimestampTz *ts)
3670 {
3671         PgStat_GlobalStats myGlobalStats;
3672         FILE       *fpin;
3673         int32           format_id;
3674         const char *statfile = permanent ? PGSTAT_STAT_PERMANENT_FILENAME : pgstat_stat_filename;
3675
3676         /*
3677          * Try to open the status file.  As above, anything but ENOENT is worthy
3678          * of complaining about.
3679          */
3680         if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
3681         {
3682                 if (errno != ENOENT)
3683                         ereport(pgStatRunningInCollector ? LOG : WARNING,
3684                                         (errcode_for_file_access(),
3685                                          errmsg("could not open statistics file \"%s\": %m",
3686                                                         statfile)));
3687                 return false;
3688         }
3689
3690         /*
3691          * Verify it's of the expected format.
3692          */
3693         if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id)
3694                 || format_id != PGSTAT_FILE_FORMAT_ID)
3695         {
3696                 ereport(pgStatRunningInCollector ? LOG : WARNING,
3697                                 (errmsg("corrupted statistics file \"%s\"", statfile)));
3698                 FreeFile(fpin);
3699                 return false;
3700         }
3701
3702         /*
3703          * Read global stats struct
3704          */
3705         if (fread(&myGlobalStats, 1, sizeof(myGlobalStats), fpin) != sizeof(myGlobalStats))
3706         {
3707                 ereport(pgStatRunningInCollector ? LOG : WARNING,
3708                                 (errmsg("corrupted statistics file \"%s\"", statfile)));
3709                 FreeFile(fpin);
3710                 return false;
3711         }
3712
3713         *ts = myGlobalStats.stats_timestamp;
3714
3715         FreeFile(fpin);
3716         return true;
3717 }
3718
3719 /*
3720  * If not already done, read the statistics collector stats file into
3721  * some hash tables.  The results will be kept until pgstat_clear_snapshot()
3722  * is called (typically, at end of transaction).
3723  */
3724 static void
3725 backend_read_statsfile(void)
3726 {
3727         TimestampTz min_ts;
3728         int                     count;
3729
3730         /* already read it? */
3731         if (pgStatDBHash)
3732                 return;
3733         Assert(!pgStatRunningInCollector);
3734
3735         /*
3736          * We set the minimum acceptable timestamp to PGSTAT_STAT_INTERVAL msec
3737          * before now.  This indirectly ensures that the collector needn't write
3738          * the file more often than PGSTAT_STAT_INTERVAL.  In an autovacuum
3739          * worker, however, we want a lower delay to avoid using stale data, so we
3740          * use PGSTAT_RETRY_DELAY (since the number of worker is low, this
3741          * shouldn't be a problem).
3742          *
3743          * Note that we don't recompute min_ts after sleeping; so we might end up
3744          * accepting a file a bit older than PGSTAT_STAT_INTERVAL.      In practice
3745          * that shouldn't happen, though, as long as the sleep time is less than
3746          * PGSTAT_STAT_INTERVAL; and we don't want to lie to the collector about
3747          * what our cutoff time really is.
3748          */
3749         if (IsAutoVacuumWorkerProcess())
3750                 min_ts = TimestampTzPlusMilliseconds(GetCurrentTimestamp(),
3751                                                                                          -PGSTAT_RETRY_DELAY);
3752         else
3753                 min_ts = TimestampTzPlusMilliseconds(GetCurrentTimestamp(),
3754                                                                                          -PGSTAT_STAT_INTERVAL);
3755
3756         /*
3757          * Loop until fresh enough stats file is available or we ran out of time.
3758          * The stats inquiry message is sent repeatedly in case collector drops
3759          * it.
3760          */
3761         for (count = 0; count < PGSTAT_POLL_LOOP_COUNT; count++)
3762         {
3763                 TimestampTz file_ts = 0;
3764
3765                 CHECK_FOR_INTERRUPTS();
3766
3767                 if (pgstat_read_statsfile_timestamp(false, &file_ts) &&
3768                         file_ts >= min_ts)
3769                         break;
3770
3771                 /* Not there or too old, so kick the collector and wait a bit */
3772                 pgstat_send_inquiry(min_ts);
3773                 pg_usleep(PGSTAT_RETRY_DELAY * 1000L);
3774         }
3775
3776         if (count >= PGSTAT_POLL_LOOP_COUNT)
3777                 elog(WARNING, "pgstat wait timeout");
3778
3779         /* Autovacuum launcher wants stats about all databases */
3780         if (IsAutoVacuumLauncherProcess())
3781                 pgStatDBHash = pgstat_read_statsfile(InvalidOid, false);
3782         else
3783                 pgStatDBHash = pgstat_read_statsfile(MyDatabaseId, false);
3784 }
3785
3786
3787 /* ----------
3788  * pgstat_setup_memcxt() -
3789  *
3790  *      Create pgStatLocalContext, if not already done.
3791  * ----------
3792  */
3793 static void
3794 pgstat_setup_memcxt(void)
3795 {
3796         if (!pgStatLocalContext)
3797                 pgStatLocalContext = AllocSetContextCreate(TopMemoryContext,
3798                                                                                                    "Statistics snapshot",
3799                                                                                                    ALLOCSET_SMALL_MINSIZE,
3800                                                                                                    ALLOCSET_SMALL_INITSIZE,
3801                                                                                                    ALLOCSET_SMALL_MAXSIZE);
3802 }
3803
3804
3805 /* ----------
3806  * pgstat_clear_snapshot() -
3807  *
3808  *      Discard any data collected in the current transaction.  Any subsequent
3809  *      request will cause new snapshots to be read.
3810  *
3811  *      This is also invoked during transaction commit or abort to discard
3812  *      the no-longer-wanted snapshot.
3813  * ----------
3814  */
3815 void
3816 pgstat_clear_snapshot(void)
3817 {
3818         /* Release memory, if any was allocated */
3819         if (pgStatLocalContext)
3820                 MemoryContextDelete(pgStatLocalContext);
3821
3822         /* Reset variables */
3823         pgStatLocalContext = NULL;
3824         pgStatDBHash = NULL;
3825         localBackendStatusTable = NULL;
3826         localNumBackends = 0;
3827 }
3828
3829
3830 /* ----------
3831  * pgstat_recv_inquiry() -
3832  *
3833  *      Process stat inquiry requests.
3834  * ----------
3835  */
3836 static void
3837 pgstat_recv_inquiry(PgStat_MsgInquiry *msg, int len)
3838 {
3839         if (msg->inquiry_time > last_statrequest)
3840                 last_statrequest = msg->inquiry_time;
3841 }
3842
3843
3844 /* ----------
3845  * pgstat_recv_tabstat() -
3846  *
3847  *      Count what the backend has done.
3848  * ----------
3849  */
3850 static void
3851 pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len)
3852 {
3853         PgStat_StatDBEntry *dbentry;
3854         PgStat_StatTabEntry *tabentry;
3855         int                     i;
3856         bool            found;
3857
3858         dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
3859
3860         /*
3861          * Update database-wide stats.
3862          */
3863         dbentry->n_xact_commit += (PgStat_Counter) (msg->m_xact_commit);
3864         dbentry->n_xact_rollback += (PgStat_Counter) (msg->m_xact_rollback);
3865
3866         /*
3867          * Process all table entries in the message.
3868          */
3869         for (i = 0; i < msg->m_nentries; i++)
3870         {
3871                 PgStat_TableEntry *tabmsg = &(msg->m_entry[i]);
3872
3873                 tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
3874                                                                                                         (void *) &(tabmsg->t_id),
3875                                                                                                            HASH_ENTER, &found);
3876
3877                 if (!found)
3878                 {
3879                         /*
3880                          * If it's a new table entry, initialize counters to the values we
3881                          * just got.
3882                          */
3883                         tabentry->numscans = tabmsg->t_counts.t_numscans;
3884                         tabentry->tuples_returned = tabmsg->t_counts.t_tuples_returned;
3885                         tabentry->tuples_fetched = tabmsg->t_counts.t_tuples_fetched;
3886                         tabentry->tuples_inserted = tabmsg->t_counts.t_tuples_inserted;
3887                         tabentry->tuples_updated = tabmsg->t_counts.t_tuples_updated;
3888                         tabentry->tuples_deleted = tabmsg->t_counts.t_tuples_deleted;
3889                         tabentry->tuples_hot_updated = tabmsg->t_counts.t_tuples_hot_updated;
3890                         tabentry->n_live_tuples = tabmsg->t_counts.t_delta_live_tuples;
3891                         tabentry->n_dead_tuples = tabmsg->t_counts.t_delta_dead_tuples;
3892                         tabentry->changes_since_analyze = tabmsg->t_counts.t_changed_tuples;
3893                         tabentry->blocks_fetched = tabmsg->t_counts.t_blocks_fetched;
3894                         tabentry->blocks_hit = tabmsg->t_counts.t_blocks_hit;
3895
3896                         tabentry->vacuum_timestamp = 0;
3897                         tabentry->autovac_vacuum_timestamp = 0;
3898                         tabentry->analyze_timestamp = 0;
3899                         tabentry->autovac_analyze_timestamp = 0;
3900                 }
3901                 else
3902                 {
3903                         /*
3904                          * Otherwise add the values to the existing entry.
3905                          */
3906                         tabentry->numscans += tabmsg->t_counts.t_numscans;
3907                         tabentry->tuples_returned += tabmsg->t_counts.t_tuples_returned;
3908                         tabentry->tuples_fetched += tabmsg->t_counts.t_tuples_fetched;
3909                         tabentry->tuples_inserted += tabmsg->t_counts.t_tuples_inserted;
3910                         tabentry->tuples_updated += tabmsg->t_counts.t_tuples_updated;
3911                         tabentry->tuples_deleted += tabmsg->t_counts.t_tuples_deleted;
3912                         tabentry->tuples_hot_updated += tabmsg->t_counts.t_tuples_hot_updated;
3913                         tabentry->n_live_tuples += tabmsg->t_counts.t_delta_live_tuples;
3914                         tabentry->n_dead_tuples += tabmsg->t_counts.t_delta_dead_tuples;
3915                         tabentry->changes_since_analyze += tabmsg->t_counts.t_changed_tuples;
3916                         tabentry->blocks_fetched += tabmsg->t_counts.t_blocks_fetched;
3917                         tabentry->blocks_hit += tabmsg->t_counts.t_blocks_hit;
3918                 }
3919
3920                 /* Clamp n_live_tuples in case of negative delta_live_tuples */
3921                 tabentry->n_live_tuples = Max(tabentry->n_live_tuples, 0);
3922                 /* Likewise for n_dead_tuples */
3923                 tabentry->n_dead_tuples = Max(tabentry->n_dead_tuples, 0);
3924
3925                 /*
3926                  * Add per-table stats to the per-database entry, too.
3927                  */
3928                 dbentry->n_tuples_returned += tabmsg->t_counts.t_tuples_returned;
3929                 dbentry->n_tuples_fetched += tabmsg->t_counts.t_tuples_fetched;
3930                 dbentry->n_tuples_inserted += tabmsg->t_counts.t_tuples_inserted;
3931                 dbentry->n_tuples_updated += tabmsg->t_counts.t_tuples_updated;
3932                 dbentry->n_tuples_deleted += tabmsg->t_counts.t_tuples_deleted;
3933                 dbentry->n_blocks_fetched += tabmsg->t_counts.t_blocks_fetched;
3934                 dbentry->n_blocks_hit += tabmsg->t_counts.t_blocks_hit;
3935         }
3936 }
3937
3938
3939 /* ----------
3940  * pgstat_recv_tabpurge() -
3941  *
3942  *      Arrange for dead table removal.
3943  * ----------
3944  */
3945 static void
3946 pgstat_recv_tabpurge(PgStat_MsgTabpurge *msg, int len)
3947 {
3948         PgStat_StatDBEntry *dbentry;
3949         int                     i;
3950
3951         dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
3952
3953         /*
3954          * No need to purge if we don't even know the database.
3955          */
3956         if (!dbentry || !dbentry->tables)
3957                 return;
3958
3959         /*
3960          * Process all table entries in the message.
3961          */
3962         for (i = 0; i < msg->m_nentries; i++)
3963         {
3964                 /* Remove from hashtable if present; we don't care if it's not. */
3965                 (void) hash_search(dbentry->tables,
3966                                                    (void *) &(msg->m_tableid[i]),
3967                                                    HASH_REMOVE, NULL);
3968         }
3969 }
3970
3971
3972 /* ----------
3973  * pgstat_recv_dropdb() -
3974  *
3975  *      Arrange for dead database removal
3976  * ----------
3977  */
3978 static void
3979 pgstat_recv_dropdb(PgStat_MsgDropdb *msg, int len)
3980 {
3981         PgStat_StatDBEntry *dbentry;
3982
3983         /*
3984          * Lookup the database in the hashtable.
3985          */
3986         dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
3987
3988         /*
3989          * If found, remove it.
3990          */
3991         if (dbentry)
3992         {
3993                 if (dbentry->tables != NULL)
3994                         hash_destroy(dbentry->tables);
3995                 if (dbentry->functions != NULL)
3996                         hash_destroy(dbentry->functions);
3997
3998                 if (hash_search(pgStatDBHash,
3999                                                 (void *) &(dbentry->databaseid),
4000                                                 HASH_REMOVE, NULL) == NULL)
4001                         ereport(ERROR,
4002                                         (errmsg("database hash table corrupted "
4003                                                         "during cleanup --- abort")));
4004         }
4005 }
4006
4007
4008 /* ----------
4009  * pgstat_recv_resetcounter() -
4010  *
4011  *      Reset the statistics for the specified database.
4012  * ----------
4013  */
4014 static void
4015 pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len)
4016 {
4017         HASHCTL         hash_ctl;
4018         PgStat_StatDBEntry *dbentry;
4019
4020         /*
4021          * Lookup the database in the hashtable.  Nothing to do if not there.
4022          */
4023         dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
4024
4025         if (!dbentry)
4026                 return;
4027
4028         /*
4029          * We simply throw away all the database's table entries by recreating a
4030          * new hash table for them.
4031          */
4032         if (dbentry->tables != NULL)
4033                 hash_destroy(dbentry->tables);
4034         if (dbentry->functions != NULL)
4035                 hash_destroy(dbentry->functions);
4036
4037         dbentry->tables = NULL;
4038         dbentry->functions = NULL;
4039
4040         /*
4041          * Reset database-level stats too.  This should match the initialization
4042          * code in pgstat_get_db_entry().
4043          */
4044         dbentry->n_xact_commit = 0;
4045         dbentry->n_xact_rollback = 0;
4046         dbentry->n_blocks_fetched = 0;
4047         dbentry->n_blocks_hit = 0;
4048         dbentry->n_tuples_returned = 0;
4049         dbentry->n_tuples_fetched = 0;
4050         dbentry->n_tuples_inserted = 0;
4051         dbentry->n_tuples_updated = 0;
4052         dbentry->n_tuples_deleted = 0;
4053         dbentry->last_autovac_time = 0;
4054
4055         memset(&hash_ctl, 0, sizeof(hash_ctl));
4056         hash_ctl.keysize = sizeof(Oid);
4057         hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
4058         hash_ctl.hash = oid_hash;
4059         dbentry->tables = hash_create("Per-database table",
4060                                                                   PGSTAT_TAB_HASH_SIZE,
4061                                                                   &hash_ctl,
4062                                                                   HASH_ELEM | HASH_FUNCTION);
4063
4064         hash_ctl.keysize = sizeof(Oid);
4065         hash_ctl.entrysize = sizeof(PgStat_StatFuncEntry);
4066         hash_ctl.hash = oid_hash;
4067         dbentry->functions = hash_create("Per-database function",
4068                                                                          PGSTAT_FUNCTION_HASH_SIZE,
4069                                                                          &hash_ctl,
4070                                                                          HASH_ELEM | HASH_FUNCTION);
4071 }
4072
4073 /* ----------
4074  * pgstat_recv_resetshared() -
4075  *
4076  *      Reset some shared statistics of the cluster.
4077  * ----------
4078  */
4079 static void
4080 pgstat_recv_resetsharedcounter(PgStat_MsgResetsharedcounter *msg, int len)
4081 {
4082         if (msg->m_resettarget == RESET_BGWRITER)
4083         {
4084                 /* Reset the global background writer statistics for the cluster. */
4085                 memset(&globalStats, 0, sizeof(globalStats));
4086         }
4087
4088         /*
4089          * Presumably the sender of this message validated the target, don't
4090          * complain here if it's not valid
4091          */
4092 }
4093
4094 /* ----------
4095  * pgstat_recv_resetsinglecounter() -
4096  *
4097  *      Reset a statistics for a single object
4098  * ----------
4099  */
4100 static void
4101 pgstat_recv_resetsinglecounter(PgStat_MsgResetsinglecounter *msg, int len)
4102 {
4103         PgStat_StatDBEntry *dbentry;
4104
4105         dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
4106
4107         if (!dbentry)
4108                 return;
4109
4110
4111         /* Remove object if it exists, ignore it if not */
4112         if (msg->m_resettype == RESET_TABLE)
4113                 (void) hash_search(dbentry->tables, (void *) &(msg->m_objectid), HASH_REMOVE, NULL);
4114         else if (msg->m_resettype == RESET_FUNCTION)
4115                 (void) hash_search(dbentry->functions, (void *) &(msg->m_objectid), HASH_REMOVE, NULL);
4116 }
4117
4118 /* ----------
4119  * pgstat_recv_autovac() -
4120  *
4121  *      Process an autovacuum signalling message.
4122  * ----------
4123  */
4124 static void
4125 pgstat_recv_autovac(PgStat_MsgAutovacStart *msg, int len)
4126 {
4127         PgStat_StatDBEntry *dbentry;
4128
4129         /*
4130          * Store the last autovacuum time in the database's hashtable entry.
4131          */
4132         dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
4133
4134         dbentry->last_autovac_time = msg->m_start_time;
4135 }
4136
4137 /* ----------
4138  * pgstat_recv_vacuum() -
4139  *
4140  *      Process a VACUUM message.
4141  * ----------
4142  */
4143 static void
4144 pgstat_recv_vacuum(PgStat_MsgVacuum *msg, int len)
4145 {
4146         PgStat_StatDBEntry *dbentry;
4147         PgStat_StatTabEntry *tabentry;
4148
4149         /*
4150          * Store the data in the table's hashtable entry.
4151          */
4152         dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
4153
4154         tabentry = pgstat_get_tab_entry(dbentry, msg->m_tableoid, true);
4155
4156         if (msg->m_adopt_counts)
4157                 tabentry->n_live_tuples = msg->m_tuples;
4158         /* Resetting dead_tuples to 0 is an approximation ... */
4159         tabentry->n_dead_tuples = 0;
4160
4161         if (msg->m_autovacuum)
4162         {
4163                 tabentry->autovac_vacuum_timestamp = msg->m_vacuumtime;
4164                 tabentry->autovac_vacuum_count++;
4165         }
4166         else
4167         {
4168                 tabentry->vacuum_timestamp = msg->m_vacuumtime;
4169                 tabentry->vacuum_count++;
4170         }
4171 }
4172
4173 /* ----------
4174  * pgstat_recv_analyze() -
4175  *
4176  *      Process an ANALYZE message.
4177  * ----------
4178  */
4179 static void
4180 pgstat_recv_analyze(PgStat_MsgAnalyze *msg, int len)
4181 {
4182         PgStat_StatDBEntry *dbentry;
4183         PgStat_StatTabEntry *tabentry;
4184
4185         /*
4186          * Store the data in the table's hashtable entry.
4187          */
4188         dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
4189
4190         tabentry = pgstat_get_tab_entry(dbentry, msg->m_tableoid, true);
4191
4192         if (msg->m_adopt_counts)
4193         {
4194                 tabentry->n_live_tuples = msg->m_live_tuples;
4195                 tabentry->n_dead_tuples = msg->m_dead_tuples;
4196         }
4197
4198         /*
4199          * We reset changes_since_analyze to zero, forgetting any changes that
4200          * occurred while the ANALYZE was in progress.
4201          */
4202         tabentry->changes_since_analyze = 0;
4203
4204         if (msg->m_autovacuum)
4205         {
4206                 tabentry->autovac_analyze_timestamp = msg->m_analyzetime;
4207                 tabentry->autovac_analyze_count++;
4208         }
4209         else
4210         {
4211                 tabentry->analyze_timestamp = msg->m_analyzetime;
4212                 tabentry->analyze_count++;
4213         }
4214 }
4215
4216
4217 /* ----------
4218  * pgstat_recv_bgwriter() -
4219  *
4220  *      Process a BGWRITER message.
4221  * ----------
4222  */
4223 static void
4224 pgstat_recv_bgwriter(PgStat_MsgBgWriter *msg, int len)
4225 {
4226         globalStats.timed_checkpoints += msg->m_timed_checkpoints;
4227         globalStats.requested_checkpoints += msg->m_requested_checkpoints;
4228         globalStats.buf_written_checkpoints += msg->m_buf_written_checkpoints;
4229         globalStats.buf_written_clean += msg->m_buf_written_clean;
4230         globalStats.maxwritten_clean += msg->m_maxwritten_clean;
4231         globalStats.buf_written_backend += msg->m_buf_written_backend;
4232         globalStats.buf_fsync_backend += msg->m_buf_fsync_backend;
4233         globalStats.buf_alloc += msg->m_buf_alloc;
4234 }
4235
4236 /* ----------
4237  * pgstat_recv_recoveryconflict() -
4238  *
4239  *  Process as RECOVERYCONFLICT message.
4240  * ----------
4241  */
4242 static void
4243 pgstat_recv_recoveryconflict(PgStat_MsgRecoveryConflict *msg, int len)
4244 {
4245         PgStat_StatDBEntry *dbentry;
4246         dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
4247
4248         switch (msg->m_reason)
4249         {
4250                 case PROCSIG_RECOVERY_CONFLICT_DATABASE:
4251                         /*
4252                          * Since we drop the information about the database as soon
4253                          * as it replicates, there is no point in counting these
4254                          * conflicts.
4255                          */
4256                         break;
4257                 case PROCSIG_RECOVERY_CONFLICT_TABLESPACE:
4258                         dbentry->n_conflict_tablespace++;
4259                         break;
4260                 case PROCSIG_RECOVERY_CONFLICT_LOCK:
4261                         dbentry->n_conflict_lock++;
4262                         break;
4263                 case PROCSIG_RECOVERY_CONFLICT_SNAPSHOT:
4264                         dbentry->n_conflict_snapshot++;
4265                         break;
4266                 case PROCSIG_RECOVERY_CONFLICT_BUFFERPIN:
4267                         dbentry->n_conflict_bufferpin++;
4268                         break;
4269                 case PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK:
4270                         dbentry->n_conflict_startup_deadlock++;
4271                         break;
4272         }
4273 }
4274
4275 /* ----------
4276  * pgstat_recv_funcstat() -
4277  *
4278  *      Count what the backend has done.
4279  * ----------
4280  */
4281 static void
4282 pgstat_recv_funcstat(PgStat_MsgFuncstat *msg, int len)
4283 {
4284         PgStat_FunctionEntry *funcmsg = &(msg->m_entry[0]);
4285         PgStat_StatDBEntry *dbentry;
4286         PgStat_StatFuncEntry *funcentry;
4287         int                     i;
4288         bool            found;
4289
4290         dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
4291
4292         /*
4293          * Process all function entries in the message.
4294          */
4295         for (i = 0; i < msg->m_nentries; i++, funcmsg++)
4296         {
4297                 funcentry = (PgStat_StatFuncEntry *) hash_search(dbentry->functions,
4298                                                                                                    (void *) &(funcmsg->f_id),
4299                                                                                                                  HASH_ENTER, &found);
4300
4301                 if (!found)
4302                 {
4303                         /*
4304                          * If it's a new function entry, initialize counters to the values
4305                          * we just got.
4306                          */
4307                         funcentry->f_numcalls = funcmsg->f_numcalls;
4308                         funcentry->f_time = funcmsg->f_time;
4309                         funcentry->f_time_self = funcmsg->f_time_self;
4310                 }
4311                 else
4312                 {
4313                         /*
4314                          * Otherwise add the values to the existing entry.
4315                          */
4316                         funcentry->f_numcalls += funcmsg->f_numcalls;
4317                         funcentry->f_time += funcmsg->f_time;
4318                         funcentry->f_time_self += funcmsg->f_time_self;
4319                 }
4320         }
4321 }
4322
4323 /* ----------
4324  * pgstat_recv_funcpurge() -
4325  *
4326  *      Arrange for dead function removal.
4327  * ----------
4328  */
4329 static void
4330 pgstat_recv_funcpurge(PgStat_MsgFuncpurge *msg, int len)
4331 {
4332         PgStat_StatDBEntry *dbentry;
4333         int                     i;
4334
4335         dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
4336
4337         /*
4338          * No need to purge if we don't even know the database.
4339          */
4340         if (!dbentry || !dbentry->functions)
4341                 return;
4342
4343         /*
4344          * Process all function entries in the message.
4345          */
4346         for (i = 0; i < msg->m_nentries; i++)
4347         {
4348                 /* Remove from hashtable if present; we don't care if it's not. */
4349                 (void) hash_search(dbentry->functions,
4350                                                    (void *) &(msg->m_functionid[i]),
4351                                                    HASH_REMOVE, NULL);
4352         }
4353 }