Line data Source code
1 : /*-------------------------------------------------------------------------
2 : *
3 : * autovacuum.c
4 : *
5 : * PostgreSQL Integrated Autovacuum Daemon
6 : *
7 : * The autovacuum system is structured in two different kinds of processes: the
8 : * autovacuum launcher and the autovacuum worker. The launcher is an
9 : * always-running process, started by the postmaster when the autovacuum GUC
10 : * parameter is set. The launcher schedules autovacuum workers to be started
11 : * when appropriate. The workers are the processes which execute the actual
12 : * vacuuming; they connect to a database as determined in the launcher, and
13 : * once connected they examine the catalogs to select the tables to vacuum.
14 : *
15 : * The autovacuum launcher cannot start the worker processes by itself,
16 : * because doing so would cause robustness issues (namely, failure to shut
17 : * them down on exceptional conditions, and also, since the launcher is
18 : * connected to shared memory and is thus subject to corruption there, it is
19 : * not as robust as the postmaster). So it leaves that task to the postmaster.
20 : *
21 : * There is an autovacuum shared memory area, where the launcher stores
22 : * information about the database it wants vacuumed. When it wants a new
23 : * worker to start, it sets a flag in shared memory and sends a signal to the
24 : * postmaster. Then postmaster knows nothing more than it must start a worker;
25 : * so it forks a new child, which turns into a worker. This new process
26 : * connects to shared memory, and there it can inspect the information that the
27 : * launcher has set up.
28 : *
29 : * If the fork() call fails in the postmaster, it sets a flag in the shared
30 : * memory area, and sends a signal to the launcher. The launcher, upon
31 : * noticing the flag, can try starting the worker again by resending the
32 : * signal. Note that the failure can only be transient (fork failure due to
33 : * high load, memory pressure, too many processes, etc); more permanent
34 : * problems, like failure to connect to a database, are detected later in the
35 : * worker and dealt with just by having the worker exit normally. The launcher
36 : * will launch a new worker again later, per schedule.
37 : *
38 : * When the worker is done vacuuming it sends SIGUSR2 to the launcher. The
39 : * launcher then wakes up and is able to launch another worker, if the schedule
40 : * is so tight that a new worker is needed immediately. At this time the
41 : * launcher can also balance the settings for the various remaining workers'
42 : * cost-based vacuum delay feature.
43 : *
44 : * Note that there can be more than one worker in a database concurrently.
45 : * They will store the table they are currently vacuuming in shared memory, so
46 : * that other workers avoid being blocked waiting for the vacuum lock for that
47 : * table. They will also fetch the last time the table was vacuumed from
48 : * pgstats just before vacuuming each table, to avoid vacuuming a table that
49 : * was just finished being vacuumed by another worker and thus is no longer
50 : * noted in shared memory. However, there is a small window (due to not yet
51 : * holding the relation lock) during which a worker may choose a table that was
52 : * already vacuumed; this is a bug in the current design.
53 : *
54 : * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
55 : * Portions Copyright (c) 1994, Regents of the University of California
56 : *
57 : *
58 : * IDENTIFICATION
59 : * src/backend/postmaster/autovacuum.c
60 : *
61 : *-------------------------------------------------------------------------
62 : */
63 : #include "postgres.h"
64 :
65 : #include <signal.h>
66 : #include <sys/time.h>
67 : #include <unistd.h>
68 :
69 : #include "access/heapam.h"
70 : #include "access/htup_details.h"
71 : #include "access/multixact.h"
72 : #include "access/reloptions.h"
73 : #include "access/tableam.h"
74 : #include "access/transam.h"
75 : #include "access/xact.h"
76 : #include "catalog/dependency.h"
77 : #include "catalog/namespace.h"
78 : #include "catalog/pg_database.h"
79 : #include "commands/dbcommands.h"
80 : #include "commands/vacuum.h"
81 : #include "lib/ilist.h"
82 : #include "libpq/pqsignal.h"
83 : #include "miscadmin.h"
84 : #include "nodes/makefuncs.h"
85 : #include "pgstat.h"
86 : #include "postmaster/autovacuum.h"
87 : #include "postmaster/fork_process.h"
88 : #include "postmaster/interrupt.h"
89 : #include "postmaster/postmaster.h"
90 : #include "storage/bufmgr.h"
91 : #include "storage/ipc.h"
92 : #include "storage/latch.h"
93 : #include "storage/lmgr.h"
94 : #include "storage/pmsignal.h"
95 : #include "storage/proc.h"
96 : #include "storage/procsignal.h"
97 : #include "storage/sinvaladt.h"
98 : #include "storage/smgr.h"
99 : #include "tcop/tcopprot.h"
100 : #include "utils/fmgroids.h"
101 : #include "utils/fmgrprotos.h"
102 : #include "utils/guc_hooks.h"
103 : #include "utils/lsyscache.h"
104 : #include "utils/memutils.h"
105 : #include "utils/ps_status.h"
106 : #include "utils/rel.h"
107 : #include "utils/snapmgr.h"
108 : #include "utils/syscache.h"
109 : #include "utils/timeout.h"
110 : #include "utils/timestamp.h"
111 :
112 :
113 : /*
114 : * GUC parameters
115 : */
116 : bool autovacuum_start_daemon = false;
117 : int autovacuum_max_workers;
118 : int autovacuum_work_mem = -1;
119 : int autovacuum_naptime;
120 : int autovacuum_vac_thresh;
121 : double autovacuum_vac_scale;
122 : int autovacuum_vac_ins_thresh;
123 : double autovacuum_vac_ins_scale;
124 : int autovacuum_anl_thresh;
125 : double autovacuum_anl_scale;
126 : int autovacuum_freeze_max_age;
127 : int autovacuum_multixact_freeze_max_age;
128 :
129 : double autovacuum_vac_cost_delay;
130 : int autovacuum_vac_cost_limit;
131 :
132 : int Log_autovacuum_min_duration = 600000;
133 :
134 : /* the minimum allowed time between two awakenings of the launcher */
135 : #define MIN_AUTOVAC_SLEEPTIME 100.0 /* milliseconds */
136 : #define MAX_AUTOVAC_SLEEPTIME 300 /* seconds */
137 :
138 : /* Flags to tell if we are in an autovacuum process */
139 : static bool am_autovacuum_launcher = false;
140 : static bool am_autovacuum_worker = false;
141 :
142 : /*
143 : * Variables to save the cost-related storage parameters for the current
144 : * relation being vacuumed by this autovacuum worker. Using these, we can
145 : * ensure we don't overwrite the values of vacuum_cost_delay and
146 : * vacuum_cost_limit after reloading the configuration file. They are
147 : * initialized to "invalid" values to indicate that no cost-related storage
148 : * parameters were specified and will be set in do_autovacuum() after checking
149 : * the storage parameters in table_recheck_autovac().
150 : */
151 : static double av_storage_param_cost_delay = -1;
152 : static int av_storage_param_cost_limit = -1;
153 :
154 : /* Flags set by signal handlers */
155 : static volatile sig_atomic_t got_SIGUSR2 = false;
156 :
157 : /* Comparison points for determining whether freeze_max_age is exceeded */
158 : static TransactionId recentXid;
159 : static MultiXactId recentMulti;
160 :
161 : /* Default freeze ages to use for autovacuum (varies by database) */
162 : static int default_freeze_min_age;
163 : static int default_freeze_table_age;
164 : static int default_multixact_freeze_min_age;
165 : static int default_multixact_freeze_table_age;
166 :
167 : /* Memory context for long-lived data */
168 : static MemoryContext AutovacMemCxt;
169 :
170 : /* struct to keep track of databases in launcher */
171 : typedef struct avl_dbase
172 : {
173 : Oid adl_datid; /* hash key -- must be first */
174 : TimestampTz adl_next_worker;
175 : int adl_score;
176 : dlist_node adl_node;
177 : } avl_dbase;
178 :
179 : /* struct to keep track of databases in worker */
180 : typedef struct avw_dbase
181 : {
182 : Oid adw_datid;
183 : char *adw_name;
184 : TransactionId adw_frozenxid;
185 : MultiXactId adw_minmulti;
186 : PgStat_StatDBEntry *adw_entry;
187 : } avw_dbase;
188 :
189 : /* struct to keep track of tables to vacuum and/or analyze, in 1st pass */
190 : typedef struct av_relation
191 : {
192 : Oid ar_toastrelid; /* hash key - must be first */
193 : Oid ar_relid;
194 : bool ar_hasrelopts;
195 : AutoVacOpts ar_reloptions; /* copy of AutoVacOpts from the main table's
196 : * reloptions, or NULL if none */
197 : } av_relation;
198 :
199 : /* struct to keep track of tables to vacuum and/or analyze, after rechecking */
200 : typedef struct autovac_table
201 : {
202 : Oid at_relid;
203 : VacuumParams at_params;
204 : double at_storage_param_vac_cost_delay;
205 : int at_storage_param_vac_cost_limit;
206 : bool at_dobalance;
207 : bool at_sharedrel;
208 : char *at_relname;
209 : char *at_nspname;
210 : char *at_datname;
211 : } autovac_table;
212 :
213 : /*-------------
214 : * This struct holds information about a single worker's whereabouts. We keep
215 : * an array of these in shared memory, sized according to
216 : * autovacuum_max_workers.
217 : *
218 : * wi_links entry into free list or running list
219 : * wi_dboid OID of the database this worker is supposed to work on
220 : * wi_tableoid OID of the table currently being vacuumed, if any
221 : * wi_sharedrel flag indicating whether table is marked relisshared
222 : * wi_proc pointer to PGPROC of the running worker, NULL if not started
223 : * wi_launchtime Time at which this worker was launched
224 : * wi_dobalance Whether this worker should be included in balance calculations
225 : *
226 : * All fields are protected by AutovacuumLock, except for wi_tableoid and
227 : * wi_sharedrel which are protected by AutovacuumScheduleLock (note these
228 : * two fields are read-only for everyone except that worker itself).
229 : *-------------
230 : */
231 : typedef struct WorkerInfoData
232 : {
233 : dlist_node wi_links;
234 : Oid wi_dboid;
235 : Oid wi_tableoid;
236 : PGPROC *wi_proc;
237 : TimestampTz wi_launchtime;
238 : pg_atomic_flag wi_dobalance;
239 : bool wi_sharedrel;
240 : } WorkerInfoData;
241 :
242 : typedef struct WorkerInfoData *WorkerInfo;
243 :
244 : /*
245 : * Possible signals received by the launcher from remote processes. These are
246 : * stored atomically in shared memory so that other processes can set them
247 : * without locking.
248 : */
249 : typedef enum
250 : {
251 : AutoVacForkFailed, /* failed trying to start a worker */
252 : AutoVacRebalance, /* rebalance the cost limits */
253 : AutoVacNumSignals, /* must be last */
254 : } AutoVacuumSignal;
255 :
256 : /*
257 : * Autovacuum workitem array, stored in AutoVacuumShmem->av_workItems. This
258 : * list is mostly protected by AutovacuumLock, except that if an item is
259 : * marked 'active' other processes must not modify the work-identifying
260 : * members.
261 : */
262 : typedef struct AutoVacuumWorkItem
263 : {
264 : AutoVacuumWorkItemType avw_type;
265 : bool avw_used; /* below data is valid */
266 : bool avw_active; /* being processed */
267 : Oid avw_database;
268 : Oid avw_relation;
269 : BlockNumber avw_blockNumber;
270 : } AutoVacuumWorkItem;
271 :
272 : #define NUM_WORKITEMS 256
273 :
274 : /*-------------
275 : * The main autovacuum shmem struct. On shared memory we store this main
276 : * struct and the array of WorkerInfo structs. This struct keeps:
277 : *
278 : * av_signal set by other processes to indicate various conditions
279 : * av_launcherpid the PID of the autovacuum launcher
280 : * av_freeWorkers the WorkerInfo freelist
281 : * av_runningWorkers the WorkerInfo non-free queue
282 : * av_startingWorker pointer to WorkerInfo currently being started (cleared by
283 : * the worker itself as soon as it's up and running)
284 : * av_workItems work item array
285 : * av_nworkersForBalance the number of autovacuum workers to use when
286 : * calculating the per worker cost limit
287 : *
288 : * This struct is protected by AutovacuumLock, except for av_signal and parts
289 : * of the worker list (see above).
290 : *-------------
291 : */
292 : typedef struct
293 : {
294 : sig_atomic_t av_signal[AutoVacNumSignals];
295 : pid_t av_launcherpid;
296 : dlist_head av_freeWorkers;
297 : dlist_head av_runningWorkers;
298 : WorkerInfo av_startingWorker;
299 : AutoVacuumWorkItem av_workItems[NUM_WORKITEMS];
300 : pg_atomic_uint32 av_nworkersForBalance;
301 : } AutoVacuumShmemStruct;
302 :
303 : static AutoVacuumShmemStruct *AutoVacuumShmem;
304 :
305 : /*
306 : * the database list (of avl_dbase elements) in the launcher, and the context
307 : * that contains it
308 : */
309 : static dlist_head DatabaseList = DLIST_STATIC_INIT(DatabaseList);
310 : static MemoryContext DatabaseListCxt = NULL;
311 :
312 : /* Pointer to my own WorkerInfo, valid on each worker */
313 : static WorkerInfo MyWorkerInfo = NULL;
314 :
315 : /* PID of launcher, valid only in worker while shutting down */
316 : int AutovacuumLauncherPid = 0;
317 :
318 : #ifdef EXEC_BACKEND
319 : static pid_t avlauncher_forkexec(void);
320 : static pid_t avworker_forkexec(void);
321 : #endif
322 : NON_EXEC_STATIC void AutoVacWorkerMain(int argc, char *argv[]) pg_attribute_noreturn();
323 : NON_EXEC_STATIC void AutoVacLauncherMain(int argc, char *argv[]) pg_attribute_noreturn();
324 :
325 : static Oid do_start_worker(void);
326 : static void HandleAutoVacLauncherInterrupts(void);
327 : static void AutoVacLauncherShutdown(void) pg_attribute_noreturn();
328 : static void launcher_determine_sleep(bool canlaunch, bool recursing,
329 : struct timeval *nap);
330 : static void launch_worker(TimestampTz now);
331 : static List *get_database_list(void);
332 : static void rebuild_database_list(Oid newdb);
333 : static int db_comparator(const void *a, const void *b);
334 : static void autovac_recalculate_workers_for_balance(void);
335 :
336 : static void do_autovacuum(void);
337 : static void FreeWorkerInfo(int code, Datum arg);
338 :
339 : static autovac_table *table_recheck_autovac(Oid relid, HTAB *table_toast_map,
340 : TupleDesc pg_class_desc,
341 : int effective_multixact_freeze_max_age);
342 : static void recheck_relation_needs_vacanalyze(Oid relid, AutoVacOpts *avopts,
343 : Form_pg_class classForm,
344 : int effective_multixact_freeze_max_age,
345 : bool *dovacuum, bool *doanalyze, bool *wraparound);
346 : static void relation_needs_vacanalyze(Oid relid, AutoVacOpts *relopts,
347 : Form_pg_class classForm,
348 : PgStat_StatTabEntry *tabentry,
349 : int effective_multixact_freeze_max_age,
350 : bool *dovacuum, bool *doanalyze, bool *wraparound);
351 :
352 : static void autovacuum_do_vac_analyze(autovac_table *tab,
353 : BufferAccessStrategy bstrategy);
354 : static AutoVacOpts *extract_autovac_opts(HeapTuple tup,
355 : TupleDesc pg_class_desc);
356 : static void perform_work_item(AutoVacuumWorkItem *workitem);
357 : static void autovac_report_activity(autovac_table *tab);
358 : static void autovac_report_workitem(AutoVacuumWorkItem *workitem,
359 : const char *nspname, const char *relname);
360 : static void avl_sigusr2_handler(SIGNAL_ARGS);
361 :
362 :
363 :
364 : /********************************************************************
365 : * AUTOVACUUM LAUNCHER CODE
366 : ********************************************************************/
367 :
368 : #ifdef EXEC_BACKEND
369 : /*
370 : * forkexec routine for the autovacuum launcher process.
371 : *
372 : * Format up the arglist, then fork and exec.
373 : */
374 : static pid_t
375 : avlauncher_forkexec(void)
376 : {
377 : char *av[10];
378 : int ac = 0;
379 :
380 : av[ac++] = "postgres";
381 : av[ac++] = "--forkavlauncher";
382 : av[ac++] = NULL; /* filled in by postmaster_forkexec */
383 : av[ac] = NULL;
384 :
385 : Assert(ac < lengthof(av));
386 :
387 : return postmaster_forkexec(ac, av);
388 : }
389 : #endif
390 :
391 : /*
392 : * Main entry point for autovacuum launcher process, to be called from the
393 : * postmaster.
394 : */
395 : int
396 1004 : StartAutoVacLauncher(void)
397 : {
398 : pid_t AutoVacPID;
399 :
400 : #ifdef EXEC_BACKEND
401 : switch ((AutoVacPID = avlauncher_forkexec()))
402 : #else
403 1004 : switch ((AutoVacPID = fork_process()))
404 : #endif
405 : {
406 0 : case -1:
407 0 : ereport(LOG,
408 : (errmsg("could not fork autovacuum launcher process: %m")));
409 0 : return 0;
410 :
411 : #ifndef EXEC_BACKEND
412 614 : case 0:
413 : /* in postmaster child ... */
414 614 : InitPostmasterChild();
415 :
416 : /* Close the postmaster's sockets */
417 614 : ClosePostmasterPorts(false);
418 :
419 614 : AutoVacLauncherMain(0, NULL);
420 : break;
421 : #endif
422 1004 : default:
423 1004 : return (int) AutoVacPID;
424 : }
425 :
426 : /* shouldn't get here */
427 : return 0;
428 : }
429 :
430 : /*
431 : * Main loop for the autovacuum launcher process.
432 : */
433 : NON_EXEC_STATIC void
434 614 : AutoVacLauncherMain(int argc, char *argv[])
435 : {
436 : sigjmp_buf local_sigjmp_buf;
437 :
438 614 : am_autovacuum_launcher = true;
439 :
440 614 : MyBackendType = B_AUTOVAC_LAUNCHER;
441 614 : init_ps_display(NULL);
442 :
443 614 : ereport(DEBUG1,
444 : (errmsg_internal("autovacuum launcher started")));
445 :
446 614 : if (PostAuthDelay)
447 0 : pg_usleep(PostAuthDelay * 1000000L);
448 :
449 614 : SetProcessingMode(InitProcessing);
450 :
451 : /*
452 : * Set up signal handlers. We operate on databases much like a regular
453 : * backend, so we use the same signal handling. See equivalent code in
454 : * tcop/postgres.c.
455 : */
456 614 : pqsignal(SIGHUP, SignalHandlerForConfigReload);
457 614 : pqsignal(SIGINT, StatementCancelHandler);
458 614 : pqsignal(SIGTERM, SignalHandlerForShutdownRequest);
459 : /* SIGQUIT handler was already set up by InitPostmasterChild */
460 :
461 614 : InitializeTimeouts(); /* establishes SIGALRM handler */
462 :
463 614 : pqsignal(SIGPIPE, SIG_IGN);
464 614 : pqsignal(SIGUSR1, procsignal_sigusr1_handler);
465 614 : pqsignal(SIGUSR2, avl_sigusr2_handler);
466 614 : pqsignal(SIGFPE, FloatExceptionHandler);
467 614 : pqsignal(SIGCHLD, SIG_DFL);
468 :
469 : /*
470 : * Create a per-backend PGPROC struct in shared memory. We must do this
471 : * before we can use LWLocks or access any shared memory.
472 : */
473 614 : InitProcess();
474 :
475 : /* Early initialization */
476 614 : BaseInit();
477 :
478 614 : InitPostgres(NULL, InvalidOid, NULL, InvalidOid, 0, NULL);
479 :
480 614 : SetProcessingMode(NormalProcessing);
481 :
482 : /*
483 : * Create a memory context that we will do all our work in. We do this so
484 : * that we can reset the context during error recovery and thereby avoid
485 : * possible memory leaks.
486 : */
487 614 : AutovacMemCxt = AllocSetContextCreate(TopMemoryContext,
488 : "Autovacuum Launcher",
489 : ALLOCSET_DEFAULT_SIZES);
490 614 : MemoryContextSwitchTo(AutovacMemCxt);
491 :
492 : /*
493 : * If an exception is encountered, processing resumes here.
494 : *
495 : * This code is a stripped down version of PostgresMain error recovery.
496 : *
497 : * Note that we use sigsetjmp(..., 1), so that the prevailing signal mask
498 : * (to wit, BlockSig) will be restored when longjmp'ing to here. Thus,
499 : * signals other than SIGQUIT will be blocked until we complete error
500 : * recovery. It might seem that this policy makes the HOLD_INTERRUPTS()
501 : * call redundant, but it is not since InterruptPending might be set
502 : * already.
503 : */
504 614 : if (sigsetjmp(local_sigjmp_buf, 1) != 0)
505 : {
506 : /* since not using PG_TRY, must reset error stack by hand */
507 0 : error_context_stack = NULL;
508 :
509 : /* Prevents interrupts while cleaning up */
510 0 : HOLD_INTERRUPTS();
511 :
512 : /* Forget any pending QueryCancel or timeout request */
513 0 : disable_all_timeouts(false);
514 0 : QueryCancelPending = false; /* second to avoid race condition */
515 :
516 : /* Report the error to the server log */
517 0 : EmitErrorReport();
518 :
519 : /* Abort the current transaction in order to recover */
520 0 : AbortCurrentTransaction();
521 :
522 : /*
523 : * Release any other resources, for the case where we were not in a
524 : * transaction.
525 : */
526 0 : LWLockReleaseAll();
527 0 : pgstat_report_wait_end();
528 0 : UnlockBuffers();
529 : /* this is probably dead code, but let's be safe: */
530 0 : if (AuxProcessResourceOwner)
531 0 : ReleaseAuxProcessResources(false);
532 0 : AtEOXact_Buffers(false);
533 0 : AtEOXact_SMgr();
534 0 : AtEOXact_Files(false);
535 0 : AtEOXact_HashTables(false);
536 :
537 : /*
538 : * Now return to normal top-level context and clear ErrorContext for
539 : * next time.
540 : */
541 0 : MemoryContextSwitchTo(AutovacMemCxt);
542 0 : FlushErrorState();
543 :
544 : /* Flush any leaked data in the top-level context */
545 0 : MemoryContextReset(AutovacMemCxt);
546 :
547 : /* don't leave dangling pointers to freed memory */
548 0 : DatabaseListCxt = NULL;
549 0 : dlist_init(&DatabaseList);
550 :
551 : /* Now we can allow interrupts again */
552 0 : RESUME_INTERRUPTS();
553 :
554 : /* if in shutdown mode, no need for anything further; just go away */
555 0 : if (ShutdownRequestPending)
556 0 : AutoVacLauncherShutdown();
557 :
558 : /*
559 : * Sleep at least 1 second after any error. We don't want to be
560 : * filling the error logs as fast as we can.
561 : */
562 0 : pg_usleep(1000000L);
563 : }
564 :
565 : /* We can now handle ereport(ERROR) */
566 614 : PG_exception_stack = &local_sigjmp_buf;
567 :
568 : /* must unblock signals before calling rebuild_database_list */
569 614 : sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
570 :
571 : /*
572 : * Set always-secure search path. Launcher doesn't connect to a database,
573 : * so this has no effect.
574 : */
575 614 : SetConfigOption("search_path", "", PGC_SUSET, PGC_S_OVERRIDE);
576 :
577 : /*
578 : * Force zero_damaged_pages OFF in the autovac process, even if it is set
579 : * in postgresql.conf. We don't really want such a dangerous option being
580 : * applied non-interactively.
581 : */
582 614 : SetConfigOption("zero_damaged_pages", "false", PGC_SUSET, PGC_S_OVERRIDE);
583 :
584 : /*
585 : * Force settable timeouts off to avoid letting these settings prevent
586 : * regular maintenance from being executed.
587 : */
588 614 : SetConfigOption("statement_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
589 614 : SetConfigOption("lock_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
590 614 : SetConfigOption("idle_in_transaction_session_timeout", "0",
591 : PGC_SUSET, PGC_S_OVERRIDE);
592 :
593 : /*
594 : * Force default_transaction_isolation to READ COMMITTED. We don't want
595 : * to pay the overhead of serializable mode, nor add any risk of causing
596 : * deadlocks or delaying other transactions.
597 : */
598 614 : SetConfigOption("default_transaction_isolation", "read committed",
599 : PGC_SUSET, PGC_S_OVERRIDE);
600 :
601 : /*
602 : * Even when system is configured to use a different fetch consistency,
603 : * for autovac we always want fresh stats.
604 : */
605 614 : SetConfigOption("stats_fetch_consistency", "none", PGC_SUSET, PGC_S_OVERRIDE);
606 :
607 : /*
608 : * In emergency mode, just start a worker (unless shutdown was requested)
609 : * and go away.
610 : */
611 614 : if (!AutoVacuumingActive())
612 : {
613 0 : if (!ShutdownRequestPending)
614 0 : do_start_worker();
615 0 : proc_exit(0); /* done */
616 : }
617 :
618 614 : AutoVacuumShmem->av_launcherpid = MyProcPid;
619 :
620 : /*
621 : * Create the initial database list. The invariant we want this list to
622 : * keep is that it's ordered by decreasing next_time. As soon as an entry
623 : * is updated to a higher time, it will be moved to the front (which is
624 : * correct because the only operation is to add autovacuum_naptime to the
625 : * entry, and time always increases).
626 : */
627 614 : rebuild_database_list(InvalidOid);
628 :
629 : /* loop until shutdown request */
630 3214 : while (!ShutdownRequestPending)
631 : {
632 : struct timeval nap;
633 3214 : TimestampTz current_time = 0;
634 : bool can_launch;
635 :
636 : /*
637 : * This loop is a bit different from the normal use of WaitLatch,
638 : * because we'd like to sleep before the first launch of a child
639 : * process. So it's WaitLatch, then ResetLatch, then check for
640 : * wakening conditions.
641 : */
642 :
643 3214 : launcher_determine_sleep(!dlist_is_empty(&AutoVacuumShmem->av_freeWorkers),
644 3214 : false, &nap);
645 :
646 : /*
647 : * Wait until naptime expires or we get some type of signal (all the
648 : * signal handlers will wake us by calling SetLatch).
649 : */
650 3214 : (void) WaitLatch(MyLatch,
651 : WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
652 3214 : (nap.tv_sec * 1000L) + (nap.tv_usec / 1000L),
653 : WAIT_EVENT_AUTOVACUUM_MAIN);
654 :
655 3208 : ResetLatch(MyLatch);
656 :
657 3208 : HandleAutoVacLauncherInterrupts();
658 :
659 : /*
660 : * a worker finished, or postmaster signaled failure to start a worker
661 : */
662 2600 : if (got_SIGUSR2)
663 : {
664 32 : got_SIGUSR2 = false;
665 :
666 : /* rebalance cost limits, if needed */
667 32 : if (AutoVacuumShmem->av_signal[AutoVacRebalance])
668 : {
669 16 : LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
670 16 : AutoVacuumShmem->av_signal[AutoVacRebalance] = false;
671 16 : autovac_recalculate_workers_for_balance();
672 16 : LWLockRelease(AutovacuumLock);
673 : }
674 :
675 32 : if (AutoVacuumShmem->av_signal[AutoVacForkFailed])
676 : {
677 : /*
678 : * If the postmaster failed to start a new worker, we sleep
679 : * for a little while and resend the signal. The new worker's
680 : * state is still in memory, so this is sufficient. After
681 : * that, we restart the main loop.
682 : *
683 : * XXX should we put a limit to the number of times we retry?
684 : * I don't think it makes much sense, because a future start
685 : * of a worker will continue to fail in the same way.
686 : */
687 0 : AutoVacuumShmem->av_signal[AutoVacForkFailed] = false;
688 0 : pg_usleep(1000000L); /* 1s */
689 0 : SendPostmasterSignal(PMSIGNAL_START_AUTOVAC_WORKER);
690 0 : continue;
691 : }
692 : }
693 :
694 : /*
695 : * There are some conditions that we need to check before trying to
696 : * start a worker. First, we need to make sure that there is a worker
697 : * slot available. Second, we need to make sure that no other worker
698 : * failed while starting up.
699 : */
700 :
701 2600 : current_time = GetCurrentTimestamp();
702 2600 : LWLockAcquire(AutovacuumLock, LW_SHARED);
703 :
704 2600 : can_launch = !dlist_is_empty(&AutoVacuumShmem->av_freeWorkers);
705 :
706 2600 : if (AutoVacuumShmem->av_startingWorker != NULL)
707 : {
708 : int waittime;
709 0 : WorkerInfo worker = AutoVacuumShmem->av_startingWorker;
710 :
711 : /*
712 : * We can't launch another worker when another one is still
713 : * starting up (or failed while doing so), so just sleep for a bit
714 : * more; that worker will wake us up again as soon as it's ready.
715 : * We will only wait autovacuum_naptime seconds (up to a maximum
716 : * of 60 seconds) for this to happen however. Note that failure
717 : * to connect to a particular database is not a problem here,
718 : * because the worker removes itself from the startingWorker
719 : * pointer before trying to connect. Problems detected by the
720 : * postmaster (like fork() failure) are also reported and handled
721 : * differently. The only problems that may cause this code to
722 : * fire are errors in the earlier sections of AutoVacWorkerMain,
723 : * before the worker removes the WorkerInfo from the
724 : * startingWorker pointer.
725 : */
726 0 : waittime = Min(autovacuum_naptime, 60) * 1000;
727 0 : if (TimestampDifferenceExceeds(worker->wi_launchtime, current_time,
728 : waittime))
729 : {
730 0 : LWLockRelease(AutovacuumLock);
731 0 : LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
732 :
733 : /*
734 : * No other process can put a worker in starting mode, so if
735 : * startingWorker is still INVALID after exchanging our lock,
736 : * we assume it's the same one we saw above (so we don't
737 : * recheck the launch time).
738 : */
739 0 : if (AutoVacuumShmem->av_startingWorker != NULL)
740 : {
741 0 : worker = AutoVacuumShmem->av_startingWorker;
742 0 : worker->wi_dboid = InvalidOid;
743 0 : worker->wi_tableoid = InvalidOid;
744 0 : worker->wi_sharedrel = false;
745 0 : worker->wi_proc = NULL;
746 0 : worker->wi_launchtime = 0;
747 0 : dlist_push_head(&AutoVacuumShmem->av_freeWorkers,
748 : &worker->wi_links);
749 0 : AutoVacuumShmem->av_startingWorker = NULL;
750 0 : ereport(WARNING,
751 : errmsg("autovacuum worker took too long to start; canceled"));
752 : }
753 : }
754 : else
755 0 : can_launch = false;
756 : }
757 2600 : LWLockRelease(AutovacuumLock); /* either shared or exclusive */
758 :
759 : /* if we can't do anything, just go back to sleep */
760 2600 : if (!can_launch)
761 0 : continue;
762 :
763 : /* We're OK to start a new worker */
764 :
765 2600 : if (dlist_is_empty(&DatabaseList))
766 : {
767 : /*
768 : * Special case when the list is empty: start a worker right away.
769 : * This covers the initial case, when no database is in pgstats
770 : * (thus the list is empty). Note that the constraints in
771 : * launcher_determine_sleep keep us from starting workers too
772 : * quickly (at most once every autovacuum_naptime when the list is
773 : * empty).
774 : */
775 60 : launch_worker(current_time);
776 : }
777 : else
778 : {
779 : /*
780 : * because rebuild_database_list constructs a list with most
781 : * distant adl_next_worker first, we obtain our database from the
782 : * tail of the list.
783 : */
784 : avl_dbase *avdb;
785 :
786 2540 : avdb = dlist_tail_element(avl_dbase, adl_node, &DatabaseList);
787 :
788 : /*
789 : * launch a worker if next_worker is right now or it is in the
790 : * past
791 : */
792 2540 : if (TimestampDifferenceExceeds(avdb->adl_next_worker,
793 : current_time, 0))
794 16 : launch_worker(current_time);
795 : }
796 : }
797 :
798 0 : AutoVacLauncherShutdown();
799 : }
800 :
801 : /*
802 : * Process any new interrupts.
803 : */
804 : static void
805 3208 : HandleAutoVacLauncherInterrupts(void)
806 : {
807 : /* the normal shutdown case */
808 3208 : if (ShutdownRequestPending)
809 608 : AutoVacLauncherShutdown();
810 :
811 2600 : if (ConfigReloadPending)
812 : {
813 52 : ConfigReloadPending = false;
814 52 : ProcessConfigFile(PGC_SIGHUP);
815 :
816 : /* shutdown requested in config file? */
817 52 : if (!AutoVacuumingActive())
818 0 : AutoVacLauncherShutdown();
819 :
820 : /* rebuild the list in case the naptime changed */
821 52 : rebuild_database_list(InvalidOid);
822 : }
823 :
824 : /* Process barrier events */
825 2600 : if (ProcSignalBarrierPending)
826 42 : ProcessProcSignalBarrier();
827 :
828 : /* Perform logging of memory contexts of this process */
829 2600 : if (LogMemoryContextPending)
830 0 : ProcessLogMemoryContextInterrupt();
831 :
832 : /* Process sinval catchup interrupts that happened while sleeping */
833 2600 : ProcessCatchupInterrupt();
834 2600 : }
835 :
836 : /*
837 : * Perform a normal exit from the autovac launcher.
838 : */
839 : static void
840 608 : AutoVacLauncherShutdown(void)
841 : {
842 608 : ereport(DEBUG1,
843 : (errmsg_internal("autovacuum launcher shutting down")));
844 608 : AutoVacuumShmem->av_launcherpid = 0;
845 :
846 608 : proc_exit(0); /* done */
847 : }
848 :
849 : /*
850 : * Determine the time to sleep, based on the database list.
851 : *
852 : * The "canlaunch" parameter indicates whether we can start a worker right now,
853 : * for example due to the workers being all busy. If this is false, we will
854 : * cause a long sleep, which will be interrupted when a worker exits.
855 : */
856 : static void
857 3214 : launcher_determine_sleep(bool canlaunch, bool recursing, struct timeval *nap)
858 : {
859 : /*
860 : * We sleep until the next scheduled vacuum. We trust that when the
861 : * database list was built, care was taken so that no entries have times
862 : * in the past; if the first entry has too close a next_worker value, or a
863 : * time in the past, we will sleep a small nominal time.
864 : */
865 3214 : if (!canlaunch)
866 : {
867 0 : nap->tv_sec = autovacuum_naptime;
868 0 : nap->tv_usec = 0;
869 : }
870 3214 : else if (!dlist_is_empty(&DatabaseList))
871 : {
872 3094 : TimestampTz current_time = GetCurrentTimestamp();
873 : TimestampTz next_wakeup;
874 : avl_dbase *avdb;
875 : long secs;
876 : int usecs;
877 :
878 3094 : avdb = dlist_tail_element(avl_dbase, adl_node, &DatabaseList);
879 :
880 3094 : next_wakeup = avdb->adl_next_worker;
881 3094 : TimestampDifference(current_time, next_wakeup, &secs, &usecs);
882 :
883 3094 : nap->tv_sec = secs;
884 3094 : nap->tv_usec = usecs;
885 : }
886 : else
887 : {
888 : /* list is empty, sleep for whole autovacuum_naptime seconds */
889 120 : nap->tv_sec = autovacuum_naptime;
890 120 : nap->tv_usec = 0;
891 : }
892 :
893 : /*
894 : * If the result is exactly zero, it means a database had an entry with
895 : * time in the past. Rebuild the list so that the databases are evenly
896 : * distributed again, and recalculate the time to sleep. This can happen
897 : * if there are more tables needing vacuum than workers, and they all take
898 : * longer to vacuum than autovacuum_naptime.
899 : *
900 : * We only recurse once. rebuild_database_list should always return times
901 : * in the future, but it seems best not to trust too much on that.
902 : */
903 3214 : if (nap->tv_sec == 0 && nap->tv_usec == 0 && !recursing)
904 : {
905 0 : rebuild_database_list(InvalidOid);
906 0 : launcher_determine_sleep(canlaunch, true, nap);
907 0 : return;
908 : }
909 :
910 : /* The smallest time we'll allow the launcher to sleep. */
911 3214 : if (nap->tv_sec <= 0 && nap->tv_usec <= MIN_AUTOVAC_SLEEPTIME * 1000)
912 : {
913 6 : nap->tv_sec = 0;
914 6 : nap->tv_usec = MIN_AUTOVAC_SLEEPTIME * 1000;
915 : }
916 :
917 : /*
918 : * If the sleep time is too large, clamp it to an arbitrary maximum (plus
919 : * any fractional seconds, for simplicity). This avoids an essentially
920 : * infinite sleep in strange cases like the system clock going backwards a
921 : * few years.
922 : */
923 3214 : if (nap->tv_sec > MAX_AUTOVAC_SLEEPTIME)
924 22 : nap->tv_sec = MAX_AUTOVAC_SLEEPTIME;
925 : }
926 :
927 : /*
928 : * Build an updated DatabaseList. It must only contain databases that appear
929 : * in pgstats, and must be sorted by next_worker from highest to lowest,
930 : * distributed regularly across the next autovacuum_naptime interval.
931 : *
932 : * Receives the Oid of the database that made this list be generated (we call
933 : * this the "new" database, because when the database was already present on
934 : * the list, we expect that this function is not called at all). The
935 : * preexisting list, if any, will be used to preserve the order of the
936 : * databases in the autovacuum_naptime period. The new database is put at the
937 : * end of the interval. The actual values are not saved, which should not be
938 : * much of a problem.
939 : */
940 : static void
941 674 : rebuild_database_list(Oid newdb)
942 : {
943 : List *dblist;
944 : ListCell *cell;
945 : MemoryContext newcxt;
946 : MemoryContext oldcxt;
947 : MemoryContext tmpcxt;
948 : HASHCTL hctl;
949 : int score;
950 : int nelems;
951 : HTAB *dbhash;
952 : dlist_iter iter;
953 :
954 674 : newcxt = AllocSetContextCreate(AutovacMemCxt,
955 : "Autovacuum database list",
956 : ALLOCSET_DEFAULT_SIZES);
957 674 : tmpcxt = AllocSetContextCreate(newcxt,
958 : "Autovacuum database list (tmp)",
959 : ALLOCSET_DEFAULT_SIZES);
960 674 : oldcxt = MemoryContextSwitchTo(tmpcxt);
961 :
962 : /*
963 : * Implementing this is not as simple as it sounds, because we need to put
964 : * the new database at the end of the list; next the databases that were
965 : * already on the list, and finally (at the tail of the list) all the
966 : * other databases that are not on the existing list.
967 : *
968 : * To do this, we build an empty hash table of scored databases. We will
969 : * start with the lowest score (zero) for the new database, then
970 : * increasing scores for the databases in the existing list, in order, and
971 : * lastly increasing scores for all databases gotten via
972 : * get_database_list() that are not already on the hash.
973 : *
974 : * Then we will put all the hash elements into an array, sort the array by
975 : * score, and finally put the array elements into the new doubly linked
976 : * list.
977 : */
978 674 : hctl.keysize = sizeof(Oid);
979 674 : hctl.entrysize = sizeof(avl_dbase);
980 674 : hctl.hcxt = tmpcxt;
981 674 : dbhash = hash_create("autovacuum db hash", 20, &hctl, /* magic number here
982 : * FIXME */
983 : HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
984 :
985 : /* start by inserting the new database */
986 674 : score = 0;
987 674 : if (OidIsValid(newdb))
988 : {
989 : avl_dbase *db;
990 : PgStat_StatDBEntry *entry;
991 :
992 : /* only consider this database if it has a pgstat entry */
993 8 : entry = pgstat_fetch_stat_dbentry(newdb);
994 8 : if (entry != NULL)
995 : {
996 : /* we assume it isn't found because the hash was just created */
997 8 : db = hash_search(dbhash, &newdb, HASH_ENTER, NULL);
998 :
999 : /* hash_search already filled in the key */
1000 8 : db->adl_score = score++;
1001 : /* next_worker is filled in later */
1002 : }
1003 : }
1004 :
1005 : /* Now insert the databases from the existing list */
1006 760 : dlist_foreach(iter, &DatabaseList)
1007 : {
1008 86 : avl_dbase *avdb = dlist_container(avl_dbase, adl_node, iter.cur);
1009 : avl_dbase *db;
1010 : bool found;
1011 : PgStat_StatDBEntry *entry;
1012 :
1013 : /*
1014 : * skip databases with no stat entries -- in particular, this gets rid
1015 : * of dropped databases
1016 : */
1017 86 : entry = pgstat_fetch_stat_dbentry(avdb->adl_datid);
1018 86 : if (entry == NULL)
1019 0 : continue;
1020 :
1021 86 : db = hash_search(dbhash, &(avdb->adl_datid), HASH_ENTER, &found);
1022 :
1023 86 : if (!found)
1024 : {
1025 : /* hash_search already filled in the key */
1026 86 : db->adl_score = score++;
1027 : /* next_worker is filled in later */
1028 : }
1029 : }
1030 :
1031 : /* finally, insert all qualifying databases not previously inserted */
1032 674 : dblist = get_database_list();
1033 2990 : foreach(cell, dblist)
1034 : {
1035 2316 : avw_dbase *avdb = lfirst(cell);
1036 : avl_dbase *db;
1037 : bool found;
1038 : PgStat_StatDBEntry *entry;
1039 :
1040 : /* only consider databases with a pgstat entry */
1041 2316 : entry = pgstat_fetch_stat_dbentry(avdb->adw_datid);
1042 2316 : if (entry == NULL)
1043 1436 : continue;
1044 :
1045 880 : db = hash_search(dbhash, &(avdb->adw_datid), HASH_ENTER, &found);
1046 : /* only update the score if the database was not already on the hash */
1047 880 : if (!found)
1048 : {
1049 : /* hash_search already filled in the key */
1050 786 : db->adl_score = score++;
1051 : /* next_worker is filled in later */
1052 : }
1053 : }
1054 674 : nelems = score;
1055 :
1056 : /* from here on, the allocated memory belongs to the new list */
1057 674 : MemoryContextSwitchTo(newcxt);
1058 674 : dlist_init(&DatabaseList);
1059 :
1060 674 : if (nelems > 0)
1061 : {
1062 : TimestampTz current_time;
1063 : int millis_increment;
1064 : avl_dbase *dbary;
1065 : avl_dbase *db;
1066 : HASH_SEQ_STATUS seq;
1067 : int i;
1068 :
1069 : /* put all the hash elements into an array */
1070 614 : dbary = palloc(nelems * sizeof(avl_dbase));
1071 :
1072 614 : i = 0;
1073 614 : hash_seq_init(&seq, dbhash);
1074 1494 : while ((db = hash_seq_search(&seq)) != NULL)
1075 880 : memcpy(&(dbary[i++]), db, sizeof(avl_dbase));
1076 :
1077 : /* sort the array */
1078 614 : qsort(dbary, nelems, sizeof(avl_dbase), db_comparator);
1079 :
1080 : /*
1081 : * Determine the time interval between databases in the schedule. If
1082 : * we see that the configured naptime would take us to sleep times
1083 : * lower than our min sleep time (which launcher_determine_sleep is
1084 : * coded not to allow), silently use a larger naptime (but don't touch
1085 : * the GUC variable).
1086 : */
1087 614 : millis_increment = 1000.0 * autovacuum_naptime / nelems;
1088 614 : if (millis_increment <= MIN_AUTOVAC_SLEEPTIME)
1089 0 : millis_increment = MIN_AUTOVAC_SLEEPTIME * 1.1;
1090 :
1091 614 : current_time = GetCurrentTimestamp();
1092 :
1093 : /*
1094 : * move the elements from the array into the dlist, setting the
1095 : * next_worker while walking the array
1096 : */
1097 1494 : for (i = 0; i < nelems; i++)
1098 : {
1099 880 : db = &(dbary[i]);
1100 :
1101 880 : current_time = TimestampTzPlusMilliseconds(current_time,
1102 : millis_increment);
1103 880 : db->adl_next_worker = current_time;
1104 :
1105 : /* later elements should go closer to the head of the list */
1106 880 : dlist_push_head(&DatabaseList, &db->adl_node);
1107 : }
1108 : }
1109 :
1110 : /* all done, clean up memory */
1111 674 : if (DatabaseListCxt != NULL)
1112 60 : MemoryContextDelete(DatabaseListCxt);
1113 674 : MemoryContextDelete(tmpcxt);
1114 674 : DatabaseListCxt = newcxt;
1115 674 : MemoryContextSwitchTo(oldcxt);
1116 674 : }
1117 :
1118 : /* qsort comparator for avl_dbase, using adl_score */
1119 : static int
1120 362 : db_comparator(const void *a, const void *b)
1121 : {
1122 362 : if (((const avl_dbase *) a)->adl_score == ((const avl_dbase *) b)->adl_score)
1123 0 : return 0;
1124 : else
1125 362 : return (((const avl_dbase *) a)->adl_score < ((const avl_dbase *) b)->adl_score) ? 1 : -1;
1126 : }
1127 :
1128 : /*
1129 : * do_start_worker
1130 : *
1131 : * Bare-bones procedure for starting an autovacuum worker from the launcher.
1132 : * It determines what database to work on, sets up shared memory stuff and
1133 : * signals postmaster to start the worker. It fails gracefully if invoked when
1134 : * autovacuum_workers are already active.
1135 : *
1136 : * Return value is the OID of the database that the worker is going to process,
1137 : * or InvalidOid if no worker was actually started.
1138 : */
1139 : static Oid
1140 76 : do_start_worker(void)
1141 : {
1142 : List *dblist;
1143 : ListCell *cell;
1144 : TransactionId xidForceLimit;
1145 : MultiXactId multiForceLimit;
1146 : bool for_xid_wrap;
1147 : bool for_multi_wrap;
1148 : avw_dbase *avdb;
1149 : TimestampTz current_time;
1150 76 : bool skipit = false;
1151 76 : Oid retval = InvalidOid;
1152 : MemoryContext tmpcxt,
1153 : oldcxt;
1154 :
1155 : /* return quickly when there are no free workers */
1156 76 : LWLockAcquire(AutovacuumLock, LW_SHARED);
1157 76 : if (dlist_is_empty(&AutoVacuumShmem->av_freeWorkers))
1158 : {
1159 0 : LWLockRelease(AutovacuumLock);
1160 0 : return InvalidOid;
1161 : }
1162 76 : LWLockRelease(AutovacuumLock);
1163 :
1164 : /*
1165 : * Create and switch to a temporary context to avoid leaking the memory
1166 : * allocated for the database list.
1167 : */
1168 76 : tmpcxt = AllocSetContextCreate(CurrentMemoryContext,
1169 : "Autovacuum start worker (tmp)",
1170 : ALLOCSET_DEFAULT_SIZES);
1171 76 : oldcxt = MemoryContextSwitchTo(tmpcxt);
1172 :
1173 : /* Get a list of databases */
1174 76 : dblist = get_database_list();
1175 :
1176 : /*
1177 : * Determine the oldest datfrozenxid/relfrozenxid that we will allow to
1178 : * pass without forcing a vacuum. (This limit can be tightened for
1179 : * particular tables, but not loosened.)
1180 : */
1181 76 : recentXid = ReadNextTransactionId();
1182 76 : xidForceLimit = recentXid - autovacuum_freeze_max_age;
1183 : /* ensure it's a "normal" XID, else TransactionIdPrecedes misbehaves */
1184 : /* this can cause the limit to go backwards by 3, but that's OK */
1185 76 : if (xidForceLimit < FirstNormalTransactionId)
1186 0 : xidForceLimit -= FirstNormalTransactionId;
1187 :
1188 : /* Also determine the oldest datminmxid we will consider. */
1189 76 : recentMulti = ReadNextMultiXactId();
1190 76 : multiForceLimit = recentMulti - MultiXactMemberFreezeThreshold();
1191 76 : if (multiForceLimit < FirstMultiXactId)
1192 0 : multiForceLimit -= FirstMultiXactId;
1193 :
1194 : /*
1195 : * Choose a database to connect to. We pick the database that was least
1196 : * recently auto-vacuumed, or one that needs vacuuming to prevent Xid
1197 : * wraparound-related data loss. If any db at risk of Xid wraparound is
1198 : * found, we pick the one with oldest datfrozenxid, independently of
1199 : * autovacuum times; similarly we pick the one with the oldest datminmxid
1200 : * if any is in MultiXactId wraparound. Note that those in Xid wraparound
1201 : * danger are given more priority than those in multi wraparound danger.
1202 : *
1203 : * Note that a database with no stats entry is not considered, except for
1204 : * Xid wraparound purposes. The theory is that if no one has ever
1205 : * connected to it since the stats were last initialized, it doesn't need
1206 : * vacuuming.
1207 : *
1208 : * XXX This could be improved if we had more info about whether it needs
1209 : * vacuuming before connecting to it. Perhaps look through the pgstats
1210 : * data for the database's tables? One idea is to keep track of the
1211 : * number of new and dead tuples per database in pgstats. However it
1212 : * isn't clear how to construct a metric that measures that and not cause
1213 : * starvation for less busy databases.
1214 : */
1215 76 : avdb = NULL;
1216 76 : for_xid_wrap = false;
1217 76 : for_multi_wrap = false;
1218 76 : current_time = GetCurrentTimestamp();
1219 342 : foreach(cell, dblist)
1220 : {
1221 266 : avw_dbase *tmp = lfirst(cell);
1222 : dlist_iter iter;
1223 :
1224 : /* Check to see if this one is at risk of wraparound */
1225 266 : if (TransactionIdPrecedes(tmp->adw_frozenxid, xidForceLimit))
1226 : {
1227 0 : if (avdb == NULL ||
1228 0 : TransactionIdPrecedes(tmp->adw_frozenxid,
1229 : avdb->adw_frozenxid))
1230 0 : avdb = tmp;
1231 0 : for_xid_wrap = true;
1232 236 : continue;
1233 : }
1234 266 : else if (for_xid_wrap)
1235 0 : continue; /* ignore not-at-risk DBs */
1236 266 : else if (MultiXactIdPrecedes(tmp->adw_minmulti, multiForceLimit))
1237 : {
1238 0 : if (avdb == NULL ||
1239 0 : MultiXactIdPrecedes(tmp->adw_minmulti, avdb->adw_minmulti))
1240 0 : avdb = tmp;
1241 0 : for_multi_wrap = true;
1242 0 : continue;
1243 : }
1244 266 : else if (for_multi_wrap)
1245 0 : continue; /* ignore not-at-risk DBs */
1246 :
1247 : /* Find pgstat entry if any */
1248 266 : tmp->adw_entry = pgstat_fetch_stat_dbentry(tmp->adw_datid);
1249 :
1250 : /*
1251 : * Skip a database with no pgstat entry; it means it hasn't seen any
1252 : * activity.
1253 : */
1254 266 : if (!tmp->adw_entry)
1255 220 : continue;
1256 :
1257 : /*
1258 : * Also, skip a database that appears on the database list as having
1259 : * been processed recently (less than autovacuum_naptime seconds ago).
1260 : * We do this so that we don't select a database which we just
1261 : * selected, but that pgstat hasn't gotten around to updating the last
1262 : * autovacuum time yet.
1263 : */
1264 46 : skipit = false;
1265 :
1266 84 : dlist_reverse_foreach(iter, &DatabaseList)
1267 : {
1268 70 : avl_dbase *dbp = dlist_container(avl_dbase, adl_node, iter.cur);
1269 :
1270 70 : if (dbp->adl_datid == tmp->adw_datid)
1271 : {
1272 : /*
1273 : * Skip this database if its next_worker value falls between
1274 : * the current time and the current time plus naptime.
1275 : */
1276 32 : if (!TimestampDifferenceExceeds(dbp->adl_next_worker,
1277 16 : current_time, 0) &&
1278 16 : !TimestampDifferenceExceeds(current_time,
1279 : dbp->adl_next_worker,
1280 : autovacuum_naptime * 1000))
1281 16 : skipit = true;
1282 :
1283 32 : break;
1284 : }
1285 : }
1286 46 : if (skipit)
1287 16 : continue;
1288 :
1289 : /*
1290 : * Remember the db with oldest autovac time. (If we are here, both
1291 : * tmp->entry and db->entry must be non-null.)
1292 : */
1293 30 : if (avdb == NULL ||
1294 14 : tmp->adw_entry->last_autovac_time < avdb->adw_entry->last_autovac_time)
1295 16 : avdb = tmp;
1296 : }
1297 :
1298 : /* Found a database -- process it */
1299 76 : if (avdb != NULL)
1300 : {
1301 : WorkerInfo worker;
1302 : dlist_node *wptr;
1303 :
1304 16 : LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
1305 :
1306 : /*
1307 : * Get a worker entry from the freelist. We checked above, so there
1308 : * really should be a free slot.
1309 : */
1310 16 : wptr = dlist_pop_head_node(&AutoVacuumShmem->av_freeWorkers);
1311 :
1312 16 : worker = dlist_container(WorkerInfoData, wi_links, wptr);
1313 16 : worker->wi_dboid = avdb->adw_datid;
1314 16 : worker->wi_proc = NULL;
1315 16 : worker->wi_launchtime = GetCurrentTimestamp();
1316 :
1317 16 : AutoVacuumShmem->av_startingWorker = worker;
1318 :
1319 16 : LWLockRelease(AutovacuumLock);
1320 :
1321 16 : SendPostmasterSignal(PMSIGNAL_START_AUTOVAC_WORKER);
1322 :
1323 16 : retval = avdb->adw_datid;
1324 : }
1325 60 : else if (skipit)
1326 : {
1327 : /*
1328 : * If we skipped all databases on the list, rebuild it, because it
1329 : * probably contains a dropped database.
1330 : */
1331 0 : rebuild_database_list(InvalidOid);
1332 : }
1333 :
1334 76 : MemoryContextSwitchTo(oldcxt);
1335 76 : MemoryContextDelete(tmpcxt);
1336 :
1337 76 : return retval;
1338 : }
1339 :
1340 : /*
1341 : * launch_worker
1342 : *
1343 : * Wrapper for starting a worker from the launcher. Besides actually starting
1344 : * it, update the database list to reflect the next time that another one will
1345 : * need to be started on the selected database. The actual database choice is
1346 : * left to do_start_worker.
1347 : *
1348 : * This routine is also expected to insert an entry into the database list if
1349 : * the selected database was previously absent from the list.
1350 : */
1351 : static void
1352 76 : launch_worker(TimestampTz now)
1353 : {
1354 : Oid dbid;
1355 : dlist_iter iter;
1356 :
1357 76 : dbid = do_start_worker();
1358 76 : if (OidIsValid(dbid))
1359 : {
1360 16 : bool found = false;
1361 :
1362 : /*
1363 : * Walk the database list and update the corresponding entry. If the
1364 : * database is not on the list, we'll recreate the list.
1365 : */
1366 40 : dlist_foreach(iter, &DatabaseList)
1367 : {
1368 32 : avl_dbase *avdb = dlist_container(avl_dbase, adl_node, iter.cur);
1369 :
1370 32 : if (avdb->adl_datid == dbid)
1371 : {
1372 8 : found = true;
1373 :
1374 : /*
1375 : * add autovacuum_naptime seconds to the current time, and use
1376 : * that as the new "next_worker" field for this database.
1377 : */
1378 8 : avdb->adl_next_worker =
1379 8 : TimestampTzPlusMilliseconds(now, autovacuum_naptime * 1000);
1380 :
1381 8 : dlist_move_head(&DatabaseList, iter.cur);
1382 8 : break;
1383 : }
1384 : }
1385 :
1386 : /*
1387 : * If the database was not present in the database list, we rebuild
1388 : * the list. It's possible that the database does not get into the
1389 : * list anyway, for example if it's a database that doesn't have a
1390 : * pgstat entry, but this is not a problem because we don't want to
1391 : * schedule workers regularly into those in any case.
1392 : */
1393 16 : if (!found)
1394 8 : rebuild_database_list(dbid);
1395 : }
1396 76 : }
1397 :
1398 : /*
1399 : * Called from postmaster to signal a failure to fork a process to become
1400 : * worker. The postmaster should kill(SIGUSR2) the launcher shortly
1401 : * after calling this function.
1402 : */
1403 : void
1404 0 : AutoVacWorkerFailed(void)
1405 : {
1406 0 : AutoVacuumShmem->av_signal[AutoVacForkFailed] = true;
1407 0 : }
1408 :
1409 : /* SIGUSR2: a worker is up and running, or just finished, or failed to fork */
1410 : static void
1411 32 : avl_sigusr2_handler(SIGNAL_ARGS)
1412 : {
1413 32 : int save_errno = errno;
1414 :
1415 32 : got_SIGUSR2 = true;
1416 32 : SetLatch(MyLatch);
1417 :
1418 32 : errno = save_errno;
1419 32 : }
1420 :
1421 :
1422 : /********************************************************************
1423 : * AUTOVACUUM WORKER CODE
1424 : ********************************************************************/
1425 :
1426 : #ifdef EXEC_BACKEND
1427 : /*
1428 : * forkexec routines for the autovacuum worker.
1429 : *
1430 : * Format up the arglist, then fork and exec.
1431 : */
1432 : static pid_t
1433 : avworker_forkexec(void)
1434 : {
1435 : char *av[10];
1436 : int ac = 0;
1437 :
1438 : av[ac++] = "postgres";
1439 : av[ac++] = "--forkavworker";
1440 : av[ac++] = NULL; /* filled in by postmaster_forkexec */
1441 : av[ac] = NULL;
1442 :
1443 : Assert(ac < lengthof(av));
1444 :
1445 : return postmaster_forkexec(ac, av);
1446 : }
1447 : #endif
1448 :
1449 : /*
1450 : * Main entry point for autovacuum worker process.
1451 : *
1452 : * This code is heavily based on pgarch.c, q.v.
1453 : */
1454 : int
1455 16 : StartAutoVacWorker(void)
1456 : {
1457 : pid_t worker_pid;
1458 :
1459 : #ifdef EXEC_BACKEND
1460 : switch ((worker_pid = avworker_forkexec()))
1461 : #else
1462 16 : switch ((worker_pid = fork_process()))
1463 : #endif
1464 : {
1465 0 : case -1:
1466 0 : ereport(LOG,
1467 : (errmsg("could not fork autovacuum worker process: %m")));
1468 0 : return 0;
1469 :
1470 : #ifndef EXEC_BACKEND
1471 16 : case 0:
1472 : /* in postmaster child ... */
1473 16 : InitPostmasterChild();
1474 :
1475 : /* Close the postmaster's sockets */
1476 16 : ClosePostmasterPorts(false);
1477 :
1478 16 : AutoVacWorkerMain(0, NULL);
1479 : break;
1480 : #endif
1481 16 : default:
1482 16 : return (int) worker_pid;
1483 : }
1484 :
1485 : /* shouldn't get here */
1486 : return 0;
1487 : }
1488 :
1489 : /*
1490 : * AutoVacWorkerMain
1491 : */
1492 : NON_EXEC_STATIC void
1493 16 : AutoVacWorkerMain(int argc, char *argv[])
1494 : {
1495 : sigjmp_buf local_sigjmp_buf;
1496 : Oid dbid;
1497 :
1498 16 : am_autovacuum_worker = true;
1499 :
1500 16 : MyBackendType = B_AUTOVAC_WORKER;
1501 16 : init_ps_display(NULL);
1502 :
1503 16 : SetProcessingMode(InitProcessing);
1504 :
1505 : /*
1506 : * Set up signal handlers. We operate on databases much like a regular
1507 : * backend, so we use the same signal handling. See equivalent code in
1508 : * tcop/postgres.c.
1509 : */
1510 16 : pqsignal(SIGHUP, SignalHandlerForConfigReload);
1511 :
1512 : /*
1513 : * SIGINT is used to signal canceling the current table's vacuum; SIGTERM
1514 : * means abort and exit cleanly, and SIGQUIT means abandon ship.
1515 : */
1516 16 : pqsignal(SIGINT, StatementCancelHandler);
1517 16 : pqsignal(SIGTERM, die);
1518 : /* SIGQUIT handler was already set up by InitPostmasterChild */
1519 :
1520 16 : InitializeTimeouts(); /* establishes SIGALRM handler */
1521 :
1522 16 : pqsignal(SIGPIPE, SIG_IGN);
1523 16 : pqsignal(SIGUSR1, procsignal_sigusr1_handler);
1524 16 : pqsignal(SIGUSR2, SIG_IGN);
1525 16 : pqsignal(SIGFPE, FloatExceptionHandler);
1526 16 : pqsignal(SIGCHLD, SIG_DFL);
1527 :
1528 : /*
1529 : * Create a per-backend PGPROC struct in shared memory. We must do this
1530 : * before we can use LWLocks or access any shared memory.
1531 : */
1532 16 : InitProcess();
1533 :
1534 : /* Early initialization */
1535 16 : BaseInit();
1536 :
1537 : /*
1538 : * If an exception is encountered, processing resumes here.
1539 : *
1540 : * Unlike most auxiliary processes, we don't attempt to continue
1541 : * processing after an error; we just clean up and exit. The autovac
1542 : * launcher is responsible for spawning another worker later.
1543 : *
1544 : * Note that we use sigsetjmp(..., 1), so that the prevailing signal mask
1545 : * (to wit, BlockSig) will be restored when longjmp'ing to here. Thus,
1546 : * signals other than SIGQUIT will be blocked until we exit. It might
1547 : * seem that this policy makes the HOLD_INTERRUPTS() call redundant, but
1548 : * it is not since InterruptPending might be set already.
1549 : */
1550 16 : if (sigsetjmp(local_sigjmp_buf, 1) != 0)
1551 : {
1552 : /* since not using PG_TRY, must reset error stack by hand */
1553 0 : error_context_stack = NULL;
1554 :
1555 : /* Prevents interrupts while cleaning up */
1556 0 : HOLD_INTERRUPTS();
1557 :
1558 : /* Report the error to the server log */
1559 0 : EmitErrorReport();
1560 :
1561 : /*
1562 : * We can now go away. Note that because we called InitProcess, a
1563 : * callback was registered to do ProcKill, which will clean up
1564 : * necessary state.
1565 : */
1566 0 : proc_exit(0);
1567 : }
1568 :
1569 : /* We can now handle ereport(ERROR) */
1570 16 : PG_exception_stack = &local_sigjmp_buf;
1571 :
1572 16 : sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
1573 :
1574 : /*
1575 : * Set always-secure search path, so malicious users can't redirect user
1576 : * code (e.g. pg_index.indexprs). (That code runs in a
1577 : * SECURITY_RESTRICTED_OPERATION sandbox, so malicious users could not
1578 : * take control of the entire autovacuum worker in any case.)
1579 : */
1580 16 : SetConfigOption("search_path", "", PGC_SUSET, PGC_S_OVERRIDE);
1581 :
1582 : /*
1583 : * Force zero_damaged_pages OFF in the autovac process, even if it is set
1584 : * in postgresql.conf. We don't really want such a dangerous option being
1585 : * applied non-interactively.
1586 : */
1587 16 : SetConfigOption("zero_damaged_pages", "false", PGC_SUSET, PGC_S_OVERRIDE);
1588 :
1589 : /*
1590 : * Force settable timeouts off to avoid letting these settings prevent
1591 : * regular maintenance from being executed.
1592 : */
1593 16 : SetConfigOption("statement_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
1594 16 : SetConfigOption("lock_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
1595 16 : SetConfigOption("idle_in_transaction_session_timeout", "0",
1596 : PGC_SUSET, PGC_S_OVERRIDE);
1597 :
1598 : /*
1599 : * Force default_transaction_isolation to READ COMMITTED. We don't want
1600 : * to pay the overhead of serializable mode, nor add any risk of causing
1601 : * deadlocks or delaying other transactions.
1602 : */
1603 16 : SetConfigOption("default_transaction_isolation", "read committed",
1604 : PGC_SUSET, PGC_S_OVERRIDE);
1605 :
1606 : /*
1607 : * Force synchronous replication off to allow regular maintenance even if
1608 : * we are waiting for standbys to connect. This is important to ensure we
1609 : * aren't blocked from performing anti-wraparound tasks.
1610 : */
1611 16 : if (synchronous_commit > SYNCHRONOUS_COMMIT_LOCAL_FLUSH)
1612 16 : SetConfigOption("synchronous_commit", "local",
1613 : PGC_SUSET, PGC_S_OVERRIDE);
1614 :
1615 : /*
1616 : * Even when system is configured to use a different fetch consistency,
1617 : * for autovac we always want fresh stats.
1618 : */
1619 16 : SetConfigOption("stats_fetch_consistency", "none", PGC_SUSET, PGC_S_OVERRIDE);
1620 :
1621 : /*
1622 : * Get the info about the database we're going to work on.
1623 : */
1624 16 : LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
1625 :
1626 : /*
1627 : * beware of startingWorker being INVALID; this should normally not
1628 : * happen, but if a worker fails after forking and before this, the
1629 : * launcher might have decided to remove it from the queue and start
1630 : * again.
1631 : */
1632 16 : if (AutoVacuumShmem->av_startingWorker != NULL)
1633 : {
1634 16 : MyWorkerInfo = AutoVacuumShmem->av_startingWorker;
1635 16 : dbid = MyWorkerInfo->wi_dboid;
1636 16 : MyWorkerInfo->wi_proc = MyProc;
1637 :
1638 : /* insert into the running list */
1639 16 : dlist_push_head(&AutoVacuumShmem->av_runningWorkers,
1640 16 : &MyWorkerInfo->wi_links);
1641 :
1642 : /*
1643 : * remove from the "starting" pointer, so that the launcher can start
1644 : * a new worker if required
1645 : */
1646 16 : AutoVacuumShmem->av_startingWorker = NULL;
1647 16 : LWLockRelease(AutovacuumLock);
1648 :
1649 16 : on_shmem_exit(FreeWorkerInfo, 0);
1650 :
1651 : /* wake up the launcher */
1652 16 : if (AutoVacuumShmem->av_launcherpid != 0)
1653 16 : kill(AutoVacuumShmem->av_launcherpid, SIGUSR2);
1654 : }
1655 : else
1656 : {
1657 : /* no worker entry for me, go away */
1658 0 : elog(WARNING, "autovacuum worker started without a worker entry");
1659 0 : dbid = InvalidOid;
1660 0 : LWLockRelease(AutovacuumLock);
1661 : }
1662 :
1663 16 : if (OidIsValid(dbid))
1664 : {
1665 : char dbname[NAMEDATALEN];
1666 :
1667 : /*
1668 : * Report autovac startup to the cumulative stats system. We
1669 : * deliberately do this before InitPostgres, so that the
1670 : * last_autovac_time will get updated even if the connection attempt
1671 : * fails. This is to prevent autovac from getting "stuck" repeatedly
1672 : * selecting an unopenable database, rather than making any progress
1673 : * on stuff it can connect to.
1674 : */
1675 16 : pgstat_report_autovac(dbid);
1676 :
1677 : /*
1678 : * Connect to the selected database, specifying no particular user
1679 : *
1680 : * Note: if we have selected a just-deleted database (due to using
1681 : * stale stats info), we'll fail and exit here.
1682 : */
1683 16 : InitPostgres(NULL, dbid, NULL, InvalidOid, 0, dbname);
1684 16 : SetProcessingMode(NormalProcessing);
1685 16 : set_ps_display(dbname);
1686 16 : ereport(DEBUG1,
1687 : (errmsg_internal("autovacuum: processing database \"%s\"", dbname)));
1688 :
1689 16 : if (PostAuthDelay)
1690 0 : pg_usleep(PostAuthDelay * 1000000L);
1691 :
1692 : /* And do an appropriate amount of work */
1693 16 : recentXid = ReadNextTransactionId();
1694 16 : recentMulti = ReadNextMultiXactId();
1695 16 : do_autovacuum();
1696 : }
1697 :
1698 : /*
1699 : * The launcher will be notified of my death in ProcKill, *if* we managed
1700 : * to get a worker slot at all
1701 : */
1702 :
1703 : /* All done, go away */
1704 16 : proc_exit(0);
1705 : }
1706 :
1707 : /*
1708 : * Return a WorkerInfo to the free list
1709 : */
1710 : static void
1711 16 : FreeWorkerInfo(int code, Datum arg)
1712 : {
1713 16 : if (MyWorkerInfo != NULL)
1714 : {
1715 16 : LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
1716 :
1717 : /*
1718 : * Wake the launcher up so that he can launch a new worker immediately
1719 : * if required. We only save the launcher's PID in local memory here;
1720 : * the actual signal will be sent when the PGPROC is recycled. Note
1721 : * that we always do this, so that the launcher can rebalance the cost
1722 : * limit setting of the remaining workers.
1723 : *
1724 : * We somewhat ignore the risk that the launcher changes its PID
1725 : * between us reading it and the actual kill; we expect ProcKill to be
1726 : * called shortly after us, and we assume that PIDs are not reused too
1727 : * quickly after a process exits.
1728 : */
1729 16 : AutovacuumLauncherPid = AutoVacuumShmem->av_launcherpid;
1730 :
1731 16 : dlist_delete(&MyWorkerInfo->wi_links);
1732 16 : MyWorkerInfo->wi_dboid = InvalidOid;
1733 16 : MyWorkerInfo->wi_tableoid = InvalidOid;
1734 16 : MyWorkerInfo->wi_sharedrel = false;
1735 16 : MyWorkerInfo->wi_proc = NULL;
1736 16 : MyWorkerInfo->wi_launchtime = 0;
1737 16 : pg_atomic_clear_flag(&MyWorkerInfo->wi_dobalance);
1738 16 : dlist_push_head(&AutoVacuumShmem->av_freeWorkers,
1739 16 : &MyWorkerInfo->wi_links);
1740 : /* not mine anymore */
1741 16 : MyWorkerInfo = NULL;
1742 :
1743 : /*
1744 : * now that we're inactive, cause a rebalancing of the surviving
1745 : * workers
1746 : */
1747 16 : AutoVacuumShmem->av_signal[AutoVacRebalance] = true;
1748 16 : LWLockRelease(AutovacuumLock);
1749 : }
1750 16 : }
1751 :
1752 : /*
1753 : * Update vacuum cost-based delay-related parameters for autovacuum workers and
1754 : * backends executing VACUUM or ANALYZE using the value of relevant GUCs and
1755 : * global state. This must be called during setup for vacuum and after every
1756 : * config reload to ensure up-to-date values.
1757 : */
1758 : void
1759 9710 : VacuumUpdateCosts(void)
1760 : {
1761 9710 : if (MyWorkerInfo)
1762 : {
1763 404 : if (av_storage_param_cost_delay >= 0)
1764 0 : vacuum_cost_delay = av_storage_param_cost_delay;
1765 404 : else if (autovacuum_vac_cost_delay >= 0)
1766 404 : vacuum_cost_delay = autovacuum_vac_cost_delay;
1767 : else
1768 : /* fall back to VacuumCostDelay */
1769 0 : vacuum_cost_delay = VacuumCostDelay;
1770 :
1771 404 : AutoVacuumUpdateCostLimit();
1772 : }
1773 : else
1774 : {
1775 : /* Must be explicit VACUUM or ANALYZE */
1776 9306 : vacuum_cost_delay = VacuumCostDelay;
1777 9306 : vacuum_cost_limit = VacuumCostLimit;
1778 : }
1779 :
1780 : /*
1781 : * If configuration changes are allowed to impact VacuumCostActive, make
1782 : * sure it is updated.
1783 : */
1784 9710 : if (VacuumFailsafeActive)
1785 : Assert(!VacuumCostActive);
1786 9710 : else if (vacuum_cost_delay > 0)
1787 404 : VacuumCostActive = true;
1788 : else
1789 : {
1790 9306 : VacuumCostActive = false;
1791 9306 : VacuumCostBalance = 0;
1792 : }
1793 :
1794 : /*
1795 : * Since the cost logging requires a lock, avoid rendering the log message
1796 : * in case we are using a message level where the log wouldn't be emitted.
1797 : */
1798 9710 : if (MyWorkerInfo && message_level_is_interesting(DEBUG2))
1799 : {
1800 : Oid dboid,
1801 : tableoid;
1802 :
1803 : Assert(!LWLockHeldByMe(AutovacuumLock));
1804 :
1805 0 : LWLockAcquire(AutovacuumLock, LW_SHARED);
1806 0 : dboid = MyWorkerInfo->wi_dboid;
1807 0 : tableoid = MyWorkerInfo->wi_tableoid;
1808 0 : LWLockRelease(AutovacuumLock);
1809 :
1810 0 : elog(DEBUG2,
1811 : "Autovacuum VacuumUpdateCosts(db=%u, rel=%u, dobalance=%s, cost_limit=%d, cost_delay=%g active=%s failsafe=%s)",
1812 : dboid, tableoid, pg_atomic_unlocked_test_flag(&MyWorkerInfo->wi_dobalance) ? "no" : "yes",
1813 : vacuum_cost_limit, vacuum_cost_delay,
1814 : vacuum_cost_delay > 0 ? "yes" : "no",
1815 : VacuumFailsafeActive ? "yes" : "no");
1816 : }
1817 9710 : }
1818 :
1819 : /*
1820 : * Update vacuum_cost_limit with the correct value for an autovacuum worker,
1821 : * given the value of other relevant cost limit parameters and the number of
1822 : * workers across which the limit must be balanced. Autovacuum workers must
1823 : * call this regularly in case av_nworkersForBalance has been updated by
1824 : * another worker or by the autovacuum launcher. They must also call it after a
1825 : * config reload.
1826 : */
1827 : void
1828 786 : AutoVacuumUpdateCostLimit(void)
1829 : {
1830 786 : if (!MyWorkerInfo)
1831 0 : return;
1832 :
1833 : /*
1834 : * note: in cost_limit, zero also means use value from elsewhere, because
1835 : * zero is not a valid value.
1836 : */
1837 :
1838 786 : if (av_storage_param_cost_limit > 0)
1839 0 : vacuum_cost_limit = av_storage_param_cost_limit;
1840 : else
1841 : {
1842 : int nworkers_for_balance;
1843 :
1844 786 : if (autovacuum_vac_cost_limit > 0)
1845 0 : vacuum_cost_limit = autovacuum_vac_cost_limit;
1846 : else
1847 786 : vacuum_cost_limit = VacuumCostLimit;
1848 :
1849 : /* Only balance limit if no cost-related storage parameters specified */
1850 786 : if (pg_atomic_unlocked_test_flag(&MyWorkerInfo->wi_dobalance))
1851 0 : return;
1852 :
1853 : Assert(vacuum_cost_limit > 0);
1854 :
1855 786 : nworkers_for_balance = pg_atomic_read_u32(&AutoVacuumShmem->av_nworkersForBalance);
1856 :
1857 : /* There is at least 1 autovac worker (this worker) */
1858 786 : if (nworkers_for_balance <= 0)
1859 0 : elog(ERROR, "nworkers_for_balance must be > 0");
1860 :
1861 786 : vacuum_cost_limit = Max(vacuum_cost_limit / nworkers_for_balance, 1);
1862 : }
1863 : }
1864 :
1865 : /*
1866 : * autovac_recalculate_workers_for_balance
1867 : * Recalculate the number of workers to consider, given cost-related
1868 : * storage parameters and the current number of active workers.
1869 : *
1870 : * Caller must hold the AutovacuumLock in at least shared mode to access
1871 : * worker->wi_proc.
1872 : */
1873 : static void
1874 218 : autovac_recalculate_workers_for_balance(void)
1875 : {
1876 : dlist_iter iter;
1877 : int orig_nworkers_for_balance;
1878 218 : int nworkers_for_balance = 0;
1879 :
1880 : Assert(LWLockHeldByMe(AutovacuumLock));
1881 :
1882 218 : orig_nworkers_for_balance =
1883 218 : pg_atomic_read_u32(&AutoVacuumShmem->av_nworkersForBalance);
1884 :
1885 420 : dlist_foreach(iter, &AutoVacuumShmem->av_runningWorkers)
1886 : {
1887 202 : WorkerInfo worker = dlist_container(WorkerInfoData, wi_links, iter.cur);
1888 :
1889 404 : if (worker->wi_proc == NULL ||
1890 202 : pg_atomic_unlocked_test_flag(&worker->wi_dobalance))
1891 0 : continue;
1892 :
1893 202 : nworkers_for_balance++;
1894 : }
1895 :
1896 218 : if (nworkers_for_balance != orig_nworkers_for_balance)
1897 28 : pg_atomic_write_u32(&AutoVacuumShmem->av_nworkersForBalance,
1898 : nworkers_for_balance);
1899 218 : }
1900 :
1901 : /*
1902 : * get_database_list
1903 : * Return a list of all databases found in pg_database.
1904 : *
1905 : * The list and associated data is allocated in the caller's memory context,
1906 : * which is in charge of ensuring that it's properly cleaned up afterwards.
1907 : *
1908 : * Note: this is the only function in which the autovacuum launcher uses a
1909 : * transaction. Although we aren't attached to any particular database and
1910 : * therefore can't access most catalogs, we do have enough infrastructure
1911 : * to do a seqscan on pg_database.
1912 : */
1913 : static List *
1914 750 : get_database_list(void)
1915 : {
1916 750 : List *dblist = NIL;
1917 : Relation rel;
1918 : TableScanDesc scan;
1919 : HeapTuple tup;
1920 : MemoryContext resultcxt;
1921 :
1922 : /* This is the context that we will allocate our output data in */
1923 750 : resultcxt = CurrentMemoryContext;
1924 :
1925 : /*
1926 : * Start a transaction so we can access pg_database, and get a snapshot.
1927 : * We don't have a use for the snapshot itself, but we're interested in
1928 : * the secondary effect that it sets RecentGlobalXmin. (This is critical
1929 : * for anything that reads heap pages, because HOT may decide to prune
1930 : * them even if the process doesn't attempt to modify any tuples.)
1931 : *
1932 : * FIXME: This comment is inaccurate / the code buggy. A snapshot that is
1933 : * not pushed/active does not reliably prevent HOT pruning (->xmin could
1934 : * e.g. be cleared when cache invalidations are processed).
1935 : */
1936 750 : StartTransactionCommand();
1937 750 : (void) GetTransactionSnapshot();
1938 :
1939 750 : rel = table_open(DatabaseRelationId, AccessShareLock);
1940 750 : scan = table_beginscan_catalog(rel, 0, NULL);
1941 :
1942 3334 : while (HeapTupleIsValid(tup = heap_getnext(scan, ForwardScanDirection)))
1943 : {
1944 2584 : Form_pg_database pgdatabase = (Form_pg_database) GETSTRUCT(tup);
1945 : avw_dbase *avdb;
1946 : MemoryContext oldcxt;
1947 :
1948 : /*
1949 : * If database has partially been dropped, we can't, nor need to,
1950 : * vacuum it.
1951 : */
1952 2584 : if (database_is_invalid_form(pgdatabase))
1953 : {
1954 2 : elog(DEBUG2,
1955 : "autovacuum: skipping invalid database \"%s\"",
1956 : NameStr(pgdatabase->datname));
1957 2 : continue;
1958 : }
1959 :
1960 : /*
1961 : * Allocate our results in the caller's context, not the
1962 : * transaction's. We do this inside the loop, and restore the original
1963 : * context at the end, so that leaky things like heap_getnext() are
1964 : * not called in a potentially long-lived context.
1965 : */
1966 2582 : oldcxt = MemoryContextSwitchTo(resultcxt);
1967 :
1968 2582 : avdb = (avw_dbase *) palloc(sizeof(avw_dbase));
1969 :
1970 2582 : avdb->adw_datid = pgdatabase->oid;
1971 2582 : avdb->adw_name = pstrdup(NameStr(pgdatabase->datname));
1972 2582 : avdb->adw_frozenxid = pgdatabase->datfrozenxid;
1973 2582 : avdb->adw_minmulti = pgdatabase->datminmxid;
1974 : /* this gets set later: */
1975 2582 : avdb->adw_entry = NULL;
1976 :
1977 2582 : dblist = lappend(dblist, avdb);
1978 2582 : MemoryContextSwitchTo(oldcxt);
1979 : }
1980 :
1981 750 : table_endscan(scan);
1982 750 : table_close(rel, AccessShareLock);
1983 :
1984 750 : CommitTransactionCommand();
1985 :
1986 : /* Be sure to restore caller's memory context */
1987 750 : MemoryContextSwitchTo(resultcxt);
1988 :
1989 750 : return dblist;
1990 : }
1991 :
1992 : /*
1993 : * Process a database table-by-table
1994 : *
1995 : * Note that CHECK_FOR_INTERRUPTS is supposed to be used in certain spots in
1996 : * order not to ignore shutdown commands for too long.
1997 : */
1998 : static void
1999 16 : do_autovacuum(void)
2000 : {
2001 : Relation classRel;
2002 : HeapTuple tuple;
2003 : TableScanDesc relScan;
2004 : Form_pg_database dbForm;
2005 16 : List *table_oids = NIL;
2006 16 : List *orphan_oids = NIL;
2007 : HASHCTL ctl;
2008 : HTAB *table_toast_map;
2009 : ListCell *volatile cell;
2010 : BufferAccessStrategy bstrategy;
2011 : ScanKeyData key;
2012 : TupleDesc pg_class_desc;
2013 : int effective_multixact_freeze_max_age;
2014 16 : bool did_vacuum = false;
2015 16 : bool found_concurrent_worker = false;
2016 : int i;
2017 :
2018 : /*
2019 : * StartTransactionCommand and CommitTransactionCommand will automatically
2020 : * switch to other contexts. We need this one to keep the list of
2021 : * relations to vacuum/analyze across transactions.
2022 : */
2023 16 : AutovacMemCxt = AllocSetContextCreate(TopMemoryContext,
2024 : "Autovacuum worker",
2025 : ALLOCSET_DEFAULT_SIZES);
2026 16 : MemoryContextSwitchTo(AutovacMemCxt);
2027 :
2028 : /* Start a transaction so our commands have one to play into. */
2029 16 : StartTransactionCommand();
2030 :
2031 : /*
2032 : * Compute the multixact age for which freezing is urgent. This is
2033 : * normally autovacuum_multixact_freeze_max_age, but may be less if we are
2034 : * short of multixact member space.
2035 : */
2036 16 : effective_multixact_freeze_max_age = MultiXactMemberFreezeThreshold();
2037 :
2038 : /*
2039 : * Find the pg_database entry and select the default freeze ages. We use
2040 : * zero in template and nonconnectable databases, else the system-wide
2041 : * default.
2042 : */
2043 16 : tuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(MyDatabaseId));
2044 16 : if (!HeapTupleIsValid(tuple))
2045 0 : elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
2046 16 : dbForm = (Form_pg_database) GETSTRUCT(tuple);
2047 :
2048 16 : if (dbForm->datistemplate || !dbForm->datallowconn)
2049 : {
2050 2 : default_freeze_min_age = 0;
2051 2 : default_freeze_table_age = 0;
2052 2 : default_multixact_freeze_min_age = 0;
2053 2 : default_multixact_freeze_table_age = 0;
2054 : }
2055 : else
2056 : {
2057 14 : default_freeze_min_age = vacuum_freeze_min_age;
2058 14 : default_freeze_table_age = vacuum_freeze_table_age;
2059 14 : default_multixact_freeze_min_age = vacuum_multixact_freeze_min_age;
2060 14 : default_multixact_freeze_table_age = vacuum_multixact_freeze_table_age;
2061 : }
2062 :
2063 16 : ReleaseSysCache(tuple);
2064 :
2065 : /* StartTransactionCommand changed elsewhere */
2066 16 : MemoryContextSwitchTo(AutovacMemCxt);
2067 :
2068 16 : classRel = table_open(RelationRelationId, AccessShareLock);
2069 :
2070 : /* create a copy so we can use it after closing pg_class */
2071 16 : pg_class_desc = CreateTupleDescCopy(RelationGetDescr(classRel));
2072 :
2073 : /* create hash table for toast <-> main relid mapping */
2074 16 : ctl.keysize = sizeof(Oid);
2075 16 : ctl.entrysize = sizeof(av_relation);
2076 :
2077 16 : table_toast_map = hash_create("TOAST to main relid map",
2078 : 100,
2079 : &ctl,
2080 : HASH_ELEM | HASH_BLOBS);
2081 :
2082 : /*
2083 : * Scan pg_class to determine which tables to vacuum.
2084 : *
2085 : * We do this in two passes: on the first one we collect the list of plain
2086 : * relations and materialized views, and on the second one we collect
2087 : * TOAST tables. The reason for doing the second pass is that during it we
2088 : * want to use the main relation's pg_class.reloptions entry if the TOAST
2089 : * table does not have any, and we cannot obtain it unless we know
2090 : * beforehand what's the main table OID.
2091 : *
2092 : * We need to check TOAST tables separately because in cases with short,
2093 : * wide tables there might be proportionally much more activity in the
2094 : * TOAST table than in its parent.
2095 : */
2096 16 : relScan = table_beginscan_catalog(classRel, 0, NULL);
2097 :
2098 : /*
2099 : * On the first pass, we collect main tables to vacuum, and also the main
2100 : * table relid to TOAST relid mapping.
2101 : */
2102 11030 : while ((tuple = heap_getnext(relScan, ForwardScanDirection)) != NULL)
2103 : {
2104 11014 : Form_pg_class classForm = (Form_pg_class) GETSTRUCT(tuple);
2105 : PgStat_StatTabEntry *tabentry;
2106 : AutoVacOpts *relopts;
2107 : Oid relid;
2108 : bool dovacuum;
2109 : bool doanalyze;
2110 : bool wraparound;
2111 :
2112 11014 : if (classForm->relkind != RELKIND_RELATION &&
2113 8276 : classForm->relkind != RELKIND_MATVIEW)
2114 8260 : continue;
2115 :
2116 2768 : relid = classForm->oid;
2117 :
2118 : /*
2119 : * Check if it is a temp table (presumably, of some other backend's).
2120 : * We cannot safely process other backends' temp tables.
2121 : */
2122 2768 : if (classForm->relpersistence == RELPERSISTENCE_TEMP)
2123 : {
2124 : /*
2125 : * We just ignore it if the owning backend is still active and
2126 : * using the temporary schema. Also, for safety, ignore it if the
2127 : * namespace doesn't exist or isn't a temp namespace after all.
2128 : */
2129 14 : if (checkTempNamespaceStatus(classForm->relnamespace) == TEMP_NAMESPACE_IDLE)
2130 : {
2131 : /*
2132 : * The table seems to be orphaned -- although it might be that
2133 : * the owning backend has already deleted it and exited; our
2134 : * pg_class scan snapshot is not necessarily up-to-date
2135 : * anymore, so we could be looking at a committed-dead entry.
2136 : * Remember it so we can try to delete it later.
2137 : */
2138 0 : orphan_oids = lappend_oid(orphan_oids, relid);
2139 : }
2140 14 : continue;
2141 : }
2142 :
2143 : /* Fetch reloptions and the pgstat entry for this table */
2144 2754 : relopts = extract_autovac_opts(tuple, pg_class_desc);
2145 2754 : tabentry = pgstat_fetch_stat_tabentry_ext(classForm->relisshared,
2146 : relid);
2147 :
2148 : /* Check if it needs vacuum or analyze */
2149 2754 : relation_needs_vacanalyze(relid, relopts, classForm, tabentry,
2150 : effective_multixact_freeze_max_age,
2151 : &dovacuum, &doanalyze, &wraparound);
2152 :
2153 : /* Relations that need work are added to table_oids */
2154 2754 : if (dovacuum || doanalyze)
2155 200 : table_oids = lappend_oid(table_oids, relid);
2156 :
2157 : /*
2158 : * Remember TOAST associations for the second pass. Note: we must do
2159 : * this whether or not the table is going to be vacuumed, because we
2160 : * don't automatically vacuum toast tables along the parent table.
2161 : */
2162 2754 : if (OidIsValid(classForm->reltoastrelid))
2163 : {
2164 : av_relation *hentry;
2165 : bool found;
2166 :
2167 2708 : hentry = hash_search(table_toast_map,
2168 1354 : &classForm->reltoastrelid,
2169 : HASH_ENTER, &found);
2170 :
2171 1354 : if (!found)
2172 : {
2173 : /* hash_search already filled in the key */
2174 1354 : hentry->ar_relid = relid;
2175 1354 : hentry->ar_hasrelopts = false;
2176 1354 : if (relopts != NULL)
2177 : {
2178 38 : hentry->ar_hasrelopts = true;
2179 38 : memcpy(&hentry->ar_reloptions, relopts,
2180 : sizeof(AutoVacOpts));
2181 : }
2182 : }
2183 : }
2184 : }
2185 :
2186 16 : table_endscan(relScan);
2187 :
2188 : /* second pass: check TOAST tables */
2189 16 : ScanKeyInit(&key,
2190 : Anum_pg_class_relkind,
2191 : BTEqualStrategyNumber, F_CHAREQ,
2192 : CharGetDatum(RELKIND_TOASTVALUE));
2193 :
2194 16 : relScan = table_beginscan_catalog(classRel, 1, &key);
2195 1370 : while ((tuple = heap_getnext(relScan, ForwardScanDirection)) != NULL)
2196 : {
2197 1354 : Form_pg_class classForm = (Form_pg_class) GETSTRUCT(tuple);
2198 : PgStat_StatTabEntry *tabentry;
2199 : Oid relid;
2200 1354 : AutoVacOpts *relopts = NULL;
2201 : bool dovacuum;
2202 : bool doanalyze;
2203 : bool wraparound;
2204 :
2205 : /*
2206 : * We cannot safely process other backends' temp tables, so skip 'em.
2207 : */
2208 1354 : if (classForm->relpersistence == RELPERSISTENCE_TEMP)
2209 0 : continue;
2210 :
2211 1354 : relid = classForm->oid;
2212 :
2213 : /*
2214 : * fetch reloptions -- if this toast table does not have them, try the
2215 : * main rel
2216 : */
2217 1354 : relopts = extract_autovac_opts(tuple, pg_class_desc);
2218 1354 : if (relopts == NULL)
2219 : {
2220 : av_relation *hentry;
2221 : bool found;
2222 :
2223 1352 : hentry = hash_search(table_toast_map, &relid, HASH_FIND, &found);
2224 1352 : if (found && hentry->ar_hasrelopts)
2225 36 : relopts = &hentry->ar_reloptions;
2226 : }
2227 :
2228 : /* Fetch the pgstat entry for this table */
2229 1354 : tabentry = pgstat_fetch_stat_tabentry_ext(classForm->relisshared,
2230 : relid);
2231 :
2232 1354 : relation_needs_vacanalyze(relid, relopts, classForm, tabentry,
2233 : effective_multixact_freeze_max_age,
2234 : &dovacuum, &doanalyze, &wraparound);
2235 :
2236 : /* ignore analyze for toast tables */
2237 1354 : if (dovacuum)
2238 2 : table_oids = lappend_oid(table_oids, relid);
2239 : }
2240 :
2241 16 : table_endscan(relScan);
2242 16 : table_close(classRel, AccessShareLock);
2243 :
2244 : /*
2245 : * Recheck orphan temporary tables, and if they still seem orphaned, drop
2246 : * them. We'll eat a transaction per dropped table, which might seem
2247 : * excessive, but we should only need to do anything as a result of a
2248 : * previous backend crash, so this should not happen often enough to
2249 : * justify "optimizing". Using separate transactions ensures that we
2250 : * don't bloat the lock table if there are many temp tables to be dropped,
2251 : * and it ensures that we don't lose work if a deletion attempt fails.
2252 : */
2253 16 : foreach(cell, orphan_oids)
2254 : {
2255 0 : Oid relid = lfirst_oid(cell);
2256 : Form_pg_class classForm;
2257 : ObjectAddress object;
2258 :
2259 : /*
2260 : * Check for user-requested abort.
2261 : */
2262 0 : CHECK_FOR_INTERRUPTS();
2263 :
2264 : /*
2265 : * Try to lock the table. If we can't get the lock immediately,
2266 : * somebody else is using (or dropping) the table, so it's not our
2267 : * concern anymore. Having the lock prevents race conditions below.
2268 : */
2269 0 : if (!ConditionalLockRelationOid(relid, AccessExclusiveLock))
2270 0 : continue;
2271 :
2272 : /*
2273 : * Re-fetch the pg_class tuple and re-check whether it still seems to
2274 : * be an orphaned temp table. If it's not there or no longer the same
2275 : * relation, ignore it.
2276 : */
2277 0 : tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
2278 0 : if (!HeapTupleIsValid(tuple))
2279 : {
2280 : /* be sure to drop useless lock so we don't bloat lock table */
2281 0 : UnlockRelationOid(relid, AccessExclusiveLock);
2282 0 : continue;
2283 : }
2284 0 : classForm = (Form_pg_class) GETSTRUCT(tuple);
2285 :
2286 : /*
2287 : * Make all the same tests made in the loop above. In event of OID
2288 : * counter wraparound, the pg_class entry we have now might be
2289 : * completely unrelated to the one we saw before.
2290 : */
2291 0 : if (!((classForm->relkind == RELKIND_RELATION ||
2292 0 : classForm->relkind == RELKIND_MATVIEW) &&
2293 0 : classForm->relpersistence == RELPERSISTENCE_TEMP))
2294 : {
2295 0 : UnlockRelationOid(relid, AccessExclusiveLock);
2296 0 : continue;
2297 : }
2298 :
2299 0 : if (checkTempNamespaceStatus(classForm->relnamespace) != TEMP_NAMESPACE_IDLE)
2300 : {
2301 0 : UnlockRelationOid(relid, AccessExclusiveLock);
2302 0 : continue;
2303 : }
2304 :
2305 : /* OK, let's delete it */
2306 0 : ereport(LOG,
2307 : (errmsg("autovacuum: dropping orphan temp table \"%s.%s.%s\"",
2308 : get_database_name(MyDatabaseId),
2309 : get_namespace_name(classForm->relnamespace),
2310 : NameStr(classForm->relname))));
2311 :
2312 0 : object.classId = RelationRelationId;
2313 0 : object.objectId = relid;
2314 0 : object.objectSubId = 0;
2315 0 : performDeletion(&object, DROP_CASCADE,
2316 : PERFORM_DELETION_INTERNAL |
2317 : PERFORM_DELETION_QUIETLY |
2318 : PERFORM_DELETION_SKIP_EXTENSIONS);
2319 :
2320 : /*
2321 : * To commit the deletion, end current transaction and start a new
2322 : * one. Note this also releases the lock we took.
2323 : */
2324 0 : CommitTransactionCommand();
2325 0 : StartTransactionCommand();
2326 :
2327 : /* StartTransactionCommand changed current memory context */
2328 0 : MemoryContextSwitchTo(AutovacMemCxt);
2329 : }
2330 :
2331 : /*
2332 : * Optionally, create a buffer access strategy object for VACUUM to use.
2333 : * We use the same BufferAccessStrategy object for all tables VACUUMed by
2334 : * this worker to prevent autovacuum from blowing out shared buffers.
2335 : *
2336 : * VacuumBufferUsageLimit being set to 0 results in
2337 : * GetAccessStrategyWithSize returning NULL, effectively meaning we can
2338 : * use up to all of shared buffers.
2339 : *
2340 : * If we later enter failsafe mode on any of the tables being vacuumed, we
2341 : * will cease use of the BufferAccessStrategy only for that table.
2342 : *
2343 : * XXX should we consider adding code to adjust the size of this if
2344 : * VacuumBufferUsageLimit changes?
2345 : */
2346 16 : bstrategy = GetAccessStrategyWithSize(BAS_VACUUM, VacuumBufferUsageLimit);
2347 :
2348 : /*
2349 : * create a memory context to act as fake PortalContext, so that the
2350 : * contexts created in the vacuum code are cleaned up for each table.
2351 : */
2352 16 : PortalContext = AllocSetContextCreate(AutovacMemCxt,
2353 : "Autovacuum Portal",
2354 : ALLOCSET_DEFAULT_SIZES);
2355 :
2356 : /*
2357 : * Perform operations on collected tables.
2358 : */
2359 218 : foreach(cell, table_oids)
2360 : {
2361 202 : Oid relid = lfirst_oid(cell);
2362 : HeapTuple classTup;
2363 : autovac_table *tab;
2364 : bool isshared;
2365 : bool skipit;
2366 : dlist_iter iter;
2367 :
2368 202 : CHECK_FOR_INTERRUPTS();
2369 :
2370 : /*
2371 : * Check for config changes before processing each collected table.
2372 : */
2373 202 : if (ConfigReloadPending)
2374 : {
2375 0 : ConfigReloadPending = false;
2376 0 : ProcessConfigFile(PGC_SIGHUP);
2377 :
2378 : /*
2379 : * You might be tempted to bail out if we see autovacuum is now
2380 : * disabled. Must resist that temptation -- this might be a
2381 : * for-wraparound emergency worker, in which case that would be
2382 : * entirely inappropriate.
2383 : */
2384 : }
2385 :
2386 : /*
2387 : * Find out whether the table is shared or not. (It's slightly
2388 : * annoying to fetch the syscache entry just for this, but in typical
2389 : * cases it adds little cost because table_recheck_autovac would
2390 : * refetch the entry anyway. We could buy that back by copying the
2391 : * tuple here and passing it to table_recheck_autovac, but that
2392 : * increases the odds of that function working with stale data.)
2393 : */
2394 202 : classTup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
2395 202 : if (!HeapTupleIsValid(classTup))
2396 0 : continue; /* somebody deleted the rel, forget it */
2397 202 : isshared = ((Form_pg_class) GETSTRUCT(classTup))->relisshared;
2398 202 : ReleaseSysCache(classTup);
2399 :
2400 : /*
2401 : * Hold schedule lock from here until we've claimed the table. We
2402 : * also need the AutovacuumLock to walk the worker array, but that one
2403 : * can just be a shared lock.
2404 : */
2405 202 : LWLockAcquire(AutovacuumScheduleLock, LW_EXCLUSIVE);
2406 202 : LWLockAcquire(AutovacuumLock, LW_SHARED);
2407 :
2408 : /*
2409 : * Check whether the table is being vacuumed concurrently by another
2410 : * worker.
2411 : */
2412 202 : skipit = false;
2413 404 : dlist_foreach(iter, &AutoVacuumShmem->av_runningWorkers)
2414 : {
2415 202 : WorkerInfo worker = dlist_container(WorkerInfoData, wi_links, iter.cur);
2416 :
2417 : /* ignore myself */
2418 202 : if (worker == MyWorkerInfo)
2419 202 : continue;
2420 :
2421 : /* ignore workers in other databases (unless table is shared) */
2422 0 : if (!worker->wi_sharedrel && worker->wi_dboid != MyDatabaseId)
2423 0 : continue;
2424 :
2425 0 : if (worker->wi_tableoid == relid)
2426 : {
2427 0 : skipit = true;
2428 0 : found_concurrent_worker = true;
2429 0 : break;
2430 : }
2431 : }
2432 202 : LWLockRelease(AutovacuumLock);
2433 202 : if (skipit)
2434 : {
2435 0 : LWLockRelease(AutovacuumScheduleLock);
2436 0 : continue;
2437 : }
2438 :
2439 : /*
2440 : * Store the table's OID in shared memory before releasing the
2441 : * schedule lock, so that other workers don't try to vacuum it
2442 : * concurrently. (We claim it here so as not to hold
2443 : * AutovacuumScheduleLock while rechecking the stats.)
2444 : */
2445 202 : MyWorkerInfo->wi_tableoid = relid;
2446 202 : MyWorkerInfo->wi_sharedrel = isshared;
2447 202 : LWLockRelease(AutovacuumScheduleLock);
2448 :
2449 : /*
2450 : * Check whether pgstat data still says we need to vacuum this table.
2451 : * It could have changed if something else processed the table while
2452 : * we weren't looking. This doesn't entirely close the race condition,
2453 : * but it is very small.
2454 : */
2455 202 : MemoryContextSwitchTo(AutovacMemCxt);
2456 202 : tab = table_recheck_autovac(relid, table_toast_map, pg_class_desc,
2457 : effective_multixact_freeze_max_age);
2458 202 : if (tab == NULL)
2459 : {
2460 : /* someone else vacuumed the table, or it went away */
2461 0 : LWLockAcquire(AutovacuumScheduleLock, LW_EXCLUSIVE);
2462 0 : MyWorkerInfo->wi_tableoid = InvalidOid;
2463 0 : MyWorkerInfo->wi_sharedrel = false;
2464 0 : LWLockRelease(AutovacuumScheduleLock);
2465 0 : continue;
2466 : }
2467 :
2468 : /*
2469 : * Save the cost-related storage parameter values in global variables
2470 : * for reference when updating vacuum_cost_delay and vacuum_cost_limit
2471 : * during vacuuming this table.
2472 : */
2473 202 : av_storage_param_cost_delay = tab->at_storage_param_vac_cost_delay;
2474 202 : av_storage_param_cost_limit = tab->at_storage_param_vac_cost_limit;
2475 :
2476 : /*
2477 : * We only expect this worker to ever set the flag, so don't bother
2478 : * checking the return value. We shouldn't have to retry.
2479 : */
2480 202 : if (tab->at_dobalance)
2481 202 : pg_atomic_test_set_flag(&MyWorkerInfo->wi_dobalance);
2482 : else
2483 0 : pg_atomic_clear_flag(&MyWorkerInfo->wi_dobalance);
2484 :
2485 202 : LWLockAcquire(AutovacuumLock, LW_SHARED);
2486 202 : autovac_recalculate_workers_for_balance();
2487 202 : LWLockRelease(AutovacuumLock);
2488 :
2489 : /*
2490 : * We wait until this point to update cost delay and cost limit
2491 : * values, even though we reloaded the configuration file above, so
2492 : * that we can take into account the cost-related storage parameters.
2493 : */
2494 202 : VacuumUpdateCosts();
2495 :
2496 :
2497 : /* clean up memory before each iteration */
2498 202 : MemoryContextReset(PortalContext);
2499 :
2500 : /*
2501 : * Save the relation name for a possible error message, to avoid a
2502 : * catalog lookup in case of an error. If any of these return NULL,
2503 : * then the relation has been dropped since last we checked; skip it.
2504 : * Note: they must live in a long-lived memory context because we call
2505 : * vacuum and analyze in different transactions.
2506 : */
2507 :
2508 202 : tab->at_relname = get_rel_name(tab->at_relid);
2509 202 : tab->at_nspname = get_namespace_name(get_rel_namespace(tab->at_relid));
2510 202 : tab->at_datname = get_database_name(MyDatabaseId);
2511 202 : if (!tab->at_relname || !tab->at_nspname || !tab->at_datname)
2512 0 : goto deleted;
2513 :
2514 : /*
2515 : * We will abort vacuuming the current table if something errors out,
2516 : * and continue with the next one in schedule; in particular, this
2517 : * happens if we are interrupted with SIGINT.
2518 : */
2519 202 : PG_TRY();
2520 : {
2521 : /* Use PortalContext for any per-table allocations */
2522 202 : MemoryContextSwitchTo(PortalContext);
2523 :
2524 : /* have at it */
2525 202 : autovacuum_do_vac_analyze(tab, bstrategy);
2526 :
2527 : /*
2528 : * Clear a possible query-cancel signal, to avoid a late reaction
2529 : * to an automatically-sent signal because of vacuuming the
2530 : * current table (we're done with it, so it would make no sense to
2531 : * cancel at this point.)
2532 : */
2533 202 : QueryCancelPending = false;
2534 : }
2535 0 : PG_CATCH();
2536 : {
2537 : /*
2538 : * Abort the transaction, start a new one, and proceed with the
2539 : * next table in our list.
2540 : */
2541 0 : HOLD_INTERRUPTS();
2542 0 : if (tab->at_params.options & VACOPT_VACUUM)
2543 0 : errcontext("automatic vacuum of table \"%s.%s.%s\"",
2544 : tab->at_datname, tab->at_nspname, tab->at_relname);
2545 : else
2546 0 : errcontext("automatic analyze of table \"%s.%s.%s\"",
2547 : tab->at_datname, tab->at_nspname, tab->at_relname);
2548 0 : EmitErrorReport();
2549 :
2550 : /* this resets ProcGlobal->statusFlags[i] too */
2551 0 : AbortOutOfAnyTransaction();
2552 0 : FlushErrorState();
2553 0 : MemoryContextReset(PortalContext);
2554 :
2555 : /* restart our transaction for the following operations */
2556 0 : StartTransactionCommand();
2557 0 : RESUME_INTERRUPTS();
2558 : }
2559 202 : PG_END_TRY();
2560 :
2561 : /* Make sure we're back in AutovacMemCxt */
2562 202 : MemoryContextSwitchTo(AutovacMemCxt);
2563 :
2564 202 : did_vacuum = true;
2565 :
2566 : /* ProcGlobal->statusFlags[i] are reset at the next end of xact */
2567 :
2568 : /* be tidy */
2569 202 : deleted:
2570 202 : if (tab->at_datname != NULL)
2571 202 : pfree(tab->at_datname);
2572 202 : if (tab->at_nspname != NULL)
2573 202 : pfree(tab->at_nspname);
2574 202 : if (tab->at_relname != NULL)
2575 202 : pfree(tab->at_relname);
2576 202 : pfree(tab);
2577 :
2578 : /*
2579 : * Remove my info from shared memory. We set wi_dobalance on the
2580 : * assumption that we are more likely than not to vacuum a table with
2581 : * no cost-related storage parameters next, so we want to claim our
2582 : * share of I/O as soon as possible to avoid thrashing the global
2583 : * balance.
2584 : */
2585 202 : LWLockAcquire(AutovacuumScheduleLock, LW_EXCLUSIVE);
2586 202 : MyWorkerInfo->wi_tableoid = InvalidOid;
2587 202 : MyWorkerInfo->wi_sharedrel = false;
2588 202 : LWLockRelease(AutovacuumScheduleLock);
2589 202 : pg_atomic_test_set_flag(&MyWorkerInfo->wi_dobalance);
2590 : }
2591 :
2592 : /*
2593 : * Perform additional work items, as requested by backends.
2594 : */
2595 16 : LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
2596 4112 : for (i = 0; i < NUM_WORKITEMS; i++)
2597 : {
2598 4096 : AutoVacuumWorkItem *workitem = &AutoVacuumShmem->av_workItems[i];
2599 :
2600 4096 : if (!workitem->avw_used)
2601 4090 : continue;
2602 6 : if (workitem->avw_active)
2603 0 : continue;
2604 6 : if (workitem->avw_database != MyDatabaseId)
2605 0 : continue;
2606 :
2607 : /* claim this one, and release lock while performing it */
2608 6 : workitem->avw_active = true;
2609 6 : LWLockRelease(AutovacuumLock);
2610 :
2611 6 : perform_work_item(workitem);
2612 :
2613 : /*
2614 : * Check for config changes before acquiring lock for further jobs.
2615 : */
2616 6 : CHECK_FOR_INTERRUPTS();
2617 6 : if (ConfigReloadPending)
2618 : {
2619 0 : ConfigReloadPending = false;
2620 0 : ProcessConfigFile(PGC_SIGHUP);
2621 0 : VacuumUpdateCosts();
2622 : }
2623 :
2624 6 : LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
2625 :
2626 : /* and mark it done */
2627 6 : workitem->avw_active = false;
2628 6 : workitem->avw_used = false;
2629 : }
2630 16 : LWLockRelease(AutovacuumLock);
2631 :
2632 : /*
2633 : * We leak table_toast_map here (among other things), but since we're
2634 : * going away soon, it's not a problem.
2635 : */
2636 :
2637 : /*
2638 : * Update pg_database.datfrozenxid, and truncate pg_xact if possible. We
2639 : * only need to do this once, not after each table.
2640 : *
2641 : * Even if we didn't vacuum anything, it may still be important to do
2642 : * this, because one indirect effect of vac_update_datfrozenxid() is to
2643 : * update ShmemVariableCache->xidVacLimit. That might need to be done
2644 : * even if we haven't vacuumed anything, because relations with older
2645 : * relfrozenxid values or other databases with older datfrozenxid values
2646 : * might have been dropped, allowing xidVacLimit to advance.
2647 : *
2648 : * However, it's also important not to do this blindly in all cases,
2649 : * because when autovacuum=off this will restart the autovacuum launcher.
2650 : * If we're not careful, an infinite loop can result, where workers find
2651 : * no work to do and restart the launcher, which starts another worker in
2652 : * the same database that finds no work to do. To prevent that, we skip
2653 : * this if (1) we found no work to do and (2) we skipped at least one
2654 : * table due to concurrent autovacuum activity. In that case, the other
2655 : * worker has already done it, or will do so when it finishes.
2656 : */
2657 16 : if (did_vacuum || !found_concurrent_worker)
2658 16 : vac_update_datfrozenxid();
2659 :
2660 : /* Finally close out the last transaction. */
2661 16 : CommitTransactionCommand();
2662 16 : }
2663 :
2664 : /*
2665 : * Execute a previously registered work item.
2666 : */
2667 : static void
2668 6 : perform_work_item(AutoVacuumWorkItem *workitem)
2669 : {
2670 6 : char *cur_datname = NULL;
2671 6 : char *cur_nspname = NULL;
2672 6 : char *cur_relname = NULL;
2673 :
2674 : /*
2675 : * Note we do not store table info in MyWorkerInfo, since this is not
2676 : * vacuuming proper.
2677 : */
2678 :
2679 : /*
2680 : * Save the relation name for a possible error message, to avoid a catalog
2681 : * lookup in case of an error. If any of these return NULL, then the
2682 : * relation has been dropped since last we checked; skip it.
2683 : */
2684 : Assert(CurrentMemoryContext == AutovacMemCxt);
2685 :
2686 6 : cur_relname = get_rel_name(workitem->avw_relation);
2687 6 : cur_nspname = get_namespace_name(get_rel_namespace(workitem->avw_relation));
2688 6 : cur_datname = get_database_name(MyDatabaseId);
2689 6 : if (!cur_relname || !cur_nspname || !cur_datname)
2690 0 : goto deleted2;
2691 :
2692 6 : autovac_report_workitem(workitem, cur_nspname, cur_relname);
2693 :
2694 : /* clean up memory before each work item */
2695 6 : MemoryContextReset(PortalContext);
2696 :
2697 : /*
2698 : * We will abort the current work item if something errors out, and
2699 : * continue with the next one; in particular, this happens if we are
2700 : * interrupted with SIGINT. Note that this means that the work item list
2701 : * can be lossy.
2702 : */
2703 6 : PG_TRY();
2704 : {
2705 : /* Use PortalContext for any per-work-item allocations */
2706 6 : MemoryContextSwitchTo(PortalContext);
2707 :
2708 : /*
2709 : * Have at it. Functions called here are responsible for any required
2710 : * user switch and sandbox.
2711 : */
2712 6 : switch (workitem->avw_type)
2713 : {
2714 6 : case AVW_BRINSummarizeRange:
2715 6 : DirectFunctionCall2(brin_summarize_range,
2716 : ObjectIdGetDatum(workitem->avw_relation),
2717 : Int64GetDatum((int64) workitem->avw_blockNumber));
2718 6 : break;
2719 0 : default:
2720 0 : elog(WARNING, "unrecognized work item found: type %d",
2721 : workitem->avw_type);
2722 0 : break;
2723 : }
2724 :
2725 : /*
2726 : * Clear a possible query-cancel signal, to avoid a late reaction to
2727 : * an automatically-sent signal because of vacuuming the current table
2728 : * (we're done with it, so it would make no sense to cancel at this
2729 : * point.)
2730 : */
2731 6 : QueryCancelPending = false;
2732 : }
2733 0 : PG_CATCH();
2734 : {
2735 : /*
2736 : * Abort the transaction, start a new one, and proceed with the next
2737 : * table in our list.
2738 : */
2739 0 : HOLD_INTERRUPTS();
2740 0 : errcontext("processing work entry for relation \"%s.%s.%s\"",
2741 : cur_datname, cur_nspname, cur_relname);
2742 0 : EmitErrorReport();
2743 :
2744 : /* this resets ProcGlobal->statusFlags[i] too */
2745 0 : AbortOutOfAnyTransaction();
2746 0 : FlushErrorState();
2747 0 : MemoryContextReset(PortalContext);
2748 :
2749 : /* restart our transaction for the following operations */
2750 0 : StartTransactionCommand();
2751 0 : RESUME_INTERRUPTS();
2752 : }
2753 6 : PG_END_TRY();
2754 :
2755 : /* Make sure we're back in AutovacMemCxt */
2756 6 : MemoryContextSwitchTo(AutovacMemCxt);
2757 :
2758 : /* We intentionally do not set did_vacuum here */
2759 :
2760 : /* be tidy */
2761 6 : deleted2:
2762 6 : if (cur_datname)
2763 6 : pfree(cur_datname);
2764 6 : if (cur_nspname)
2765 6 : pfree(cur_nspname);
2766 6 : if (cur_relname)
2767 6 : pfree(cur_relname);
2768 6 : }
2769 :
2770 : /*
2771 : * extract_autovac_opts
2772 : *
2773 : * Given a relation's pg_class tuple, return the AutoVacOpts portion of
2774 : * reloptions, if set; otherwise, return NULL.
2775 : *
2776 : * Note: callers do not have a relation lock on the table at this point,
2777 : * so the table could have been dropped, and its catalog rows gone, after
2778 : * we acquired the pg_class row. If pg_class had a TOAST table, this would
2779 : * be a risk; fortunately, it doesn't.
2780 : */
2781 : static AutoVacOpts *
2782 4310 : extract_autovac_opts(HeapTuple tup, TupleDesc pg_class_desc)
2783 : {
2784 : bytea *relopts;
2785 : AutoVacOpts *av;
2786 :
2787 : Assert(((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_RELATION ||
2788 : ((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_MATVIEW ||
2789 : ((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_TOASTVALUE);
2790 :
2791 4310 : relopts = extractRelOptions(tup, pg_class_desc, NULL);
2792 4310 : if (relopts == NULL)
2793 4232 : return NULL;
2794 :
2795 78 : av = palloc(sizeof(AutoVacOpts));
2796 78 : memcpy(av, &(((StdRdOptions *) relopts)->autovacuum), sizeof(AutoVacOpts));
2797 78 : pfree(relopts);
2798 :
2799 78 : return av;
2800 : }
2801 :
2802 :
2803 : /*
2804 : * table_recheck_autovac
2805 : *
2806 : * Recheck whether a table still needs vacuum or analyze. Return value is a
2807 : * valid autovac_table pointer if it does, NULL otherwise.
2808 : *
2809 : * Note that the returned autovac_table does not have the name fields set.
2810 : */
2811 : static autovac_table *
2812 202 : table_recheck_autovac(Oid relid, HTAB *table_toast_map,
2813 : TupleDesc pg_class_desc,
2814 : int effective_multixact_freeze_max_age)
2815 : {
2816 : Form_pg_class classForm;
2817 : HeapTuple classTup;
2818 : bool dovacuum;
2819 : bool doanalyze;
2820 202 : autovac_table *tab = NULL;
2821 : bool wraparound;
2822 : AutoVacOpts *avopts;
2823 :
2824 : /* fetch the relation's relcache entry */
2825 202 : classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
2826 202 : if (!HeapTupleIsValid(classTup))
2827 0 : return NULL;
2828 202 : classForm = (Form_pg_class) GETSTRUCT(classTup);
2829 :
2830 : /*
2831 : * Get the applicable reloptions. If it is a TOAST table, try to get the
2832 : * main table reloptions if the toast table itself doesn't have.
2833 : */
2834 202 : avopts = extract_autovac_opts(classTup, pg_class_desc);
2835 202 : if (classForm->relkind == RELKIND_TOASTVALUE &&
2836 2 : avopts == NULL && table_toast_map != NULL)
2837 : {
2838 : av_relation *hentry;
2839 : bool found;
2840 :
2841 2 : hentry = hash_search(table_toast_map, &relid, HASH_FIND, &found);
2842 2 : if (found && hentry->ar_hasrelopts)
2843 0 : avopts = &hentry->ar_reloptions;
2844 : }
2845 :
2846 202 : recheck_relation_needs_vacanalyze(relid, avopts, classForm,
2847 : effective_multixact_freeze_max_age,
2848 : &dovacuum, &doanalyze, &wraparound);
2849 :
2850 : /* OK, it needs something done */
2851 202 : if (doanalyze || dovacuum)
2852 : {
2853 : int freeze_min_age;
2854 : int freeze_table_age;
2855 : int multixact_freeze_min_age;
2856 : int multixact_freeze_table_age;
2857 : int log_min_duration;
2858 :
2859 : /*
2860 : * Calculate the vacuum cost parameters and the freeze ages. If there
2861 : * are options set in pg_class.reloptions, use them; in the case of a
2862 : * toast table, try the main table too. Otherwise use the GUC
2863 : * defaults, autovacuum's own first and plain vacuum second.
2864 : */
2865 :
2866 : /* -1 in autovac setting means use log_autovacuum_min_duration */
2867 6 : log_min_duration = (avopts && avopts->log_min_duration >= 0)
2868 : ? avopts->log_min_duration
2869 208 : : Log_autovacuum_min_duration;
2870 :
2871 : /* these do not have autovacuum-specific settings */
2872 6 : freeze_min_age = (avopts && avopts->freeze_min_age >= 0)
2873 : ? avopts->freeze_min_age
2874 208 : : default_freeze_min_age;
2875 :
2876 6 : freeze_table_age = (avopts && avopts->freeze_table_age >= 0)
2877 : ? avopts->freeze_table_age
2878 208 : : default_freeze_table_age;
2879 :
2880 208 : multixact_freeze_min_age = (avopts &&
2881 6 : avopts->multixact_freeze_min_age >= 0)
2882 : ? avopts->multixact_freeze_min_age
2883 208 : : default_multixact_freeze_min_age;
2884 :
2885 208 : multixact_freeze_table_age = (avopts &&
2886 6 : avopts->multixact_freeze_table_age >= 0)
2887 : ? avopts->multixact_freeze_table_age
2888 208 : : default_multixact_freeze_table_age;
2889 :
2890 202 : tab = palloc(sizeof(autovac_table));
2891 202 : tab->at_relid = relid;
2892 202 : tab->at_sharedrel = classForm->relisshared;
2893 :
2894 : /*
2895 : * Select VACUUM options. Note we don't say VACOPT_PROCESS_TOAST, so
2896 : * that vacuum() skips toast relations. Also note we tell vacuum() to
2897 : * skip vac_update_datfrozenxid(); we'll do that separately.
2898 : */
2899 202 : tab->at_params.options =
2900 202 : (dovacuum ? (VACOPT_VACUUM |
2901 : VACOPT_PROCESS_MAIN |
2902 202 : VACOPT_SKIP_DATABASE_STATS) : 0) |
2903 202 : (doanalyze ? VACOPT_ANALYZE : 0) |
2904 202 : (!wraparound ? VACOPT_SKIP_LOCKED : 0);
2905 :
2906 : /*
2907 : * index_cleanup and truncate are unspecified at first in autovacuum.
2908 : * They will be filled in with usable values using their reloptions
2909 : * (or reloption defaults) later.
2910 : */
2911 202 : tab->at_params.index_cleanup = VACOPTVALUE_UNSPECIFIED;
2912 202 : tab->at_params.truncate = VACOPTVALUE_UNSPECIFIED;
2913 : /* As of now, we don't support parallel vacuum for autovacuum */
2914 202 : tab->at_params.nworkers = -1;
2915 202 : tab->at_params.freeze_min_age = freeze_min_age;
2916 202 : tab->at_params.freeze_table_age = freeze_table_age;
2917 202 : tab->at_params.multixact_freeze_min_age = multixact_freeze_min_age;
2918 202 : tab->at_params.multixact_freeze_table_age = multixact_freeze_table_age;
2919 202 : tab->at_params.is_wraparound = wraparound;
2920 202 : tab->at_params.log_min_duration = log_min_duration;
2921 202 : tab->at_storage_param_vac_cost_limit = avopts ?
2922 202 : avopts->vacuum_cost_limit : 0;
2923 202 : tab->at_storage_param_vac_cost_delay = avopts ?
2924 202 : avopts->vacuum_cost_delay : -1;
2925 202 : tab->at_relname = NULL;
2926 202 : tab->at_nspname = NULL;
2927 202 : tab->at_datname = NULL;
2928 :
2929 : /*
2930 : * If any of the cost delay parameters has been set individually for
2931 : * this table, disable the balancing algorithm.
2932 : */
2933 202 : tab->at_dobalance =
2934 208 : !(avopts && (avopts->vacuum_cost_limit > 0 ||
2935 6 : avopts->vacuum_cost_delay >= 0));
2936 : }
2937 :
2938 202 : heap_freetuple(classTup);
2939 202 : return tab;
2940 : }
2941 :
2942 : /*
2943 : * recheck_relation_needs_vacanalyze
2944 : *
2945 : * Subroutine for table_recheck_autovac.
2946 : *
2947 : * Fetch the pgstat of a relation and recheck whether a relation
2948 : * needs to be vacuumed or analyzed.
2949 : */
2950 : static void
2951 202 : recheck_relation_needs_vacanalyze(Oid relid,
2952 : AutoVacOpts *avopts,
2953 : Form_pg_class classForm,
2954 : int effective_multixact_freeze_max_age,
2955 : bool *dovacuum,
2956 : bool *doanalyze,
2957 : bool *wraparound)
2958 : {
2959 : PgStat_StatTabEntry *tabentry;
2960 :
2961 : /* fetch the pgstat table entry */
2962 202 : tabentry = pgstat_fetch_stat_tabentry_ext(classForm->relisshared,
2963 : relid);
2964 :
2965 202 : relation_needs_vacanalyze(relid, avopts, classForm, tabentry,
2966 : effective_multixact_freeze_max_age,
2967 : dovacuum, doanalyze, wraparound);
2968 :
2969 : /* ignore ANALYZE for toast tables */
2970 202 : if (classForm->relkind == RELKIND_TOASTVALUE)
2971 2 : *doanalyze = false;
2972 202 : }
2973 :
2974 : /*
2975 : * relation_needs_vacanalyze
2976 : *
2977 : * Check whether a relation needs to be vacuumed or analyzed; return each into
2978 : * "dovacuum" and "doanalyze", respectively. Also return whether the vacuum is
2979 : * being forced because of Xid or multixact wraparound.
2980 : *
2981 : * relopts is a pointer to the AutoVacOpts options (either for itself in the
2982 : * case of a plain table, or for either itself or its parent table in the case
2983 : * of a TOAST table), NULL if none; tabentry is the pgstats entry, which can be
2984 : * NULL.
2985 : *
2986 : * A table needs to be vacuumed if the number of dead tuples exceeds a
2987 : * threshold. This threshold is calculated as
2988 : *
2989 : * threshold = vac_base_thresh + vac_scale_factor * reltuples
2990 : *
2991 : * For analyze, the analysis done is that the number of tuples inserted,
2992 : * deleted and updated since the last analyze exceeds a threshold calculated
2993 : * in the same fashion as above. Note that the cumulative stats system stores
2994 : * the number of tuples (both live and dead) that there were as of the last
2995 : * analyze. This is asymmetric to the VACUUM case.
2996 : *
2997 : * We also force vacuum if the table's relfrozenxid is more than freeze_max_age
2998 : * transactions back, and if its relminmxid is more than
2999 : * multixact_freeze_max_age multixacts back.
3000 : *
3001 : * A table whose autovacuum_enabled option is false is
3002 : * automatically skipped (unless we have to vacuum it due to freeze_max_age).
3003 : * Thus autovacuum can be disabled for specific tables. Also, when the cumulative
3004 : * stats system does not have data about a table, it will be skipped.
3005 : *
3006 : * A table whose vac_base_thresh value is < 0 takes the base value from the
3007 : * autovacuum_vacuum_threshold GUC variable. Similarly, a vac_scale_factor
3008 : * value < 0 is substituted with the value of
3009 : * autovacuum_vacuum_scale_factor GUC variable. Ditto for analyze.
3010 : */
3011 : static void
3012 4310 : relation_needs_vacanalyze(Oid relid,
3013 : AutoVacOpts *relopts,
3014 : Form_pg_class classForm,
3015 : PgStat_StatTabEntry *tabentry,
3016 : int effective_multixact_freeze_max_age,
3017 : /* output params below */
3018 : bool *dovacuum,
3019 : bool *doanalyze,
3020 : bool *wraparound)
3021 : {
3022 : bool force_vacuum;
3023 : bool av_enabled;
3024 : float4 reltuples; /* pg_class.reltuples */
3025 :
3026 : /* constants from reloptions or GUC variables */
3027 : int vac_base_thresh,
3028 : vac_ins_base_thresh,
3029 : anl_base_thresh;
3030 : float4 vac_scale_factor,
3031 : vac_ins_scale_factor,
3032 : anl_scale_factor;
3033 :
3034 : /* thresholds calculated from above constants */
3035 : float4 vacthresh,
3036 : vacinsthresh,
3037 : anlthresh;
3038 :
3039 : /* number of vacuum (resp. analyze) tuples at this time */
3040 : float4 vactuples,
3041 : instuples,
3042 : anltuples;
3043 :
3044 : /* freeze parameters */
3045 : int freeze_max_age;
3046 : int multixact_freeze_max_age;
3047 : TransactionId xidForceLimit;
3048 : MultiXactId multiForceLimit;
3049 :
3050 : Assert(classForm != NULL);
3051 : Assert(OidIsValid(relid));
3052 :
3053 : /*
3054 : * Determine vacuum/analyze equation parameters. We have two possible
3055 : * sources: the passed reloptions (which could be a main table or a toast
3056 : * table), or the autovacuum GUC variables.
3057 : */
3058 :
3059 : /* -1 in autovac setting means use plain vacuum_scale_factor */
3060 114 : vac_scale_factor = (relopts && relopts->vacuum_scale_factor >= 0)
3061 0 : ? relopts->vacuum_scale_factor
3062 4424 : : autovacuum_vac_scale;
3063 :
3064 114 : vac_base_thresh = (relopts && relopts->vacuum_threshold >= 0)
3065 : ? relopts->vacuum_threshold
3066 4424 : : autovacuum_vac_thresh;
3067 :
3068 114 : vac_ins_scale_factor = (relopts && relopts->vacuum_ins_scale_factor >= 0)
3069 0 : ? relopts->vacuum_ins_scale_factor
3070 4424 : : autovacuum_vac_ins_scale;
3071 :
3072 : /* -1 is used to disable insert vacuums */
3073 114 : vac_ins_base_thresh = (relopts && relopts->vacuum_ins_threshold >= -1)
3074 : ? relopts->vacuum_ins_threshold
3075 4424 : : autovacuum_vac_ins_thresh;
3076 :
3077 114 : anl_scale_factor = (relopts && relopts->analyze_scale_factor >= 0)
3078 0 : ? relopts->analyze_scale_factor
3079 4424 : : autovacuum_anl_scale;
3080 :
3081 114 : anl_base_thresh = (relopts && relopts->analyze_threshold >= 0)
3082 : ? relopts->analyze_threshold
3083 4424 : : autovacuum_anl_thresh;
3084 :
3085 114 : freeze_max_age = (relopts && relopts->freeze_max_age >= 0)
3086 0 : ? Min(relopts->freeze_max_age, autovacuum_freeze_max_age)
3087 4424 : : autovacuum_freeze_max_age;
3088 :
3089 114 : multixact_freeze_max_age = (relopts && relopts->multixact_freeze_max_age >= 0)
3090 0 : ? Min(relopts->multixact_freeze_max_age, effective_multixact_freeze_max_age)
3091 4424 : : effective_multixact_freeze_max_age;
3092 :
3093 4310 : av_enabled = (relopts ? relopts->enabled : true);
3094 :
3095 : /* Force vacuum if table is at risk of wraparound */
3096 4310 : xidForceLimit = recentXid - freeze_max_age;
3097 4310 : if (xidForceLimit < FirstNormalTransactionId)
3098 0 : xidForceLimit -= FirstNormalTransactionId;
3099 8620 : force_vacuum = (TransactionIdIsNormal(classForm->relfrozenxid) &&
3100 4310 : TransactionIdPrecedes(classForm->relfrozenxid,
3101 : xidForceLimit));
3102 4310 : if (!force_vacuum)
3103 : {
3104 4310 : multiForceLimit = recentMulti - multixact_freeze_max_age;
3105 4310 : if (multiForceLimit < FirstMultiXactId)
3106 0 : multiForceLimit -= FirstMultiXactId;
3107 8620 : force_vacuum = MultiXactIdIsValid(classForm->relminmxid) &&
3108 4310 : MultiXactIdPrecedes(classForm->relminmxid, multiForceLimit);
3109 : }
3110 4310 : *wraparound = force_vacuum;
3111 :
3112 : /* User disabled it in pg_class.reloptions? (But ignore if at risk) */
3113 4310 : if (!av_enabled && !force_vacuum)
3114 : {
3115 78 : *doanalyze = false;
3116 78 : *dovacuum = false;
3117 78 : return;
3118 : }
3119 :
3120 : /*
3121 : * If we found stats for the table, and autovacuum is currently enabled,
3122 : * make a threshold-based decision whether to vacuum and/or analyze. If
3123 : * autovacuum is currently disabled, we must be here for anti-wraparound
3124 : * vacuuming only, so don't vacuum (or analyze) anything that's not being
3125 : * forced.
3126 : */
3127 4232 : if (PointerIsValid(tabentry) && AutoVacuumingActive())
3128 : {
3129 3368 : reltuples = classForm->reltuples;
3130 3368 : vactuples = tabentry->dead_tuples;
3131 3368 : instuples = tabentry->ins_since_vacuum;
3132 3368 : anltuples = tabentry->mod_since_analyze;
3133 :
3134 : /* If the table hasn't yet been vacuumed, take reltuples as zero */
3135 3368 : if (reltuples < 0)
3136 1140 : reltuples = 0;
3137 :
3138 3368 : vacthresh = (float4) vac_base_thresh + vac_scale_factor * reltuples;
3139 3368 : vacinsthresh = (float4) vac_ins_base_thresh + vac_ins_scale_factor * reltuples;
3140 3368 : anlthresh = (float4) anl_base_thresh + anl_scale_factor * reltuples;
3141 :
3142 : /*
3143 : * Note that we don't need to take special consideration for stat
3144 : * reset, because if that happens, the last vacuum and analyze counts
3145 : * will be reset too.
3146 : */
3147 3368 : if (vac_ins_base_thresh >= 0)
3148 3368 : elog(DEBUG3, "%s: vac: %.0f (threshold %.0f), ins: %.0f (threshold %.0f), anl: %.0f (threshold %.0f)",
3149 : NameStr(classForm->relname),
3150 : vactuples, vacthresh, instuples, vacinsthresh, anltuples, anlthresh);
3151 : else
3152 0 : elog(DEBUG3, "%s: vac: %.0f (threshold %.0f), ins: (disabled), anl: %.0f (threshold %.0f)",
3153 : NameStr(classForm->relname),
3154 : vactuples, vacthresh, anltuples, anlthresh);
3155 :
3156 : /* Determine if this table needs vacuum or analyze. */
3157 6592 : *dovacuum = force_vacuum || (vactuples > vacthresh) ||
3158 3224 : (vac_ins_base_thresh >= 0 && instuples > vacinsthresh);
3159 3368 : *doanalyze = (anltuples > anlthresh);
3160 : }
3161 : else
3162 : {
3163 : /*
3164 : * Skip a table not found in stat hash, unless we have to force vacuum
3165 : * for anti-wrap purposes. If it's not acted upon, there's no need to
3166 : * vacuum it.
3167 : */
3168 864 : *dovacuum = force_vacuum;
3169 864 : *doanalyze = false;
3170 : }
3171 :
3172 : /* ANALYZE refuses to work with pg_statistic */
3173 4232 : if (relid == StatisticRelationId)
3174 18 : *doanalyze = false;
3175 : }
3176 :
3177 : /*
3178 : * autovacuum_do_vac_analyze
3179 : * Vacuum and/or analyze the specified table
3180 : *
3181 : * We expect the caller to have switched into a memory context that won't
3182 : * disappear at transaction commit.
3183 : */
3184 : static void
3185 202 : autovacuum_do_vac_analyze(autovac_table *tab, BufferAccessStrategy bstrategy)
3186 : {
3187 : RangeVar *rangevar;
3188 : VacuumRelation *rel;
3189 : List *rel_list;
3190 : MemoryContext vac_context;
3191 :
3192 : /* Let pgstat know what we're doing */
3193 202 : autovac_report_activity(tab);
3194 :
3195 : /* Set up one VacuumRelation target, identified by OID, for vacuum() */
3196 202 : rangevar = makeRangeVar(tab->at_nspname, tab->at_relname, -1);
3197 202 : rel = makeVacuumRelation(rangevar, tab->at_relid, NIL);
3198 202 : rel_list = list_make1(rel);
3199 :
3200 202 : vac_context = AllocSetContextCreate(CurrentMemoryContext,
3201 : "Vacuum",
3202 : ALLOCSET_DEFAULT_SIZES);
3203 :
3204 202 : vacuum(rel_list, &tab->at_params, bstrategy, vac_context, true);
3205 :
3206 202 : MemoryContextDelete(vac_context);
3207 202 : }
3208 :
3209 : /*
3210 : * autovac_report_activity
3211 : * Report to pgstat what autovacuum is doing
3212 : *
3213 : * We send a SQL string corresponding to what the user would see if the
3214 : * equivalent command was to be issued manually.
3215 : *
3216 : * Note we assume that we are going to report the next command as soon as we're
3217 : * done with the current one, and exit right after the last one, so we don't
3218 : * bother to report "<IDLE>" or some such.
3219 : */
3220 : static void
3221 202 : autovac_report_activity(autovac_table *tab)
3222 : {
3223 : #define MAX_AUTOVAC_ACTIV_LEN (NAMEDATALEN * 2 + 56)
3224 : char activity[MAX_AUTOVAC_ACTIV_LEN];
3225 : int len;
3226 :
3227 : /* Report the command and possible options */
3228 202 : if (tab->at_params.options & VACOPT_VACUUM)
3229 104 : snprintf(activity, MAX_AUTOVAC_ACTIV_LEN,
3230 : "autovacuum: VACUUM%s",
3231 104 : tab->at_params.options & VACOPT_ANALYZE ? " ANALYZE" : "");
3232 : else
3233 98 : snprintf(activity, MAX_AUTOVAC_ACTIV_LEN,
3234 : "autovacuum: ANALYZE");
3235 :
3236 : /*
3237 : * Report the qualified name of the relation.
3238 : */
3239 202 : len = strlen(activity);
3240 :
3241 202 : snprintf(activity + len, MAX_AUTOVAC_ACTIV_LEN - len,
3242 : " %s.%s%s", tab->at_nspname, tab->at_relname,
3243 202 : tab->at_params.is_wraparound ? " (to prevent wraparound)" : "");
3244 :
3245 : /* Set statement_timestamp() to current time for pg_stat_activity */
3246 202 : SetCurrentStatementStartTimestamp();
3247 :
3248 202 : pgstat_report_activity(STATE_RUNNING, activity);
3249 202 : }
3250 :
3251 : /*
3252 : * autovac_report_workitem
3253 : * Report to pgstat that autovacuum is processing a work item
3254 : */
3255 : static void
3256 6 : autovac_report_workitem(AutoVacuumWorkItem *workitem,
3257 : const char *nspname, const char *relname)
3258 : {
3259 : char activity[MAX_AUTOVAC_ACTIV_LEN + 12 + 2];
3260 : char blk[12 + 2];
3261 : int len;
3262 :
3263 6 : switch (workitem->avw_type)
3264 : {
3265 6 : case AVW_BRINSummarizeRange:
3266 6 : snprintf(activity, MAX_AUTOVAC_ACTIV_LEN,
3267 : "autovacuum: BRIN summarize");
3268 6 : break;
3269 : }
3270 :
3271 : /*
3272 : * Report the qualified name of the relation, and the block number if any
3273 : */
3274 6 : len = strlen(activity);
3275 :
3276 6 : if (BlockNumberIsValid(workitem->avw_blockNumber))
3277 6 : snprintf(blk, sizeof(blk), " %u", workitem->avw_blockNumber);
3278 : else
3279 0 : blk[0] = '\0';
3280 :
3281 6 : snprintf(activity + len, MAX_AUTOVAC_ACTIV_LEN - len,
3282 : " %s.%s%s", nspname, relname, blk);
3283 :
3284 : /* Set statement_timestamp() to current time for pg_stat_activity */
3285 6 : SetCurrentStatementStartTimestamp();
3286 :
3287 6 : pgstat_report_activity(STATE_RUNNING, activity);
3288 6 : }
3289 :
3290 : /*
3291 : * AutoVacuumingActive
3292 : * Check GUC vars and report whether the autovacuum process should be
3293 : * running.
3294 : */
3295 : bool
3296 14228 : AutoVacuumingActive(void)
3297 : {
3298 14228 : if (!autovacuum_start_daemon || !pgstat_track_counts)
3299 3350 : return false;
3300 10878 : return true;
3301 : }
3302 :
3303 : /*
3304 : * Request one work item to the next autovacuum run processing our database.
3305 : * Return false if the request can't be recorded.
3306 : */
3307 : bool
3308 6 : AutoVacuumRequestWork(AutoVacuumWorkItemType type, Oid relationId,
3309 : BlockNumber blkno)
3310 : {
3311 : int i;
3312 6 : bool result = false;
3313 :
3314 6 : LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
3315 :
3316 : /*
3317 : * Locate an unused work item and fill it with the given data.
3318 : */
3319 12 : for (i = 0; i < NUM_WORKITEMS; i++)
3320 : {
3321 12 : AutoVacuumWorkItem *workitem = &AutoVacuumShmem->av_workItems[i];
3322 :
3323 12 : if (workitem->avw_used)
3324 6 : continue;
3325 :
3326 6 : workitem->avw_used = true;
3327 6 : workitem->avw_active = false;
3328 6 : workitem->avw_type = type;
3329 6 : workitem->avw_database = MyDatabaseId;
3330 6 : workitem->avw_relation = relationId;
3331 6 : workitem->avw_blockNumber = blkno;
3332 6 : result = true;
3333 :
3334 : /* done */
3335 6 : break;
3336 : }
3337 :
3338 6 : LWLockRelease(AutovacuumLock);
3339 :
3340 6 : return result;
3341 : }
3342 :
3343 : /*
3344 : * autovac_init
3345 : * This is called at postmaster initialization.
3346 : *
3347 : * All we do here is annoy the user if he got it wrong.
3348 : */
3349 : void
3350 1280 : autovac_init(void)
3351 : {
3352 1280 : if (autovacuum_start_daemon && !pgstat_track_counts)
3353 0 : ereport(WARNING,
3354 : (errmsg("autovacuum not started because of misconfiguration"),
3355 : errhint("Enable the \"track_counts\" option.")));
3356 1280 : }
3357 :
3358 : /*
3359 : * IsAutoVacuum functions
3360 : * Return whether this is either a launcher autovacuum process or a worker
3361 : * process.
3362 : */
3363 : bool
3364 96046 : IsAutoVacuumLauncherProcess(void)
3365 : {
3366 96046 : return am_autovacuum_launcher;
3367 : }
3368 :
3369 : bool
3370 178500 : IsAutoVacuumWorkerProcess(void)
3371 : {
3372 178500 : return am_autovacuum_worker;
3373 : }
3374 :
3375 :
3376 : /*
3377 : * AutoVacuumShmemSize
3378 : * Compute space needed for autovacuum-related shared memory
3379 : */
3380 : Size
3381 4496 : AutoVacuumShmemSize(void)
3382 : {
3383 : Size size;
3384 :
3385 : /*
3386 : * Need the fixed struct and the array of WorkerInfoData.
3387 : */
3388 4496 : size = sizeof(AutoVacuumShmemStruct);
3389 4496 : size = MAXALIGN(size);
3390 4496 : size = add_size(size, mul_size(autovacuum_max_workers,
3391 : sizeof(WorkerInfoData)));
3392 4496 : return size;
3393 : }
3394 :
3395 : /*
3396 : * AutoVacuumShmemInit
3397 : * Allocate and initialize autovacuum-related shared memory
3398 : */
3399 : void
3400 1562 : AutoVacuumShmemInit(void)
3401 : {
3402 : bool found;
3403 :
3404 1562 : AutoVacuumShmem = (AutoVacuumShmemStruct *)
3405 1562 : ShmemInitStruct("AutoVacuum Data",
3406 : AutoVacuumShmemSize(),
3407 : &found);
3408 :
3409 1562 : if (!IsUnderPostmaster)
3410 : {
3411 : WorkerInfo worker;
3412 : int i;
3413 :
3414 : Assert(!found);
3415 :
3416 1562 : AutoVacuumShmem->av_launcherpid = 0;
3417 1562 : dlist_init(&AutoVacuumShmem->av_freeWorkers);
3418 1562 : dlist_init(&AutoVacuumShmem->av_runningWorkers);
3419 1562 : AutoVacuumShmem->av_startingWorker = NULL;
3420 1562 : memset(AutoVacuumShmem->av_workItems, 0,
3421 : sizeof(AutoVacuumWorkItem) * NUM_WORKITEMS);
3422 :
3423 1562 : worker = (WorkerInfo) ((char *) AutoVacuumShmem +
3424 : MAXALIGN(sizeof(AutoVacuumShmemStruct)));
3425 :
3426 : /* initialize the WorkerInfo free list */
3427 6248 : for (i = 0; i < autovacuum_max_workers; i++)
3428 : {
3429 4686 : dlist_push_head(&AutoVacuumShmem->av_freeWorkers,
3430 4686 : &worker[i].wi_links);
3431 4686 : pg_atomic_init_flag(&worker[i].wi_dobalance);
3432 : }
3433 :
3434 1562 : pg_atomic_init_u32(&AutoVacuumShmem->av_nworkersForBalance, 0);
3435 :
3436 : }
3437 : else
3438 : Assert(found);
3439 1562 : }
3440 :
3441 : /*
3442 : * GUC check_hook for autovacuum_work_mem
3443 : */
3444 : bool
3445 1628 : check_autovacuum_work_mem(int *newval, void **extra, GucSource source)
3446 : {
3447 : /*
3448 : * -1 indicates fallback.
3449 : *
3450 : * If we haven't yet changed the boot_val default of -1, just let it be.
3451 : * Autovacuum will look to maintenance_work_mem instead.
3452 : */
3453 1628 : if (*newval == -1)
3454 1624 : return true;
3455 :
3456 : /*
3457 : * We clamp manually-set values to at least 1MB. Since
3458 : * maintenance_work_mem is always set to at least this value, do the same
3459 : * here.
3460 : */
3461 4 : if (*newval < 1024)
3462 4 : *newval = 1024;
3463 :
3464 4 : return true;
3465 : }
|