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