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