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