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