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