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