diff options
| author | Bruce Momjian <bruce@momjian.us> | 2007-11-15 21:14:46 +0000 |
|---|---|---|
| committer | Bruce Momjian <bruce@momjian.us> | 2007-11-15 21:14:46 +0000 |
| commit | fdf5a5efb7b28c13085fe7313658de8d7b9914f6 (patch) | |
| tree | a75cf1422fa1eef4e801cf502b148d8ce1b5dfe7 /src/backend/postmaster | |
| parent | 3adc760fb92eab1a8720337a8bf9b66486609eb3 (diff) | |
| download | postgresql-fdf5a5efb7b28c13085fe7313658de8d7b9914f6.tar.gz | |
pgindent run for 8.3.
Diffstat (limited to 'src/backend/postmaster')
| -rw-r--r-- | src/backend/postmaster/autovacuum.c | 395 | ||||
| -rw-r--r-- | src/backend/postmaster/bgwriter.c | 92 | ||||
| -rw-r--r-- | src/backend/postmaster/pgarch.c | 16 | ||||
| -rw-r--r-- | src/backend/postmaster/pgstat.c | 142 | ||||
| -rw-r--r-- | src/backend/postmaster/postmaster.c | 269 | ||||
| -rw-r--r-- | src/backend/postmaster/syslogger.c | 165 | ||||
| -rw-r--r-- | src/backend/postmaster/walwriter.c | 18 |
7 files changed, 567 insertions, 530 deletions
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c index b8300f00cf..060fc06dfa 100644 --- a/src/backend/postmaster/autovacuum.c +++ b/src/backend/postmaster/autovacuum.c @@ -21,21 +21,21 @@ * There is an autovacuum shared memory area, where the launcher stores * information about the database it wants vacuumed. When it wants a new * worker to start, it sets a flag in shared memory and sends a signal to the - * postmaster. Then postmaster knows nothing more than it must start a worker; - * so it forks a new child, which turns into a worker. This new process + * postmaster. Then postmaster knows nothing more than it must start a worker; + * so it forks a new child, which turns into a worker. This new process * connects to shared memory, and there it can inspect the information that the * launcher has set up. * * If the fork() call fails in the postmaster, it sets a flag in the shared * memory area, and sends a signal to the launcher. The launcher, upon * noticing the flag, can try starting the worker again by resending the - * signal. Note that the failure can only be transient (fork failure due to + * signal. Note that the failure can only be transient (fork failure due to * high load, memory pressure, too many processes, etc); more permanent * problems, like failure to connect to a database, are detected later in the * worker and dealt with just by having the worker exit normally. The launcher * will launch a new worker again later, per schedule. * - * When the worker is done vacuuming it sends SIGUSR1 to the launcher. The + * When the worker is done vacuuming it sends SIGUSR1 to the launcher. The * launcher then wakes up and is able to launch another worker, if the schedule * is so tight that a new worker is needed immediately. At this time the * launcher can also balance the settings for the various remaining workers' @@ -55,7 +55,7 @@ * * * IDENTIFICATION - * $PostgreSQL: pgsql/src/backend/postmaster/autovacuum.c,v 1.67 2007/10/29 22:17:41 alvherre Exp $ + * $PostgreSQL: pgsql/src/backend/postmaster/autovacuum.c,v 1.68 2007/11/15 21:14:37 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -141,10 +141,10 @@ static MemoryContext AutovacMemCxt; /* struct to keep track of databases in launcher */ typedef struct avl_dbase { - Oid adl_datid; /* hash key -- must be first */ - TimestampTz adl_next_worker; + Oid adl_datid; /* hash key -- must be first */ + TimestampTz adl_next_worker; int adl_score; -} avl_dbase; +} avl_dbase; /* struct to keep track of databases in worker */ typedef struct avw_dbase @@ -153,14 +153,14 @@ typedef struct avw_dbase char *adw_name; TransactionId adw_frozenxid; PgStat_StatDBEntry *adw_entry; -} avw_dbase; +} avw_dbase; /* struct to keep track of tables to vacuum and/or analyze, in 1st pass */ typedef struct av_relation { - Oid ar_relid; - Oid ar_toastrelid; -} av_relation; + Oid ar_relid; + Oid ar_toastrelid; +} av_relation; /* struct to keep track of tables to vacuum and/or analyze, after rechecking */ typedef struct autovac_table @@ -198,11 +198,11 @@ typedef struct WorkerInfoData Oid wi_dboid; Oid wi_tableoid; PGPROC *wi_proc; - TimestampTz wi_launchtime; + TimestampTz wi_launchtime; int wi_cost_delay; int wi_cost_limit; int wi_cost_limit_base; -} WorkerInfoData; +} WorkerInfoData; typedef struct WorkerInfoData *WorkerInfo; @@ -211,16 +211,16 @@ typedef struct WorkerInfoData *WorkerInfo; * stored atomically in shared memory so that other processes can set them * without locking. */ -typedef enum +typedef enum { - AutoVacForkFailed, /* failed trying to start a worker */ - AutoVacRebalance, /* rebalance the cost limits */ - AutoVacNumSignals = AutoVacRebalance /* must be last */ + AutoVacForkFailed, /* failed trying to start a worker */ + AutoVacRebalance, /* rebalance the cost limits */ + AutoVacNumSignals = AutoVacRebalance /* must be last */ } AutoVacuumSignal; /*------------- * The main autovacuum shmem struct. On shared memory we store this main - * struct and the array of WorkerInfo structs. This struct keeps: + * struct and the array of WorkerInfo structs. This struct keeps: * * av_signal set by other processes to indicate various conditions * av_launcherpid the PID of the autovacuum launcher @@ -235,12 +235,12 @@ typedef enum */ typedef struct { - sig_atomic_t av_signal[AutoVacNumSignals]; - pid_t av_launcherpid; - SHMEM_OFFSET av_freeWorkers; - SHM_QUEUE av_runningWorkers; - SHMEM_OFFSET av_startingWorker; -} AutoVacuumShmemStruct; + sig_atomic_t av_signal[AutoVacNumSignals]; + pid_t av_launcherpid; + SHMEM_OFFSET av_freeWorkers; + SHM_QUEUE av_runningWorkers; + SHMEM_OFFSET av_startingWorker; +} AutoVacuumShmemStruct; static AutoVacuumShmemStruct *AutoVacuumShmem; @@ -249,10 +249,10 @@ static Dllist *DatabaseList = NULL; static MemoryContext DatabaseListCxt = NULL; /* Pointer to my own WorkerInfo, valid on each worker */ -static WorkerInfo MyWorkerInfo = NULL; +static WorkerInfo MyWorkerInfo = NULL; /* PID of launcher, valid only in worker while shutting down */ -int AutovacuumLauncherPid = 0; +int AutovacuumLauncherPid = 0; #ifdef EXEC_BACKEND static pid_t avlauncher_forkexec(void); @@ -261,20 +261,20 @@ static pid_t avworker_forkexec(void); NON_EXEC_STATIC void AutoVacWorkerMain(int argc, char *argv[]); NON_EXEC_STATIC void AutoVacLauncherMain(int argc, char *argv[]); -static Oid do_start_worker(void); +static Oid do_start_worker(void); static void launcher_determine_sleep(bool canlaunch, bool recursing, - struct timeval *nap); + struct timeval * nap); static void launch_worker(TimestampTz now); static List *get_database_list(void); static void rebuild_database_list(Oid newdb); -static int db_comparator(const void *a, const void *b); +static int db_comparator(const void *a, const void *b); static void autovac_balance_cost(void); static void do_autovacuum(void); static void FreeWorkerInfo(int code, Datum arg); static void relation_check_autovac(Oid relid, Form_pg_class classForm, - Form_pg_autovacuum avForm, PgStat_StatTabEntry *tabentry, + Form_pg_autovacuum avForm, PgStat_StatTabEntry *tabentry, List **table_oids, List **table_toast_list, List **toast_oids); static autovac_table *table_recheck_autovac(Oid relid); @@ -300,7 +300,7 @@ static void autovac_refresh_stats(void); /******************************************************************** - * AUTOVACUUM LAUNCHER CODE + * AUTOVACUUM LAUNCHER CODE ********************************************************************/ #ifdef EXEC_BACKEND @@ -403,9 +403,9 @@ AutoVacLauncherMain(int argc, char *argv[]) /* * If possible, make this process a group leader, so that the postmaster - * can signal any child processes too. (autovacuum probably never has - * any child processes, but for consistency we make all postmaster - * child processes do this.) + * can signal any child processes too. (autovacuum probably never has any + * child processes, but for consistency we make all postmaster child + * processes do this.) */ #ifdef HAVE_SETSID if (setsid() < 0) @@ -475,7 +475,7 @@ AutoVacLauncherMain(int argc, char *argv[]) /* * These operations are really just a minimal subset of - * AbortTransaction(). We don't have very many resources to worry + * AbortTransaction(). We don't have very many resources to worry * about, but we do have LWLocks. */ LWLockReleaseAll(); @@ -525,7 +525,7 @@ AutoVacLauncherMain(int argc, char *argv[]) if (!AutoVacuumingActive()) { do_start_worker(); - proc_exit(0); /* done */ + proc_exit(0); /* done */ } AutoVacuumShmem->av_launcherpid = MyProcPid; @@ -543,8 +543,8 @@ AutoVacLauncherMain(int argc, char *argv[]) { struct timeval nap; TimestampTz current_time = 0; - bool can_launch; - Dlelem *elem; + bool can_launch; + Dlelem *elem; /* * Emergency bailout if postmaster has died. This is to avoid the @@ -554,7 +554,7 @@ AutoVacLauncherMain(int argc, char *argv[]) exit(1); launcher_determine_sleep(AutoVacuumShmem->av_freeWorkers != - INVALID_OFFSET, false, &nap); + INVALID_OFFSET, false, &nap); /* * Sleep for a while according to schedule. @@ -566,7 +566,7 @@ AutoVacLauncherMain(int argc, char *argv[]) */ while (nap.tv_sec > 0 || nap.tv_usec > 0) { - uint32 sleeptime; + uint32 sleeptime; if (nap.tv_sec > 0) { @@ -643,7 +643,7 @@ AutoVacLauncherMain(int argc, char *argv[]) * of a worker will continue to fail in the same way. */ AutoVacuumShmem->av_signal[AutoVacForkFailed] = false; - pg_usleep(100000L); /* 100ms */ + pg_usleep(100000L); /* 100ms */ SendPostmasterSignal(PMSIGNAL_START_AUTOVAC_WORKER); continue; } @@ -652,8 +652,8 @@ AutoVacLauncherMain(int argc, char *argv[]) /* * There are some conditions that we need to check before trying to * start a launcher. First, we need to make sure that there is a - * launcher slot available. Second, we need to make sure that no other - * worker failed while starting up. + * launcher slot available. Second, we need to make sure that no + * other worker failed while starting up. */ current_time = GetCurrentTimestamp(); @@ -663,23 +663,24 @@ AutoVacLauncherMain(int argc, char *argv[]) if (AutoVacuumShmem->av_startingWorker != INVALID_OFFSET) { - int waittime; + int waittime; - WorkerInfo worker = (WorkerInfo) MAKE_PTR(AutoVacuumShmem->av_startingWorker); + WorkerInfo worker = (WorkerInfo) MAKE_PTR(AutoVacuumShmem->av_startingWorker); /* * We can't launch another worker when another one is still * starting up (or failed while doing so), so just sleep for a bit * more; that worker will wake us up again as soon as it's ready. - * We will only wait autovacuum_naptime seconds (up to a maximum of - * 60 seconds) for this to happen however. Note that failure to - * connect to a particular database is not a problem here, because - * the worker removes itself from the startingWorker pointer before - * trying to connect. Problems detected by the postmaster (like - * fork() failure) are also reported and handled differently. The - * only problems that may cause this code to fire are errors in the - * earlier sections of AutoVacWorkerMain, before the worker removes - * the WorkerInfo from the startingWorker pointer. + * We will only wait autovacuum_naptime seconds (up to a maximum + * of 60 seconds) for this to happen however. Note that failure + * to connect to a particular database is not a problem here, + * because the worker removes itself from the startingWorker + * pointer before trying to connect. Problems detected by the + * postmaster (like fork() failure) are also reported and handled + * differently. The only problems that may cause this code to + * fire are errors in the earlier sections of AutoVacWorkerMain, + * before the worker removes the WorkerInfo from the + * startingWorker pointer. */ waittime = Min(autovacuum_naptime, 60) * 1000; if (TimestampDifferenceExceeds(worker->wi_launchtime, current_time, @@ -687,6 +688,7 @@ AutoVacLauncherMain(int argc, char *argv[]) { LWLockRelease(AutovacuumLock); LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE); + /* * No other process can put a worker in starting mode, so if * startingWorker is still INVALID after exchanging our lock, @@ -709,7 +711,7 @@ AutoVacLauncherMain(int argc, char *argv[]) else can_launch = false; } - LWLockRelease(AutovacuumLock); /* either shared or exclusive */ + LWLockRelease(AutovacuumLock); /* either shared or exclusive */ /* if we can't do anything, just go back to sleep */ if (!can_launch) @@ -720,10 +722,11 @@ AutoVacLauncherMain(int argc, char *argv[]) elem = DLGetTail(DatabaseList); if (elem != NULL) { - avl_dbase *avdb = DLE_VAL(elem); + avl_dbase *avdb = DLE_VAL(elem); /* - * launch a worker if next_worker is right now or it is in the past + * launch a worker if next_worker is right now or it is in the + * past */ if (TimestampDifferenceExceeds(avdb->adl_next_worker, current_time, 0)) @@ -748,7 +751,7 @@ AutoVacLauncherMain(int argc, char *argv[]) (errmsg("autovacuum launcher shutting down"))); AutoVacuumShmem->av_launcherpid = 0; - proc_exit(0); /* done */ + proc_exit(0); /* done */ } /* @@ -759,14 +762,14 @@ AutoVacLauncherMain(int argc, char *argv[]) * cause a long sleep, which will be interrupted when a worker exits. */ static void -launcher_determine_sleep(bool canlaunch, bool recursing, struct timeval *nap) +launcher_determine_sleep(bool canlaunch, bool recursing, struct timeval * nap) { - Dlelem *elem; + Dlelem *elem; /* * We sleep until the next scheduled vacuum. We trust that when the - * database list was built, care was taken so that no entries have times in - * the past; if the first entry has too close a next_worker value, or a + * database list was built, care was taken so that no entries have times + * in the past; if the first entry has too close a next_worker value, or a * time in the past, we will sleep a small nominal time. */ if (!canlaunch) @@ -777,10 +780,10 @@ launcher_determine_sleep(bool canlaunch, bool recursing, struct timeval *nap) else if ((elem = DLGetTail(DatabaseList)) != NULL) { avl_dbase *avdb = DLE_VAL(elem); - TimestampTz current_time = GetCurrentTimestamp(); - TimestampTz next_wakeup; - long secs; - int usecs; + TimestampTz current_time = GetCurrentTimestamp(); + TimestampTz next_wakeup; + long secs; + int usecs; next_wakeup = avdb->adl_next_worker; TimestampDifference(current_time, next_wakeup, &secs, &usecs); @@ -829,7 +832,7 @@ launcher_determine_sleep(bool canlaunch, bool recursing, struct timeval *nap) * this the "new" database, because when the database was already present on * the list, we expect that this function is not called at all). The * preexisting list, if any, will be used to preserve the order of the - * databases in the autovacuum_naptime period. The new database is put at the + * databases in the autovacuum_naptime period. The new database is put at the * end of the interval. The actual values are not saved, which should not be * much of a problem. */ @@ -864,14 +867,14 @@ rebuild_database_list(Oid newdb) /* * Implementing this is not as simple as it sounds, because we need to put * the new database at the end of the list; next the databases that were - * already on the list, and finally (at the tail of the list) all the other - * databases that are not on the existing list. + * already on the list, and finally (at the tail of the list) all the + * other databases that are not on the existing list. * * To do this, we build an empty hash table of scored databases. We will - * start with the lowest score (zero) for the new database, then increasing - * scores for the databases in the existing list, in order, and lastly - * increasing scores for all databases gotten via get_database_list() that - * are not already on the hash. + * start with the lowest score (zero) for the new database, then + * increasing scores for the databases in the existing list, in order, and + * lastly increasing scores for all databases gotten via + * get_database_list() that are not already on the hash. * * Then we will put all the hash elements into an array, sort the array by * score, and finally put the array elements into the new doubly linked @@ -888,7 +891,7 @@ rebuild_database_list(Oid newdb) score = 0; if (OidIsValid(newdb)) { - avl_dbase *db; + avl_dbase *db; PgStat_StatDBEntry *entry; /* only consider this database if it has a pgstat entry */ @@ -907,7 +910,7 @@ rebuild_database_list(Oid newdb) /* Now insert the databases from the existing list */ if (DatabaseList != NULL) { - Dlelem *elem; + Dlelem *elem; elem = DLGetHead(DatabaseList); while (elem != NULL) @@ -920,8 +923,8 @@ rebuild_database_list(Oid newdb) elem = DLGetSucc(elem); /* - * skip databases with no stat entries -- in particular, this - * gets rid of dropped databases + * skip databases with no stat entries -- in particular, this gets + * rid of dropped databases */ entry = pgstat_fetch_stat_dbentry(avdb->adl_datid); if (entry == NULL) @@ -969,12 +972,12 @@ rebuild_database_list(Oid newdb) if (nelems > 0) { - TimestampTz current_time; - int millis_increment; - avl_dbase *dbary; - avl_dbase *db; - HASH_SEQ_STATUS seq; - int i; + TimestampTz current_time; + int millis_increment; + avl_dbase *dbary; + avl_dbase *db; + HASH_SEQ_STATUS seq; + int i; /* put all the hash elements into an array */ dbary = palloc(nelems * sizeof(avl_dbase)); @@ -992,7 +995,7 @@ rebuild_database_list(Oid newdb) current_time = GetCurrentTimestamp(); /* - * move the elements from the array into the dllist, setting the + * move the elements from the array into the dllist, setting the * next_worker while walking the array */ for (i = 0; i < nelems; i++) @@ -1033,7 +1036,7 @@ db_comparator(const void *a, const void *b) * * Bare-bones procedure for starting an autovacuum worker from the launcher. * It determines what database to work on, sets up shared memory stuff and - * signals postmaster to start the worker. It fails gracefully if invoked when + * signals postmaster to start the worker. It fails gracefully if invoked when * autovacuum_workers are already active. * * Return value is the OID of the database that the worker is going to process, @@ -1047,11 +1050,11 @@ do_start_worker(void) TransactionId xidForceLimit; bool for_xid_wrap; avw_dbase *avdb; - TimestampTz current_time; + TimestampTz current_time; bool skipit = false; Oid retval = InvalidOid; MemoryContext tmpcxt, - oldcxt; + oldcxt; /* return quickly when there are no free workers */ LWLockAcquire(AutovacuumLock, LW_SHARED); @@ -1080,8 +1083,8 @@ do_start_worker(void) dblist = get_database_list(); /* - * Determine the oldest datfrozenxid/relfrozenxid that we will allow - * to pass without forcing a vacuum. (This limit can be tightened for + * Determine the oldest datfrozenxid/relfrozenxid that we will allow to + * pass without forcing a vacuum. (This limit can be tightened for * particular tables, but not loosened.) */ recentXid = ReadNewTransactionId(); @@ -1121,7 +1124,7 @@ do_start_worker(void) if (TransactionIdPrecedes(tmp->adw_frozenxid, xidForceLimit)) { if (avdb == NULL || - TransactionIdPrecedes(tmp->adw_frozenxid, avdb->adw_frozenxid)) + TransactionIdPrecedes(tmp->adw_frozenxid, avdb->adw_frozenxid)) avdb = tmp; for_xid_wrap = true; continue; @@ -1151,7 +1154,7 @@ do_start_worker(void) while (elem != NULL) { - avl_dbase *dbp = DLE_VAL(elem); + avl_dbase *dbp = DLE_VAL(elem); if (dbp->adl_datid == tmp->adw_datid) { @@ -1160,7 +1163,7 @@ do_start_worker(void) * the current time and the current time plus naptime. */ if (!TimestampDifferenceExceeds(dbp->adl_next_worker, - current_time, 0) && + current_time, 0) && !TimestampDifferenceExceeds(current_time, dbp->adl_next_worker, autovacuum_naptime * 1000)) @@ -1174,8 +1177,8 @@ do_start_worker(void) continue; /* - * Remember the db with oldest autovac time. (If we are here, - * both tmp->entry and db->entry must be non-null.) + * Remember the db with oldest autovac time. (If we are here, both + * tmp->entry and db->entry must be non-null.) */ if (avdb == NULL || tmp->adw_entry->last_autovac_time < avdb->adw_entry->last_autovac_time) @@ -1192,7 +1195,8 @@ do_start_worker(void) /* * Get a worker entry from the freelist. We checked above, so there - * really should be a free slot -- complain very loudly if there isn't. + * really should be a free slot -- complain very loudly if there + * isn't. */ sworker = AutoVacuumShmem->av_freeWorkers; if (sworker == INVALID_OFFSET) @@ -1243,8 +1247,8 @@ do_start_worker(void) static void launch_worker(TimestampTz now) { - Oid dbid; - Dlelem *elem; + Oid dbid; + Dlelem *elem; dbid = do_start_worker(); if (OidIsValid(dbid)) @@ -1256,7 +1260,7 @@ launch_worker(TimestampTz now) elem = (DatabaseList == NULL) ? NULL : DLGetHead(DatabaseList); while (elem != NULL) { - avl_dbase *avdb = DLE_VAL(elem); + avl_dbase *avdb = DLE_VAL(elem); if (avdb->adl_datid == dbid) { @@ -1274,11 +1278,11 @@ launch_worker(TimestampTz now) } /* - * If the database was not present in the database list, we rebuild the - * list. It's possible that the database does not get into the list - * anyway, for example if it's a database that doesn't have a pgstat - * entry, but this is not a problem because we don't want to schedule - * workers regularly into those in any case. + * If the database was not present in the database list, we rebuild + * the list. It's possible that the database does not get into the + * list anyway, for example if it's a database that doesn't have a + * pgstat entry, but this is not a problem because we don't want to + * schedule workers regularly into those in any case. */ if (elem == NULL) rebuild_database_list(dbid); @@ -1287,7 +1291,7 @@ launch_worker(TimestampTz now) /* * Called from postmaster to signal a failure to fork a process to become - * worker. The postmaster should kill(SIGUSR1) the launcher shortly + * worker. The postmaster should kill(SIGUSR1) the launcher shortly * after calling this function. */ void @@ -1343,7 +1347,7 @@ avl_quickdie(SIGNAL_ARGS) /******************************************************************** - * AUTOVACUUM WORKER CODE + * AUTOVACUUM WORKER CODE ********************************************************************/ #ifdef EXEC_BACKEND @@ -1445,9 +1449,9 @@ AutoVacWorkerMain(int argc, char *argv[]) /* * If possible, make this process a group leader, so that the postmaster - * can signal any child processes too. (autovacuum probably never has - * any child processes, but for consistency we make all postmaster - * child processes do this.) + * can signal any child processes too. (autovacuum probably never has any + * child processes, but for consistency we make all postmaster child + * processes do this.) */ #ifdef HAVE_SETSID if (setsid() < 0) @@ -1465,8 +1469,8 @@ AutoVacWorkerMain(int argc, char *argv[]) pqsignal(SIGHUP, SIG_IGN); /* - * SIGINT is used to signal cancelling the current table's vacuum; - * SIGTERM means abort and exit cleanly, and SIGQUIT means abandon ship. + * SIGINT is used to signal cancelling the current table's vacuum; SIGTERM + * means abort and exit cleanly, and SIGQUIT means abandon ship. */ pqsignal(SIGINT, StatementCancelHandler); pqsignal(SIGTERM, die); @@ -1538,9 +1542,10 @@ AutoVacWorkerMain(int argc, char *argv[]) LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE); /* - * beware of startingWorker being INVALID; this should normally not happen, - * but if a worker fails after forking and before this, the launcher might - * have decided to remove it from the queue and start again. + * beware of startingWorker being INVALID; this should normally not + * happen, but if a worker fails after forking and before this, the + * launcher might have decided to remove it from the queue and start + * again. */ if (AutoVacuumShmem->av_startingWorker != INVALID_OFFSET) { @@ -1549,7 +1554,7 @@ AutoVacWorkerMain(int argc, char *argv[]) MyWorkerInfo->wi_proc = MyProc; /* insert into the running list */ - SHMQueueInsertBefore(&AutoVacuumShmem->av_runningWorkers, + SHMQueueInsertBefore(&AutoVacuumShmem->av_runningWorkers, &MyWorkerInfo->wi_links); /* @@ -1575,7 +1580,7 @@ AutoVacWorkerMain(int argc, char *argv[]) if (OidIsValid(dbid)) { - char *dbname; + char *dbname; /* * Report autovac startup to the stats collector. We deliberately do @@ -1629,7 +1634,7 @@ FreeWorkerInfo(int code, Datum arg) /* * Wake the launcher up so that he can launch a new worker immediately * if required. We only save the launcher's PID in local memory here; - * the actual signal will be sent when the PGPROC is recycled. Note + * the actual signal will be sent when the PGPROC is recycled. Note * that we always do this, so that the launcher can rebalance the cost * limit setting of the remaining workers. * @@ -1686,16 +1691,17 @@ static void autovac_balance_cost(void) { WorkerInfo worker; + /* * note: in cost_limit, zero also means use value from elsewhere, because * zero is not a valid value. */ - int vac_cost_limit = (autovacuum_vac_cost_limit > 0 ? - autovacuum_vac_cost_limit : VacuumCostLimit); - int vac_cost_delay = (autovacuum_vac_cost_delay >= 0 ? - autovacuum_vac_cost_delay : VacuumCostDelay); - double cost_total; - double cost_avail; + int vac_cost_limit = (autovacuum_vac_cost_limit > 0 ? + autovacuum_vac_cost_limit : VacuumCostLimit); + int vac_cost_delay = (autovacuum_vac_cost_delay >= 0 ? + autovacuum_vac_cost_delay : VacuumCostDelay); + double cost_total; + double cost_avail; /* not set? nothing to do */ if (vac_cost_limit <= 0 || vac_cost_delay <= 0) @@ -1715,15 +1721,15 @@ autovac_balance_cost(void) worker = (WorkerInfo) SHMQueueNext(&AutoVacuumShmem->av_runningWorkers, &worker->wi_links, - offsetof(WorkerInfoData, wi_links)); + offsetof(WorkerInfoData, wi_links)); } /* there are no cost limits -- nothing to do */ if (cost_total <= 0) return; /* - * Adjust each cost limit of active workers to balance the total of - * cost limit to autovacuum_vacuum_cost_limit. + * Adjust each cost limit of active workers to balance the total of cost + * limit to autovacuum_vacuum_cost_limit. */ cost_avail = (double) vac_cost_limit / vac_cost_delay; worker = (WorkerInfo) SHMQueueNext(&AutoVacuumShmem->av_runningWorkers, @@ -1734,8 +1740,8 @@ autovac_balance_cost(void) if (worker->wi_proc != NULL && worker->wi_cost_limit_base > 0 && worker->wi_cost_delay > 0) { - int limit = (int) - (cost_avail * worker->wi_cost_limit_base / cost_total); + int limit = (int) + (cost_avail * worker->wi_cost_limit_base / cost_total); /* * We put a lower bound of 1 to the cost_limit, to avoid division- @@ -1750,7 +1756,7 @@ autovac_balance_cost(void) worker = (WorkerInfo) SHMQueueNext(&AutoVacuumShmem->av_runningWorkers, &worker->wi_links, - offsetof(WorkerInfoData, wi_links)); + offsetof(WorkerInfoData, wi_links)); } } @@ -1781,7 +1787,7 @@ get_database_list(void) while (read_pg_database_line(db_file, thisname, &db_id, &db_tablespace, &db_frozenxid)) { - avw_dbase *avdb; + avw_dbase *avdb; avdb = (avw_dbase *) palloc(sizeof(avw_dbase)); @@ -1817,7 +1823,7 @@ do_autovacuum(void) List *table_oids = NIL; List *toast_oids = NIL; List *table_toast_list = NIL; - ListCell * volatile cell; + ListCell *volatile cell; PgStat_StatDBEntry *shared; PgStat_StatDBEntry *dbentry; BufferAccessStrategy bstrategy; @@ -1835,8 +1841,8 @@ do_autovacuum(void) MemoryContextSwitchTo(AutovacMemCxt); /* - * may be NULL if we couldn't find an entry (only happens if we - * are forcing a vacuum for anti-wrap purposes). + * may be NULL if we couldn't find an entry (only happens if we are + * forcing a vacuum for anti-wrap purposes). */ dbentry = pgstat_fetch_stat_dbentry(MyDatabaseId); @@ -1854,9 +1860,9 @@ do_autovacuum(void) pgstat_vacuum_tabstat(); /* - * Find the pg_database entry and select the default freeze_min_age. - * We use zero in template and nonconnectable databases, - * else the system-wide default. + * Find the pg_database entry and select the default freeze_min_age. We + * use zero in template and nonconnectable databases, else the system-wide + * default. */ tuple = SearchSysCache(DATABASEOID, ObjectIdGetDatum(MyDatabaseId), @@ -1948,12 +1954,12 @@ do_autovacuum(void) */ foreach(cell, toast_oids) { - Oid toastoid = lfirst_oid(cell); - ListCell *cell2; + Oid toastoid = lfirst_oid(cell); + ListCell *cell2; foreach(cell2, table_toast_list) { - av_relation *ar = lfirst(cell2); + av_relation *ar = lfirst(cell2); if (ar->ar_toastrelid == toastoid) { @@ -1969,9 +1975,9 @@ do_autovacuum(void) toast_oids = NIL; /* - * Create a buffer access strategy object for VACUUM to use. We want - * to use the same one across all the vacuum operations we perform, - * since the point is for VACUUM not to blow out the shared cache. + * Create a buffer access strategy object for VACUUM to use. We want to + * use the same one across all the vacuum operations we perform, since the + * point is for VACUUM not to blow out the shared cache. */ bstrategy = GetAccessStrategy(BAS_VACUUM); @@ -1990,10 +1996,10 @@ do_autovacuum(void) */ foreach(cell, table_oids) { - Oid relid = lfirst_oid(cell); + Oid relid = lfirst_oid(cell); autovac_table *tab; WorkerInfo worker; - bool skipit; + bool skipit; char *datname, *nspname, *relname; @@ -2001,9 +2007,9 @@ do_autovacuum(void) CHECK_FOR_INTERRUPTS(); /* - * hold schedule lock from here until we're sure that this table - * still needs vacuuming. We also need the AutovacuumLock to walk - * the worker array, but we'll let go of that one quickly. + * hold schedule lock from here until we're sure that this table still + * needs vacuuming. We also need the AutovacuumLock to walk the + * worker array, but we'll let go of that one quickly. */ LWLockAcquire(AutovacuumScheduleLock, LW_EXCLUSIVE); LWLockAcquire(AutovacuumLock, LW_SHARED); @@ -2014,8 +2020,8 @@ do_autovacuum(void) */ skipit = false; worker = (WorkerInfo) SHMQueueNext(&AutoVacuumShmem->av_runningWorkers, - &AutoVacuumShmem->av_runningWorkers, - offsetof(WorkerInfoData, wi_links)); + &AutoVacuumShmem->av_runningWorkers, + offsetof(WorkerInfoData, wi_links)); while (worker) { /* ignore myself */ @@ -2032,10 +2038,10 @@ do_autovacuum(void) break; } -next_worker: + next_worker: worker = (WorkerInfo) SHMQueueNext(&AutoVacuumShmem->av_runningWorkers, &worker->wi_links, - offsetof(WorkerInfoData, wi_links)); + offsetof(WorkerInfoData, wi_links)); } LWLockRelease(AutovacuumLock); if (skipit) @@ -2046,8 +2052,8 @@ next_worker: /* * Check whether pgstat data still says we need to vacuum this table. - * It could have changed if something else processed the table while we - * weren't looking. + * It could have changed if something else processed the table while + * we weren't looking. * * FIXME we ignore the possibility that the table was finished being * vacuumed in the last 500ms (PGSTAT_STAT_INTERVAL). This is a bug. @@ -2062,7 +2068,7 @@ next_worker: } /* - * Ok, good to go. Store the table in shared memory before releasing + * Ok, good to go. Store the table in shared memory before releasing * the lock so that other workers don't vacuum it concurrently. */ MyWorkerInfo->wi_tableoid = relid; @@ -2099,7 +2105,7 @@ next_worker: /* * Save the relation name for a possible error message, to avoid a - * catalog lookup in case of an error. Note: they must live in a + * catalog lookup in case of an error. Note: they must live in a * long-lived memory context because we call vacuum and analyze in * different transactions. */ @@ -2124,9 +2130,9 @@ next_worker: /* * Clear a possible query-cancel signal, to avoid a late reaction - * to an automatically-sent signal because of vacuuming the current - * table (we're done with it, so it would make no sense to cancel - * at this point.) + * to an automatically-sent signal because of vacuuming the + * current table (we're done with it, so it would make no sense to + * cancel at this point.) */ QueryCancelPending = false; } @@ -2171,8 +2177,8 @@ next_worker: } /* - * Update pg_database.datfrozenxid, and truncate pg_clog if possible. - * We only need to do this once, not after each table. + * Update pg_database.datfrozenxid, and truncate pg_clog if possible. We + * only need to do this once, not after each table. */ vac_update_datfrozenxid(); @@ -2249,13 +2255,13 @@ get_pgstat_tabentry_relid(Oid relid, bool isshared, PgStat_StatDBEntry *shared, */ static void relation_check_autovac(Oid relid, Form_pg_class classForm, - Form_pg_autovacuum avForm, PgStat_StatTabEntry *tabentry, + Form_pg_autovacuum avForm, PgStat_StatTabEntry *tabentry, List **table_oids, List **table_toast_list, List **toast_oids) { - bool dovacuum; - bool doanalyze; - bool dummy; + bool dovacuum; + bool doanalyze; + bool dummy; relation_needs_vacanalyze(relid, avForm, classForm, tabentry, &dovacuum, &doanalyze, &dummy); @@ -2273,7 +2279,7 @@ relation_check_autovac(Oid relid, Form_pg_class classForm, *table_oids = lappend_oid(*table_oids, relid); else if (OidIsValid(classForm->reltoastrelid)) { - av_relation *rel = palloc(sizeof(av_relation)); + av_relation *rel = palloc(sizeof(av_relation)); rel->ar_relid = relid; rel->ar_toastrelid = classForm->reltoastrelid; @@ -2341,7 +2347,7 @@ table_recheck_autovac(Oid relid) /* it doesn't need vacuum, but what about it's TOAST table? */ else if (OidIsValid(classForm->reltoastrelid)) { - Oid toastrelid = classForm->reltoastrelid; + Oid toastrelid = classForm->reltoastrelid; HeapTuple toastClassTup; toastClassTup = SearchSysCacheCopy(RELOID, @@ -2349,15 +2355,15 @@ table_recheck_autovac(Oid relid) 0, 0, 0); if (HeapTupleIsValid(toastClassTup)) { - bool toast_dovacuum; - bool toast_doanalyze; - bool toast_wraparound; - Form_pg_class toastClassForm; + bool toast_dovacuum; + bool toast_doanalyze; + bool toast_wraparound; + Form_pg_class toastClassForm; PgStat_StatTabEntry *toasttabentry; toastClassForm = (Form_pg_class) GETSTRUCT(toastClassTup); toasttabentry = get_pgstat_tabentry_relid(toastrelid, - toastClassForm->relisshared, + toastClassForm->relisshared, shared, dbentry); /* note we use the pg_autovacuum entry for the main table */ @@ -2386,8 +2392,8 @@ table_recheck_autovac(Oid relid) int vac_cost_delay; /* - * Calculate the vacuum cost parameters and the minimum freeze age. If - * there is a tuple in pg_autovacuum, use it; else, use the GUC + * Calculate the vacuum cost parameters and the minimum freeze age. + * If there is a tuple in pg_autovacuum, use it; else, use the GUC * defaults. Note that the fields may contain "-1" (or indeed any * negative value), which means use the GUC defaults for each setting. * In cost_limit, the value 0 also means to use the value from @@ -2442,7 +2448,7 @@ table_recheck_autovac(Oid relid) * * Check whether a relation needs to be vacuumed or analyzed; return each into * "dovacuum" and "doanalyze", respectively. Also return whether the vacuum is - * being forced because of Xid wraparound. avForm and tabentry can be NULL, + * being forced because of Xid wraparound. avForm and tabentry can be NULL, * classForm shouldn't. * * A table needs to be vacuumed if the number of dead tuples exceeds a @@ -2461,7 +2467,7 @@ table_recheck_autovac(Oid relid) * * A table whose pg_autovacuum.enabled value is false, is automatically * skipped (unless we have to vacuum it due to freeze_max_age). Thus - * autovacuum can be disabled for specific tables. Also, when the stats + * autovacuum can be disabled for specific tables. Also, when the stats * collector does not have data about a table, it will be skipped. * * A table whose vac_base_thresh value is <0 takes the base value from the @@ -2474,24 +2480,28 @@ relation_needs_vacanalyze(Oid relid, Form_pg_autovacuum avForm, Form_pg_class classForm, PgStat_StatTabEntry *tabentry, - /* output params below */ + /* output params below */ bool *dovacuum, bool *doanalyze, bool *wraparound) { bool force_vacuum; float4 reltuples; /* pg_class.reltuples */ + /* constants from pg_autovacuum or GUC variables */ int vac_base_thresh, anl_base_thresh; float4 vac_scale_factor, anl_scale_factor; + /* thresholds calculated from above constants */ float4 vacthresh, anlthresh; + /* number of vacuum (resp. analyze) tuples at this time */ float4 vactuples, anltuples; + /* freeze parameters */ int freeze_max_age; TransactionId xidForceLimit; @@ -2501,9 +2511,9 @@ relation_needs_vacanalyze(Oid relid, /* * Determine vacuum/analyze equation parameters. If there is a tuple in - * pg_autovacuum, use it; else, use the GUC defaults. Note that the fields - * may contain "-1" (or indeed any negative value), which means use the GUC - * defaults for each setting. + * pg_autovacuum, use it; else, use the GUC defaults. Note that the + * fields may contain "-1" (or indeed any negative value), which means use + * the GUC defaults for each setting. */ if (avForm != NULL) { @@ -2575,9 +2585,9 @@ relation_needs_vacanalyze(Oid relid, else { /* - * Skip a table not found in stat hash, unless we have to force - * vacuum for anti-wrap purposes. If it's not acted upon, there's - * no need to vacuum it. + * Skip a table not found in stat hash, unless we have to force vacuum + * for anti-wrap purposes. If it's not acted upon, there's no need to + * vacuum it. */ *dovacuum = force_vacuum; *doanalyze = false; @@ -2641,6 +2651,7 @@ autovac_report_activity(VacuumStmt *vacstmt, Oid relid) { char *relname = get_rel_name(relid); char *nspname = get_namespace_name(get_rel_namespace(relid)); + #define MAX_AUTOVAC_ACTIV_LEN (NAMEDATALEN * 2 + 32) char activity[MAX_AUTOVAC_ACTIV_LEN]; @@ -2656,9 +2667,9 @@ autovac_report_activity(VacuumStmt *vacstmt, Oid relid) /* * Report the qualified name of the relation. * - * Paranoia is appropriate here in case relation was recently dropped - * --- the lsyscache routines we just invoked will return NULL rather - * than failing. + * Paranoia is appropriate here in case relation was recently dropped --- + * the lsyscache routines we just invoked will return NULL rather than + * failing. */ if (relname && nspname) { @@ -2722,12 +2733,12 @@ IsAutoVacuumWorkerProcess(void) /* * AutoVacuumShmemSize - * Compute space needed for autovacuum-related shared memory + * Compute space needed for autovacuum-related shared memory */ Size AutoVacuumShmemSize(void) { - Size size; + Size size; /* * Need the fixed struct and the array of WorkerInfoData. @@ -2746,7 +2757,7 @@ AutoVacuumShmemSize(void) void AutoVacuumShmemInit(void) { - bool found; + bool found; AutoVacuumShmem = (AutoVacuumShmemStruct *) ShmemInitStruct("AutoVacuum Data", @@ -2785,10 +2796,10 @@ AutoVacuumShmemInit(void) /* * autovac_refresh_stats - * Refresh pgstats data for an autovacuum process + * Refresh pgstats data for an autovacuum process * * Cause the next pgstats read operation to obtain fresh data, but throttle - * such refreshing in the autovacuum launcher. This is mostly to avoid + * such refreshing in the autovacuum launcher. This is mostly to avoid * rereading the pgstats files too many times in quick succession when there * are many databases. * @@ -2800,8 +2811,8 @@ autovac_refresh_stats(void) { if (IsAutoVacuumLauncherProcess()) { - static TimestampTz last_read = 0; - TimestampTz current_time; + static TimestampTz last_read = 0; + TimestampTz current_time; current_time = GetCurrentTimestamp(); diff --git a/src/backend/postmaster/bgwriter.c b/src/backend/postmaster/bgwriter.c index f75e9f37d8..7f2d3b820a 100644 --- a/src/backend/postmaster/bgwriter.c +++ b/src/backend/postmaster/bgwriter.c @@ -2,7 +2,7 @@ * * bgwriter.c * - * The background writer (bgwriter) is new as of Postgres 8.0. It attempts + * The background writer (bgwriter) is new as of Postgres 8.0. It attempts * to keep regular backends from having to write out dirty shared buffers * (which they would only do when needing to free a shared buffer to read in * another page). In the best scenario all writes from shared buffers will @@ -37,7 +37,7 @@ * * * IDENTIFICATION - * $PostgreSQL: pgsql/src/backend/postmaster/bgwriter.c,v 1.46 2007/11/14 21:19:18 tgl Exp $ + * $PostgreSQL: pgsql/src/backend/postmaster/bgwriter.c,v 1.47 2007/11/15 21:14:37 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -128,7 +128,7 @@ typedef struct int ckpt_flags; /* checkpoint flags, as defined in xlog.h */ - uint32 num_backend_writes; /* counts non-bgwriter buffer writes */ + uint32 num_backend_writes; /* counts non-bgwriter buffer writes */ int num_requests; /* current # of requests */ int max_requests; /* allocated array size */ @@ -202,9 +202,9 @@ BackgroundWriterMain(void) /* * If possible, make this process a group leader, so that the postmaster - * can signal any child processes too. (bgwriter probably never has - * any child processes, but for consistency we make all postmaster - * child processes do this.) + * can signal any child processes too. (bgwriter probably never has any + * child processes, but for consistency we make all postmaster child + * processes do this.) */ #ifdef HAVE_SETSID if (setsid() < 0) @@ -402,10 +402,10 @@ BackgroundWriterMain(void) } /* - * Force a checkpoint if too much time has elapsed since the - * last one. Note that we count a timed checkpoint in stats only - * when this occurs without an external request, but we set the - * CAUSE_TIME flag bit even if there is also an external request. + * Force a checkpoint if too much time has elapsed since the last one. + * Note that we count a timed checkpoint in stats only when this + * occurs without an external request, but we set the CAUSE_TIME flag + * bit even if there is also an external request. */ now = time(NULL); elapsed_secs = now - last_checkpoint_time; @@ -427,10 +427,9 @@ BackgroundWriterMain(void) volatile BgWriterShmemStruct *bgs = BgWriterShmem; /* - * Atomically fetch the request flags to figure out what - * kind of a checkpoint we should perform, and increase the - * started-counter to acknowledge that we've started - * a new checkpoint. + * Atomically fetch the request flags to figure out what kind of a + * checkpoint we should perform, and increase the started-counter + * to acknowledge that we've started a new checkpoint. */ SpinLockAcquire(&bgs->ckpt_lck); flags |= bgs->ckpt_flags; @@ -518,8 +517,8 @@ CheckArchiveTimeout(void) return; /* - * Update local state ... note that last_xlog_switch_time is the - * last time a switch was performed *or requested*. + * Update local state ... note that last_xlog_switch_time is the last time + * a switch was performed *or requested*. */ last_time = GetLastSegSwitchTime(); @@ -534,17 +533,17 @@ CheckArchiveTimeout(void) switchpoint = RequestXLogSwitch(); /* - * If the returned pointer points exactly to a segment - * boundary, assume nothing happened. + * If the returned pointer points exactly to a segment boundary, + * assume nothing happened. */ if ((switchpoint.xrecoff % XLogSegSize) != 0) ereport(DEBUG1, - (errmsg("transaction log switch forced (archive_timeout=%d)", - XLogArchiveTimeout))); + (errmsg("transaction log switch forced (archive_timeout=%d)", + XLogArchiveTimeout))); /* - * Update state in any case, so we don't retry constantly when - * the system is idle. + * Update state in any case, so we don't retry constantly when the + * system is idle. */ last_xlog_switch_time = now; } @@ -577,14 +576,14 @@ BgWriterNap(void) if (bgwriter_lru_maxpages > 0 || ckpt_active) udelay = BgWriterDelay * 1000L; else if (XLogArchiveTimeout > 0) - udelay = 1000000L; /* One second */ + udelay = 1000000L; /* One second */ else - udelay = 10000000L; /* Ten seconds */ + udelay = 10000000L; /* Ten seconds */ while (udelay > 999999L) { if (got_SIGHUP || shutdown_requested || - (ckpt_active ? ImmediateCheckpointRequested() : checkpoint_requested)) + (ckpt_active ? ImmediateCheckpointRequested() : checkpoint_requested)) break; pg_usleep(1000000L); AbsorbFsyncRequests(); @@ -592,12 +591,12 @@ BgWriterNap(void) } if (!(got_SIGHUP || shutdown_requested || - (ckpt_active ? ImmediateCheckpointRequested() : checkpoint_requested))) + (ckpt_active ? ImmediateCheckpointRequested() : checkpoint_requested))) pg_usleep(udelay); } /* - * Returns true if an immediate checkpoint request is pending. (Note that + * Returns true if an immediate checkpoint request is pending. (Note that * this does not check the *current* checkpoint's IMMEDIATE flag, but whether * there is one pending behind it.) */ @@ -635,7 +634,7 @@ ImmediateCheckpointRequested(void) void CheckpointWriteDelay(int flags, double progress) { - static int absorb_counter = WRITES_PER_ABSORB; + static int absorb_counter = WRITES_PER_ABSORB; /* Do nothing if checkpoint is being executed by non-bgwriter process */ if (!am_bg_writer) @@ -687,7 +686,7 @@ static bool IsCheckpointOnSchedule(double progress) { XLogRecPtr recptr; - struct timeval now; + struct timeval now; double elapsed_xlogs, elapsed_time; @@ -697,7 +696,7 @@ IsCheckpointOnSchedule(double progress) progress *= CheckPointCompletionTarget; /* - * Check against the cached value first. Only do the more expensive + * Check against the cached value first. Only do the more expensive * calculations once we reach the target previously calculated. Since * neither time or WAL insert pointer moves backwards, a freshly * calculated value can only be greater than or equal to the cached value. @@ -708,12 +707,12 @@ IsCheckpointOnSchedule(double progress) /* * Check progress against WAL segments written and checkpoint_segments. * - * We compare the current WAL insert location against the location + * We compare the current WAL insert location against the location * computed before calling CreateCheckPoint. The code in XLogInsert that * actually triggers a checkpoint when checkpoint_segments is exceeded * compares against RedoRecptr, so this is not completely accurate. - * However, it's good enough for our purposes, we're only calculating - * an estimate anyway. + * However, it's good enough for our purposes, we're only calculating an + * estimate anyway. */ recptr = GetInsertRecPtr(); elapsed_xlogs = @@ -852,7 +851,7 @@ BgWriterShmemInit(void) * flags is a bitwise OR of the following: * CHECKPOINT_IS_SHUTDOWN: checkpoint is for database shutdown. * CHECKPOINT_IMMEDIATE: finish the checkpoint ASAP, - * ignoring checkpoint_completion_target parameter. + * ignoring checkpoint_completion_target parameter. * CHECKPOINT_FORCE: force a checkpoint even if no XLOG activity has occured * since the last one (implied by CHECKPOINT_IS_SHUTDOWN). * CHECKPOINT_WAIT: wait for completion before returning (otherwise, @@ -865,7 +864,8 @@ RequestCheckpoint(int flags) { /* use volatile pointer to prevent code rearrangement */ volatile BgWriterShmemStruct *bgs = BgWriterShmem; - int old_failed, old_started; + int old_failed, + old_started; /* * If in a standalone backend, just do it ourselves. @@ -873,9 +873,8 @@ RequestCheckpoint(int flags) if (!IsPostmasterEnvironment) { /* - * There's no point in doing slow checkpoints in a standalone - * backend, because there's no other backends the checkpoint could - * disrupt. + * There's no point in doing slow checkpoints in a standalone backend, + * because there's no other backends the checkpoint could disrupt. */ CreateCheckPoint(flags | CHECKPOINT_IMMEDIATE); @@ -906,8 +905,8 @@ RequestCheckpoint(int flags) SpinLockRelease(&bgs->ckpt_lck); /* - * Send signal to request checkpoint. When not waiting, we - * consider failure to send the signal to be nonfatal. + * Send signal to request checkpoint. When not waiting, we consider + * failure to send the signal to be nonfatal. */ if (BgWriterShmem->bgwriter_pid == 0) elog((flags & CHECKPOINT_WAIT) ? ERROR : LOG, @@ -922,18 +921,19 @@ RequestCheckpoint(int flags) */ if (flags & CHECKPOINT_WAIT) { - int new_started, new_failed; + int new_started, + new_failed; /* Wait for a new checkpoint to start. */ - for(;;) + for (;;) { SpinLockAcquire(&bgs->ckpt_lck); new_started = bgs->ckpt_started; SpinLockRelease(&bgs->ckpt_lck); - + if (new_started != old_started) break; - + CHECK_FOR_INTERRUPTS(); pg_usleep(100000L); } @@ -941,9 +941,9 @@ RequestCheckpoint(int flags) /* * We are waiting for ckpt_done >= new_started, in a modulo sense. */ - for(;;) + for (;;) { - int new_done; + int new_done; SpinLockAcquire(&bgs->ckpt_lck); new_done = bgs->ckpt_done; diff --git a/src/backend/postmaster/pgarch.c b/src/backend/postmaster/pgarch.c index 1b0ad2786c..37e25861e7 100644 --- a/src/backend/postmaster/pgarch.c +++ b/src/backend/postmaster/pgarch.c @@ -19,7 +19,7 @@ * * * IDENTIFICATION - * $PostgreSQL: pgsql/src/backend/postmaster/pgarch.c,v 1.31 2007/09/26 22:36:30 tgl Exp $ + * $PostgreSQL: pgsql/src/backend/postmaster/pgarch.c,v 1.32 2007/11/15 21:14:37 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -223,7 +223,7 @@ PgArchiverMain(int argc, char *argv[]) MyProcPid = getpid(); /* reset MyProcPid */ - MyStartTime = time(NULL); /* record Start Time for logging */ + MyStartTime = time(NULL); /* record Start Time for logging */ /* * If possible, make this process a group leader, so that the postmaster @@ -360,7 +360,7 @@ pgarch_ArchiverCopyLoop(void) if (!XLogArchiveCommandSet()) { ereport(WARNING, - (errmsg("archive_mode enabled, yet archive_command is not set"))); + (errmsg("archive_mode enabled, yet archive_command is not set"))); /* can't do anything if no command ... */ return; } @@ -476,15 +476,15 @@ pgarch_archiveXlog(char *xlog) { /* * If either the shell itself, or a called command, died on a signal, - * abort the archiver. We do this because system() ignores SIGINT and + * abort the archiver. We do this because system() ignores SIGINT and * SIGQUIT while waiting; so a signal is very likely something that - * should have interrupted us too. If we overreact it's no big deal, + * should have interrupted us too. If we overreact it's no big deal, * the postmaster will just start the archiver again. * - * Per the Single Unix Spec, shells report exit status > 128 when - * a called command died on a signal. + * Per the Single Unix Spec, shells report exit status > 128 when a + * called command died on a signal. */ - bool signaled = WIFSIGNALED(rc) || WEXITSTATUS(rc) > 128; + bool signaled = WIFSIGNALED(rc) || WEXITSTATUS(rc) > 128; ereport(signaled ? FATAL : LOG, (errmsg("archive command \"%s\" failed: return code %d", diff --git a/src/backend/postmaster/pgstat.c b/src/backend/postmaster/pgstat.c index 8623dbd005..22ba2ee344 100644 --- a/src/backend/postmaster/pgstat.c +++ b/src/backend/postmaster/pgstat.c @@ -13,7 +13,7 @@ * * Copyright (c) 2001-2007, PostgreSQL Global Development Group * - * $PostgreSQL: pgsql/src/backend/postmaster/pgstat.c,v 1.166 2007/09/25 20:03:37 tgl Exp $ + * $PostgreSQL: pgsql/src/backend/postmaster/pgstat.c,v 1.167 2007/11/15 21:14:37 momjian Exp $ * ---------- */ #include "postgres.h" @@ -127,14 +127,14 @@ static bool pgStatRunningInCollector = false; * avoiding repeated searches in pgstat_initstats() when a relation is * repeatedly opened during a transaction. */ -#define TABSTAT_QUANTUM 100 /* we alloc this many at a time */ +#define TABSTAT_QUANTUM 100 /* we alloc this many at a time */ typedef struct TabStatusArray { struct TabStatusArray *tsa_next; /* link to next array, if any */ - int tsa_used; /* # entries currently used */ + int tsa_used; /* # entries currently used */ PgStat_TableStatus tsa_entries[TABSTAT_QUANTUM]; /* per-table data */ -} TabStatusArray; +} TabStatusArray; static TabStatusArray *pgStatTabList = NULL; @@ -147,10 +147,10 @@ static TabStatusArray *pgStatTabList = NULL; */ typedef struct PgStat_SubXactStatus { - int nest_level; /* subtransaction nest level */ + int nest_level; /* subtransaction nest level */ struct PgStat_SubXactStatus *prev; /* higher-level subxact if any */ PgStat_TableXactStatus *first; /* head of list for this subxact */ -} PgStat_SubXactStatus; +} PgStat_SubXactStatus; static PgStat_SubXactStatus *pgStatXactStack = NULL; @@ -160,11 +160,11 @@ static int pgStatXactRollback = 0; /* Record that's written to 2PC state file when pgstat state is persisted */ typedef struct TwoPhasePgStatRecord { - PgStat_Counter tuples_inserted; /* tuples inserted in xact */ - PgStat_Counter tuples_deleted; /* tuples deleted in xact */ - Oid t_id; /* table's OID */ - bool t_shared; /* is it a shared catalog? */ -} TwoPhasePgStatRecord; + PgStat_Counter tuples_inserted; /* tuples inserted in xact */ + PgStat_Counter tuples_deleted; /* tuples deleted in xact */ + Oid t_id; /* table's OID */ + bool t_shared; /* is it a shared catalog? */ +} TwoPhasePgStatRecord; /* * Info about current "snapshot" of stats file @@ -221,7 +221,7 @@ static void pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len); static void pgstat_recv_autovac(PgStat_MsgAutovacStart *msg, int len); static void pgstat_recv_vacuum(PgStat_MsgVacuum *msg, int len); static void pgstat_recv_analyze(PgStat_MsgAnalyze *msg, int len); -static void pgstat_recv_bgwriter(PgStat_MsgBgWriter *msg, int len); +static void pgstat_recv_bgwriter(PgStat_MsgBgWriter * msg, int len); /* ------------------------------------------------------------ @@ -470,9 +470,9 @@ startup_failed: /* * Adjust GUC variables to suppress useless activity, and for debugging - * purposes (seeing track_counts off is a clue that we failed here). - * We use PGC_S_OVERRIDE because there is no point in trying to turn it - * back on from postgresql.conf without a restart. + * purposes (seeing track_counts off is a clue that we failed here). We + * use PGC_S_OVERRIDE because there is no point in trying to turn it back + * on from postgresql.conf without a restart. */ SetConfigOption("track_counts", "off", PGC_INTERNAL, PGC_S_OVERRIDE); } @@ -531,8 +531,8 @@ pgstat_start(void) pid_t pgStatPid; /* - * Check that the socket is there, else pgstat_init failed and we can - * do nothing useful. + * Check that the socket is there, else pgstat_init failed and we can do + * nothing useful. */ if (pgStatSock < 0) return 0; @@ -587,9 +587,10 @@ pgstat_start(void) return 0; } -void allow_immediate_pgstat_restart(void) +void +allow_immediate_pgstat_restart(void) { - last_pgstat_start_time = 0; + last_pgstat_start_time = 0; } /* ------------------------------------------------------------ @@ -612,7 +613,7 @@ pgstat_report_tabstat(bool force) { /* we assume this inits to all zeroes: */ static const PgStat_TableCounts all_zeroes; - static TimestampTz last_report = 0; + static TimestampTz last_report = 0; TimestampTz now; PgStat_MsgTabstat regular_msg; @@ -638,8 +639,8 @@ pgstat_report_tabstat(bool force) /* * Scan through the TabStatusArray struct(s) to find tables that actually * have counts, and build messages to send. We have to separate shared - * relations from regular ones because the databaseid field in the - * message header has to depend on that. + * relations from regular ones because the databaseid field in the message + * header has to depend on that. */ regular_msg.m_databaseid = MyDatabaseId; shared_msg.m_databaseid = InvalidOid; @@ -658,12 +659,13 @@ pgstat_report_tabstat(bool force) Assert(entry->trans == NULL); /* - * Ignore entries that didn't accumulate any actual counts, - * such as indexes that were opened by the planner but not used. + * Ignore entries that didn't accumulate any actual counts, such + * as indexes that were opened by the planner but not used. */ if (memcmp(&entry->t_counts, &all_zeroes, sizeof(PgStat_TableCounts)) == 0) continue; + /* * OK, insert data into the appropriate message, and send if full. */ @@ -885,7 +887,7 @@ pgstat_collect_oids(Oid catalogid) scan = heap_beginscan(rel, SnapshotNow, 0, NULL); while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL) { - Oid thisoid = HeapTupleGetOid(tup); + Oid thisoid = HeapTupleGetOid(tup); CHECK_FOR_INTERRUPTS(); @@ -950,7 +952,7 @@ pgstat_drop_relation(Oid relid) msg.m_databaseid = MyDatabaseId; pgstat_send(&msg, len); } -#endif /* NOT_USED */ +#endif /* NOT_USED */ /* ---------- @@ -1021,7 +1023,7 @@ pgstat_report_vacuum(Oid tableoid, bool shared, msg.m_databaseid = shared ? InvalidOid : MyDatabaseId; msg.m_tableoid = tableoid; msg.m_analyze = analyze; - msg.m_autovacuum = IsAutoVacuumWorkerProcess(); /* is this autovacuum? */ + msg.m_autovacuum = IsAutoVacuumWorkerProcess(); /* is this autovacuum? */ msg.m_vacuumtime = GetCurrentTimestamp(); msg.m_tuples = tuples; pgstat_send(&msg, sizeof(msg)); @@ -1045,7 +1047,7 @@ pgstat_report_analyze(Oid tableoid, bool shared, PgStat_Counter livetuples, pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_ANALYZE); msg.m_databaseid = shared ? InvalidOid : MyDatabaseId; msg.m_tableoid = tableoid; - msg.m_autovacuum = IsAutoVacuumWorkerProcess(); /* is this autovacuum? */ + msg.m_autovacuum = IsAutoVacuumWorkerProcess(); /* is this autovacuum? */ msg.m_analyzetime = GetCurrentTimestamp(); msg.m_live_tuples = livetuples; msg.m_dead_tuples = deadtuples; @@ -1107,8 +1109,8 @@ pgstat_initstats(Relation rel) } /* - * If we already set up this relation in the current transaction, - * nothing to do. + * If we already set up this relation in the current transaction, nothing + * to do. */ if (rel->pgstat_info != NULL && rel->pgstat_info->t_id == rel_id) @@ -1145,9 +1147,9 @@ get_tabstat_entry(Oid rel_id, bool isshared) if (tsa->tsa_used < TABSTAT_QUANTUM) { /* - * It must not be present, but we found a free slot instead. - * Fine, let's use this one. We assume the entry was already - * zeroed, either at creation or after last use. + * It must not be present, but we found a free slot instead. Fine, + * let's use this one. We assume the entry was already zeroed, + * either at creation or after last use. */ entry = &tsa->tsa_entries[tsa->tsa_used++]; entry->t_id = rel_id; @@ -1201,14 +1203,14 @@ get_tabstat_stack_level(int nest_level) * add_tabstat_xact_level - add a new (sub)transaction state record */ static void -add_tabstat_xact_level(PgStat_TableStatus *pgstat_info, int nest_level) +add_tabstat_xact_level(PgStat_TableStatus * pgstat_info, int nest_level) { PgStat_SubXactStatus *xact_state; PgStat_TableXactStatus *trans; /* - * If this is the first rel to be modified at the current nest level, - * we first have to push a transaction stack entry. + * If this is the first rel to be modified at the current nest level, we + * first have to push a transaction stack entry. */ xact_state = get_tabstat_stack_level(nest_level); @@ -1234,7 +1236,7 @@ pgstat_count_heap_insert(Relation rel) if (pgstat_track_counts && pgstat_info != NULL) { - int nest_level = GetCurrentTransactionNestLevel(); + int nest_level = GetCurrentTransactionNestLevel(); /* t_tuples_inserted is nontransactional, so just advance it */ pgstat_info->t_counts.t_tuples_inserted++; @@ -1258,7 +1260,7 @@ pgstat_count_heap_update(Relation rel, bool hot) if (pgstat_track_counts && pgstat_info != NULL) { - int nest_level = GetCurrentTransactionNestLevel(); + int nest_level = GetCurrentTransactionNestLevel(); /* t_tuples_updated is nontransactional, so just advance it */ pgstat_info->t_counts.t_tuples_updated++; @@ -1287,7 +1289,7 @@ pgstat_count_heap_delete(Relation rel) if (pgstat_track_counts && pgstat_info != NULL) { - int nest_level = GetCurrentTransactionNestLevel(); + int nest_level = GetCurrentTransactionNestLevel(); /* t_tuples_deleted is nontransactional, so just advance it */ pgstat_info->t_counts.t_tuples_deleted++; @@ -1341,8 +1343,8 @@ AtEOXact_PgStat(bool isCommit) /* * Transfer transactional insert/update counts into the base tabstat - * entries. We don't bother to free any of the transactional state, - * since it's all in TopTransactionContext and will go away anyway. + * entries. We don't bother to free any of the transactional state, since + * it's all in TopTransactionContext and will go away anyway. */ xact_state = pgStatXactStack; if (xact_state != NULL) @@ -1424,11 +1426,11 @@ AtEOSubXact_PgStat(bool isCommit, int nestDepth) else { /* - * When there isn't an immediate parent state, we can - * just reuse the record instead of going through a + * When there isn't an immediate parent state, we can just + * reuse the record instead of going through a * palloc/pfree pushup (this works since it's all in - * TopTransactionContext anyway). We have to re-link - * it into the parent level, though, and that might mean + * TopTransactionContext anyway). We have to re-link it + * into the parent level, though, and that might mean * pushing a new entry into the pgStatXactStack. */ PgStat_SubXactStatus *upper_xact_state; @@ -1500,7 +1502,7 @@ AtPrepare_PgStat(void) * Clean up after successful PREPARE. * * All we need do here is unlink the transaction stats state from the - * nontransactional state. The nontransactional action counts will be + * nontransactional state. The nontransactional action counts will be * reported to the stats collector immediately, while the effects on live * and dead tuple counts are preserved in the 2PC state file. * @@ -1512,8 +1514,8 @@ PostPrepare_PgStat(void) PgStat_SubXactStatus *xact_state; /* - * We don't bother to free any of the transactional state, - * since it's all in TopTransactionContext and will go away anyway. + * We don't bother to free any of the transactional state, since it's all + * in TopTransactionContext and will go away anyway. */ xact_state = pgStatXactStack; if (xact_state != NULL) @@ -1701,8 +1703,8 @@ pgstat_fetch_stat_numbackends(void) * --------- * pgstat_fetch_global() - * - * Support function for the SQL-callable pgstat* functions. Returns - * a pointer to the global statistics struct. + * Support function for the SQL-callable pgstat* functions. Returns + * a pointer to the global statistics struct. * --------- */ PgStat_GlobalStats * @@ -1795,8 +1797,8 @@ pgstat_bestart(void) volatile PgBackendStatus *beentry; /* - * To minimize the time spent modifying the PgBackendStatus entry, - * fetch all the needed data first. + * To minimize the time spent modifying the PgBackendStatus entry, fetch + * all the needed data first. * * If we have a MyProcPort, use its session start time (for consistency, * and to save a kernel call). @@ -1930,8 +1932,8 @@ pgstat_report_xact_timestamp(TimestampTz tstamp) /* * Update my status entry, following the protocol of bumping - * st_changecount before and after. We use a volatile pointer - * here to ensure the compiler doesn't try to get cute. + * st_changecount before and after. We use a volatile pointer here to + * ensure the compiler doesn't try to get cute. */ beentry->st_changecount++; beentry->st_xact_start_timestamp = tstamp; @@ -2085,7 +2087,7 @@ pgstat_send(void *msg, int len) /* ---------- * pgstat_send_bgwriter() - * - * Send bgwriter statistics to the collector + * Send bgwriter statistics to the collector * ---------- */ void @@ -2095,9 +2097,9 @@ pgstat_send_bgwriter(void) static const PgStat_MsgBgWriter all_zeroes; /* - * This function can be called even if nothing at all has happened. - * In this case, avoid sending a completely empty message to - * the stats collector. + * This function can be called even if nothing at all has happened. In + * this case, avoid sending a completely empty message to the stats + * collector. */ if (memcmp(&BgWriterStats, &all_zeroes, sizeof(PgStat_MsgBgWriter)) == 0) return; @@ -2145,13 +2147,13 @@ PgstatCollectorMain(int argc, char *argv[]) MyProcPid = getpid(); /* reset MyProcPid */ - MyStartTime = time(NULL); /* record Start Time for logging */ + MyStartTime = time(NULL); /* record Start Time for logging */ /* * If possible, make this process a group leader, so that the postmaster - * can signal any child processes too. (pgstat probably never has - * any child processes, but for consistency we make all postmaster - * child processes do this.) + * can signal any child processes too. (pgstat probably never has any + * child processes, but for consistency we make all postmaster child + * processes do this.) */ #ifdef HAVE_SETSID if (setsid() < 0) @@ -2250,8 +2252,8 @@ PgstatCollectorMain(int argc, char *argv[]) * poll/select call, so this also limits speed of response to SIGQUIT, * which is more important.) * - * We use poll(2) if available, otherwise select(2). - * Win32 has its own implementation. + * We use poll(2) if available, otherwise select(2). Win32 has its own + * implementation. */ #ifndef WIN32 #ifdef HAVE_POLL @@ -2291,9 +2293,9 @@ PgstatCollectorMain(int argc, char *argv[]) got_data = FD_ISSET(pgStatSock, &rfds); #endif /* HAVE_POLL */ -#else /* WIN32 */ +#else /* WIN32 */ got_data = pgwin32_waitforsinglesocket(pgStatSock, FD_READ, - PGSTAT_SELECT_TIMEOUT*1000); + PGSTAT_SELECT_TIMEOUT * 1000); #endif /* @@ -2363,7 +2365,7 @@ PgstatCollectorMain(int argc, char *argv[]) break; case PGSTAT_MTYPE_BGWRITER: - pgstat_recv_bgwriter((PgStat_MsgBgWriter *) &msg, len); + pgstat_recv_bgwriter((PgStat_MsgBgWriter *) & msg, len); break; default: @@ -2704,7 +2706,7 @@ pgstat_read_statsfile(Oid onlydb) dbentry->tables = hash_create("Per-database table", PGSTAT_TAB_HASH_SIZE, &hash_ctl, - HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT); + HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT); /* * Arrange that following 'T's add entries to this database's @@ -2813,7 +2815,7 @@ pgstat_setup_memcxt(void) /* ---------- * pgstat_clear_snapshot() - * - * Discard any data collected in the current transaction. Any subsequent + * Discard any data collected in the current transaction. Any subsequent * request will cause new snapshots to be read. * * This is also invoked during transaction commit or abort to discard @@ -3158,7 +3160,7 @@ pgstat_recv_analyze(PgStat_MsgAnalyze *msg, int len) * ---------- */ static void -pgstat_recv_bgwriter(PgStat_MsgBgWriter *msg, int len) +pgstat_recv_bgwriter(PgStat_MsgBgWriter * msg, int len) { globalStats.timed_checkpoints += msg->m_timed_checkpoints; globalStats.requested_checkpoints += msg->m_requested_checkpoints; diff --git a/src/backend/postmaster/postmaster.c b/src/backend/postmaster/postmaster.c index 9af6526159..c83e4e73d8 100644 --- a/src/backend/postmaster/postmaster.c +++ b/src/backend/postmaster/postmaster.c @@ -37,7 +37,7 @@ * * * IDENTIFICATION - * $PostgreSQL: pgsql/src/backend/postmaster/postmaster.c,v 1.546 2007/11/15 20:04:38 petere Exp $ + * $PostgreSQL: pgsql/src/backend/postmaster/postmaster.c,v 1.547 2007/11/15 21:14:37 momjian Exp $ * * NOTES * @@ -130,10 +130,10 @@ * children we have and send them appropriate signals when necessary. * * "Special" children such as the startup, bgwriter and autovacuum launcher - * tasks are not in this list. Autovacuum worker processes are in it. + * tasks are not in this list. Autovacuum worker processes are in it. * Also, "dead_end" children are in it: these are children launched just * for the purpose of sending a friendly rejection message to a would-be - * client. We must track them because they are attached to shared memory, + * client. We must track them because they are attached to shared memory, * but we know they will never become live backends. */ typedef struct bkend @@ -189,7 +189,7 @@ static char ExtraOptions[MAXPGPATH]; * backend dumps core. Normally, it kills all peers of the dead backend * and reinitializes shared memory. By specifying -s or -n, we can have * the postmaster stop (rather than kill) peers and not reinitialize - * shared data structures. (Reinit is currently dead code, though.) + * shared data structures. (Reinit is currently dead code, though.) */ static bool Reinit = true; static int SendStop = false; @@ -213,8 +213,8 @@ static pid_t StartupPID = 0, WalWriterPID = 0, AutoVacPID = 0, PgArchPID = 0, - PgStatPID = 0, - SysLoggerPID = 0; + PgStatPID = 0, + SysLoggerPID = 0; /* Startup/shutdown state */ #define NoShutdown 0 @@ -243,12 +243,13 @@ static bool FatalError = false; /* T if recovering from backend crash */ * * Notice that this state variable does not distinguish *why* we entered * PM_WAIT_BACKENDS or later states --- Shutdown and FatalError must be - * consulted to find that out. FatalError is never true in PM_RUN state, nor + * consulted to find that out. FatalError is never true in PM_RUN state, nor * in PM_SHUTDOWN state (because we don't enter that state when trying to * recover from a crash). It can be true in PM_STARTUP state, because we * don't clear it until we've successfully recovered. */ -typedef enum { +typedef enum +{ PM_INIT, /* postmaster starting */ PM_STARTUP, /* waiting for startup subprocess */ PM_RUN, /* normal "database is alive" state */ @@ -256,14 +257,14 @@ typedef enum { PM_SHUTDOWN, /* waiting for bgwriter to do shutdown ckpt */ PM_WAIT_DEAD_END, /* waiting for dead_end children to exit */ PM_NO_CHILDREN /* all important children have exited */ -} PMState; +} PMState; static PMState pmState = PM_INIT; bool ClientAuthInProgress = false; /* T during new-client * authentication */ -bool redirection_done = false; /* stderr redirected for syslogger? */ +bool redirection_done = false; /* stderr redirected for syslogger? */ /* received START_AUTOVAC_LAUNCHER signal */ static volatile sig_atomic_t start_autovac_launcher = false; @@ -321,6 +322,7 @@ static long PostmasterRandom(void); static void RandomSalt(char *cryptSalt, char *md5Salt); static void signal_child(pid_t pid, int signal); static void SignalSomeChildren(int signal, bool only_autovac); + #define SignalChildren(sig) SignalSomeChildren(sig, false) #define SignalAutovacWorkers(sig) SignalSomeChildren(sig, true) static int CountChildren(void); @@ -336,12 +338,12 @@ static void WINAPI pgwin32_deadchild_callback(PVOID lpParameter, BOOLEAN TimerOr static HANDLE win32ChildQueue; -typedef struct +typedef struct { - HANDLE waitHandle; - HANDLE procHandle; - DWORD procId; -} win32_deadchild_waitinfo; + HANDLE waitHandle; + HANDLE procHandle; + DWORD procId; +} win32_deadchild_waitinfo; HANDLE PostmasterHandle; #endif @@ -385,7 +387,7 @@ typedef struct InheritableSocket pgStatSock; pid_t PostmasterPid; TimestampTz PgStartTime; - bool redirection_done; + bool redirection_done; #ifdef WIN32 HANDLE PostmasterHandle; HANDLE initial_signal_pipe; @@ -477,9 +479,9 @@ PostmasterMain(int argc, char *argv[]) opterr = 1; /* - * Parse command-line options. CAUTION: keep this in sync with - * tcop/postgres.c (the option sets should not conflict) - * and with the common help() function in main/main.c. + * Parse command-line options. CAUTION: keep this in sync with + * tcop/postgres.c (the option sets should not conflict) and with the + * common help() function in main/main.c. */ while ((opt = getopt(argc, argv, "A:B:c:D:d:EeFf:h:ijk:lN:nOo:Pp:r:S:sTt:W:-:")) != -1) { @@ -907,7 +909,7 @@ PostmasterMain(int argc, char *argv[]) win32ChildQueue = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1); if (win32ChildQueue == NULL) ereport(FATAL, - (errmsg("could not create I/O completion port for child queue"))); + (errmsg("could not create I/O completion port for child queue"))); /* * Set up a handle that child processes can use to check whether the @@ -1158,8 +1160,8 @@ pmdaemonize(void) MyStartTime = time(NULL); /* - * GH: If there's no setsid(), we hopefully don't need silent mode. - * Until there's a better solution. + * GH: If there's no setsid(), we hopefully don't need silent mode. Until + * there's a better solution. */ #ifdef HAVE_SETSID if (setsid() < 0) @@ -1207,9 +1209,9 @@ ServerLoop(void) * We wait at most one minute, to ensure that the other background * tasks handled below get done even when no requests are arriving. * - * If we are in PM_WAIT_DEAD_END state, then we don't want to - * accept any new connections, so we don't call select() at all; - * just sleep for a little bit with signals unblocked. + * If we are in PM_WAIT_DEAD_END state, then we don't want to accept + * any new connections, so we don't call select() at all; just sleep + * for a little bit with signals unblocked. */ memcpy((char *) &rmask, (char *) &readmask, sizeof(fd_set)); @@ -1217,7 +1219,7 @@ ServerLoop(void) if (pmState == PM_WAIT_DEAD_END) { - pg_usleep(100000L); /* 100 msec seems reasonable */ + pg_usleep(100000L); /* 100 msec seems reasonable */ selres = 0; } else @@ -1294,8 +1296,8 @@ ServerLoop(void) BgWriterPID = StartBackgroundWriter(); /* - * Likewise, if we have lost the walwriter process, try to start a - * new one. + * Likewise, if we have lost the walwriter process, try to start a new + * one. */ if (WalWriterPID == 0 && pmState == PM_RUN) WalWriterPID = StartWalWriter(); @@ -1307,13 +1309,13 @@ ServerLoop(void) { AutoVacPID = StartAutoVacLauncher(); if (AutoVacPID != 0) - start_autovac_launcher = false; /* signal processed */ + start_autovac_launcher = false; /* signal processed */ } - /* - * If we have lost the archiver, try to start a new one. - * We do this even if we are shutting down, to allow archiver to - * take care of any remaining WAL files. + /* + * If we have lost the archiver, try to start a new one. We do this + * even if we are shutting down, to allow archiver to take care of any + * remaining WAL files. */ if (XLogArchivingActive() && PgArchPID == 0 && pmState >= PM_RUN) PgArchPID = pgarch_start(); @@ -1732,10 +1734,10 @@ canAcceptConnections(void) if (pmState != PM_RUN) { if (Shutdown > NoShutdown) - return CAC_SHUTDOWN; /* shutdown is pending */ + return CAC_SHUTDOWN; /* shutdown is pending */ if (pmState == PM_STARTUP && !FatalError) - return CAC_STARTUP; /* normal startup */ - return CAC_RECOVERY; /* else must be crash recovery */ + return CAC_STARTUP; /* normal startup */ + return CAC_RECOVERY; /* else must be crash recovery */ } /* @@ -1793,11 +1795,11 @@ ConnCreate(int serverFd) } /* - * Allocate GSSAPI specific state struct + * Allocate GSSAPI specific state struct */ #ifndef EXEC_BACKEND -#if defined(ENABLE_GSS) || defined(ENABLE_SSPI) - port->gss = (pg_gssinfo *)calloc(1, sizeof(pg_gssinfo)); +#if defined(ENABLE_GSS) || defined(ENABLE_SSPI) + port->gss = (pg_gssinfo *) calloc(1, sizeof(pg_gssinfo)); if (!port->gss) { ereport(LOG, @@ -2062,14 +2064,16 @@ reaper(SIGNAL_ARGS) /* These macros hide platform variations in getting child status */ #ifdef HAVE_WAITPID int status; /* child exit status */ + #define LOOPTEST() ((pid = waitpid(-1, &status, WNOHANG)) > 0) #define LOOPHEADER() (exitstatus = status) -#else /* !HAVE_WAITPID */ +#else /* !HAVE_WAITPID */ #ifndef WIN32 union wait status; /* child exit status */ + #define LOOPTEST() ((pid = wait3(&status, WNOHANG, NULL)) > 0) #define LOOPHEADER() (exitstatus = status.w_status) -#else /* WIN32 */ +#else /* WIN32 */ #define LOOPTEST() ((pid = win32_waitpid(&exitstatus)) > 0) #define LOOPHEADER() #endif /* WIN32 */ @@ -2152,7 +2156,7 @@ reaper(SIGNAL_ARGS) /* at this point we are really open for business */ ereport(LOG, - (errmsg("database system is ready to accept connections"))); + (errmsg("database system is ready to accept connections"))); continue; } @@ -2166,13 +2170,13 @@ reaper(SIGNAL_ARGS) if (EXIT_STATUS_0(exitstatus) && pmState == PM_SHUTDOWN) { /* - * OK, we saw normal exit of the bgwriter after it's been - * told to shut down. We expect that it wrote a shutdown - * checkpoint. (If for some reason it didn't, recovery will + * OK, we saw normal exit of the bgwriter after it's been told + * to shut down. We expect that it wrote a shutdown + * checkpoint. (If for some reason it didn't, recovery will * occur on next postmaster start.) * - * At this point we should have no normal children left - * (else we'd not be in PM_SHUTDOWN state) but we might have + * At this point we should have no normal children left (else + * we'd not be in PM_SHUTDOWN state) but we might have * dead_end children. */ Assert(Shutdown > NoShutdown); @@ -2192,9 +2196,9 @@ reaper(SIGNAL_ARGS) } /* - * Was it the wal writer? Normal exit can be ignored; we'll - * start a new one at the next iteration of the postmaster's main loop, - * if necessary. Any other exit condition is treated as a crash. + * Was it the wal writer? Normal exit can be ignored; we'll start a + * new one at the next iteration of the postmaster's main loop, if + * necessary. Any other exit condition is treated as a crash. */ if (pid == WalWriterPID) { @@ -2206,9 +2210,10 @@ reaper(SIGNAL_ARGS) } /* - * Was it the autovacuum launcher? Normal exit can be ignored; we'll - * start a new one at the next iteration of the postmaster's main loop, - * if necessary. Any other exit condition is treated as a crash. + * Was it the autovacuum launcher? Normal exit can be ignored; we'll + * start a new one at the next iteration of the postmaster's main + * loop, if necessary. Any other exit condition is treated as a + * crash. */ if (pid == AutoVacPID) { @@ -2433,8 +2438,8 @@ HandleChildCrash(int pid, int exitstatus, const char *procname) /* * Force a power-cycle of the pgarch process too. (This isn't absolutely * necessary, but it seems like a good idea for robustness, and it - * simplifies the state-machine logic in the case where a shutdown - * request arrives during crash processing.) + * simplifies the state-machine logic in the case where a shutdown request + * arrives during crash processing.) */ if (PgArchPID != 0 && !FatalError) { @@ -2448,8 +2453,8 @@ HandleChildCrash(int pid, int exitstatus, const char *procname) /* * Force a power-cycle of the pgstat process too. (This isn't absolutely * necessary, but it seems like a good idea for robustness, and it - * simplifies the state-machine logic in the case where a shutdown - * request arrives during crash processing.) + * simplifies the state-machine logic in the case where a shutdown request + * arrives during crash processing.) */ if (PgStatPID != 0 && !FatalError) { @@ -2494,15 +2499,15 @@ LogChildExit(int lev, const char *procname, int pid, int exitstatus) procname, pid, WTERMSIG(exitstatus)), errhint("See C include file \"ntstatus.h\" for a description of the hexadecimal value."))); #elif defined(HAVE_DECL_SYS_SIGLIST) && HAVE_DECL_SYS_SIGLIST - ereport(lev, - - /*------ - translator: %s is a noun phrase describing a child process, such as - "server process" */ - (errmsg("%s (PID %d) was terminated by signal %d: %s", - procname, pid, WTERMSIG(exitstatus), - WTERMSIG(exitstatus) < NSIG ? - sys_siglist[WTERMSIG(exitstatus)] : "(unknown)"))); + ereport(lev, + + /*------ + translator: %s is a noun phrase describing a child process, such as + "server process" */ + (errmsg("%s (PID %d) was terminated by signal %d: %s", + procname, pid, WTERMSIG(exitstatus), + WTERMSIG(exitstatus) < NSIG ? + sys_siglist[WTERMSIG(exitstatus)] : "(unknown)"))); #else ereport(lev, @@ -2532,18 +2537,18 @@ static void PostmasterStateMachine(void) { /* - * If we are in a state-machine state that implies waiting for backends - * to exit, see if they're all gone, and change state if so. + * If we are in a state-machine state that implies waiting for backends to + * exit, see if they're all gone, and change state if so. */ if (pmState == PM_WAIT_BACKENDS) { /* * PM_WAIT_BACKENDS state ends when we have no regular backends * (including autovac workers) and no walwriter or autovac launcher. - * If we are doing crash recovery then we expect the bgwriter to - * exit too, otherwise not. The archiver, stats, and syslogger - * processes are disregarded since they are not connected to shared - * memory; we also disregard dead_end children here. + * If we are doing crash recovery then we expect the bgwriter to exit + * too, otherwise not. The archiver, stats, and syslogger processes + * are disregarded since they are not connected to shared memory; we + * also disregard dead_end children here. */ if (CountChildren() == 0 && StartupPID == 0 && @@ -2554,7 +2559,7 @@ PostmasterStateMachine(void) if (FatalError) { /* - * Start waiting for dead_end children to die. This state + * Start waiting for dead_end children to die. This state * change causes ServerLoop to stop creating new ones. */ pmState = PM_WAIT_DEAD_END; @@ -2562,9 +2567,9 @@ PostmasterStateMachine(void) else { /* - * If we get here, we are proceeding with normal shutdown. - * All the regular children are gone, and it's time to tell - * the bgwriter to do a shutdown checkpoint. + * If we get here, we are proceeding with normal shutdown. All + * the regular children are gone, and it's time to tell the + * bgwriter to do a shutdown checkpoint. */ Assert(Shutdown > NoShutdown); /* Start the bgwriter if not running */ @@ -2579,10 +2584,10 @@ PostmasterStateMachine(void) else { /* - * If we failed to fork a bgwriter, just shut down. - * Any required cleanup will happen at next restart. - * We set FatalError so that an "abnormal shutdown" - * message gets logged when we exit. + * If we failed to fork a bgwriter, just shut down. Any + * required cleanup will happen at next restart. We set + * FatalError so that an "abnormal shutdown" message gets + * logged when we exit. */ FatalError = true; pmState = PM_WAIT_DEAD_END; @@ -2600,8 +2605,8 @@ PostmasterStateMachine(void) if (pmState == PM_WAIT_DEAD_END) { /* - * PM_WAIT_DEAD_END state ends when the BackendList is entirely - * empty (ie, no dead_end children remain). + * PM_WAIT_DEAD_END state ends when the BackendList is entirely empty + * (ie, no dead_end children remain). */ if (!DLGetHead(BackendList)) { @@ -2617,7 +2622,7 @@ PostmasterStateMachine(void) /* * If we've been told to shut down, we exit as soon as there are no - * remaining children. If there was a crash, cleanup will occur at the + * remaining children. If there was a crash, cleanup will occur at the * next startup. (Before PostgreSQL 8.3, we tried to recover from the * crash before exiting, but that seems unwise if we are quitting because * we got SIGTERM from init --- there may well not be time for recovery @@ -2627,7 +2632,7 @@ PostmasterStateMachine(void) * processes. They've been sent SIGQUIT by this point (either when we * entered PM_SHUTDOWN state, or when we set FatalError, and at least one * of those must have happened by now). In any case they contain logic to - * commit hara-kiri if they notice the postmaster is gone. Since they + * commit hara-kiri if they notice the postmaster is gone. Since they * aren't connected to shared memory, they pose no problem for shutdown. * The syslogger is not considered either, since it's intended to survive * till the postmaster exits. @@ -2648,7 +2653,7 @@ PostmasterStateMachine(void) /* * If we need to recover from a crash, wait for all shmem-connected - * children to exit, then reset shmem and StartupDataBase. (We can ignore + * children to exit, then reset shmem and StartupDataBase. (We can ignore * the archiver and stats processes here since they are not connected to * shmem.) */ @@ -2678,7 +2683,7 @@ PostmasterStateMachine(void) * system(). * * There is a race condition for recently-forked children: they might not - * have executed setsid() yet. So we signal the child directly as well as + * have executed setsid() yet. So we signal the child directly as well as * the group. We assume such a child will handle the signal before trying * to spawn any grandchild processes. We also assume that signaling the * child twice will not cause any problems. @@ -2945,7 +2950,7 @@ BackendInitialize(Port *port) /* * If possible, make this process a group leader, so that the postmaster - * can signal any child processes too. (We do this now on the off chance + * can signal any child processes too. (We do this now on the off chance * that something might spawn a child process during authentication.) */ #ifdef HAVE_SETSID @@ -3448,17 +3453,18 @@ internal_forkexec(int argc, char *argv[], Port *port) } /* - * Queue a waiter for to signal when this child dies. The wait will be handled automatically - * by an operating system thread pool. + * Queue a waiter for to signal when this child dies. The wait will be + * handled automatically by an operating system thread pool. * - * Note: use malloc instead of palloc, since it needs to be thread-safe. Struct will be - * free():d from the callback function that runs on a different thread. + * Note: use malloc instead of palloc, since it needs to be thread-safe. + * Struct will be free():d from the callback function that runs on a + * different thread. */ childinfo = malloc(sizeof(win32_deadchild_waitinfo)); if (!childinfo) ereport(FATAL, - (errcode(ERRCODE_OUT_OF_MEMORY), - errmsg("out of memory"))); + (errcode(ERRCODE_OUT_OF_MEMORY), + errmsg("out of memory"))); childinfo->procHandle = pi.hProcess; childinfo->procId = pi.dwProcessId; @@ -3468,10 +3474,10 @@ internal_forkexec(int argc, char *argv[], Port *port) pgwin32_deadchild_callback, childinfo, INFINITE, - WT_EXECUTEONLYONCE | WT_EXECUTEINWAITTHREAD)) + WT_EXECUTEONLYONCE | WT_EXECUTEINWAITTHREAD)) ereport(FATAL, - (errmsg_internal("could not register process for wait: error code %d", - (int) GetLastError()))); + (errmsg_internal("could not register process for wait: error code %d", + (int) GetLastError()))); /* Don't close pi.hProcess here - the wait thread needs access to it */ @@ -3505,13 +3511,14 @@ SubPostmasterMain(int argc, char *argv[]) MyStartTime = time(NULL); - /* make sure stderr is in binary mode before anything can - * possibly be written to it, in case it's actually the syslogger pipe, - * so the pipe chunking protocol isn't disturbed. Non-logpipe data - * gets translated on redirection (e.g. via pg_ctl -l) anyway. + /* + * make sure stderr is in binary mode before anything can possibly be + * written to it, in case it's actually the syslogger pipe, so the pipe + * chunking protocol isn't disturbed. Non-logpipe data gets translated on + * redirection (e.g. via pg_ctl -l) anyway. */ #ifdef WIN32 - _setmode(fileno(stderr),_O_BINARY); + _setmode(fileno(stderr), _O_BINARY); #endif /* Lose the postmaster's on-exit routines (really a no-op) */ @@ -3529,12 +3536,12 @@ SubPostmasterMain(int argc, char *argv[]) memset(&port, 0, sizeof(Port)); read_backend_variables(argv[2], &port); - /* - * Set up memory area for GSS information. Mirrors the code in - * ConnCreate for the non-exec case. + /* + * Set up memory area for GSS information. Mirrors the code in ConnCreate + * for the non-exec case. */ #if defined(ENABLE_GSS) || defined(ENABLE_SSPI) - port.gss = (pg_gssinfo *)calloc(1, sizeof(pg_gssinfo)); + port.gss = (pg_gssinfo *) calloc(1, sizeof(pg_gssinfo)); if (!port.gss) ereport(FATAL, (errcode(ERRCODE_OUT_OF_MEMORY), @@ -3601,8 +3608,8 @@ SubPostmasterMain(int argc, char *argv[]) * process any libraries that should be preloaded at postmaster start * * NOTE: we have to re-load the shared_preload_libraries here because - * this backend is not fork()ed so we can't inherit any shared - * libraries / DLL's from our parent (the postmaster). + * this backend is not fork()ed so we can't inherit any shared + * libraries / DLL's from our parent (the postmaster). */ process_shared_preload_libraries(); @@ -3899,6 +3906,7 @@ PostmasterRandom(void) struct timeval random_stop_time; gettimeofday(&random_stop_time, NULL); + /* * We are not sure how much precision is in tv_usec, so we swap * the high and low 16 bits of 'random_stop_time' and XOR them @@ -4014,7 +4022,7 @@ StartChildProcess(AuxProcType type) break; case WalWriterProcess: ereport(LOG, - (errmsg("could not fork WAL writer process: %m"))); + (errmsg("could not fork WAL writer process: %m"))); break; default: ereport(LOG, @@ -4049,7 +4057,7 @@ StartChildProcess(AuxProcType type) static void StartAutovacuumWorker(void) { - Backend *bn; + Backend *bn; /* * If not in condition to run a process, don't try, but handle it like a @@ -4061,8 +4069,8 @@ StartAutovacuumWorker(void) if (canAcceptConnections() == CAC_OK) { /* - * Compute the cancel key that will be assigned to this session. - * We probably don't need cancel keys for autovac workers, but we'd + * Compute the cancel key that will be assigned to this session. We + * probably don't need cancel keys for autovac workers, but we'd * better have something random in the field to prevent unfriendly * people from sending cancels to them. */ @@ -4098,9 +4106,9 @@ StartAutovacuumWorker(void) } /* - * Report the failure to the launcher, if it's running. (If it's not, - * we might not even be connected to shared memory, so don't try to - * call AutoVacWorkerFailed.) + * Report the failure to the launcher, if it's running. (If it's not, we + * might not even be connected to shared memory, so don't try to call + * AutoVacWorkerFailed.) */ if (AutoVacPID != 0) { @@ -4487,16 +4495,17 @@ ShmemBackendArrayRemove(pid_t pid) static pid_t win32_waitpid(int *exitstatus) { - DWORD dwd; - ULONG_PTR key; - OVERLAPPED* ovl; + DWORD dwd; + ULONG_PTR key; + OVERLAPPED *ovl; /* - * Check if there are any dead children. If there are, return the pid of the first one that died. + * Check if there are any dead children. If there are, return the pid of + * the first one that died. */ if (GetQueuedCompletionStatus(win32ChildQueue, &dwd, &key, &ovl, 0)) { - *exitstatus = (int)key; + *exitstatus = (int) key; return dwd; } @@ -4510,13 +4519,17 @@ win32_waitpid(int *exitstatus) static void WINAPI pgwin32_deadchild_callback(PVOID lpParameter, BOOLEAN TimerOrWaitFired) { - win32_deadchild_waitinfo *childinfo = (win32_deadchild_waitinfo *)lpParameter; + win32_deadchild_waitinfo *childinfo = (win32_deadchild_waitinfo *) lpParameter; DWORD exitcode; if (TimerOrWaitFired) - return; /* timeout. Should never happen, since we use INFINITE as timeout value. */ + return; /* timeout. Should never happen, since we use + * INFINITE as timeout value. */ - /* Remove handle from wait - required even though it's set to wait only once */ + /* + * Remove handle from wait - required even though it's set to wait only + * once + */ UnregisterWaitEx(childinfo->waitHandle, NULL); if (!GetExitCodeProcess(childinfo->procHandle, &exitcode)) @@ -4528,13 +4541,19 @@ pgwin32_deadchild_callback(PVOID lpParameter, BOOLEAN TimerOrWaitFired) exitcode = 255; } - if (!PostQueuedCompletionStatus(win32ChildQueue, childinfo->procId, (ULONG_PTR)exitcode, NULL)) + if (!PostQueuedCompletionStatus(win32ChildQueue, childinfo->procId, (ULONG_PTR) exitcode, NULL)) write_stderr("could not post child completion status\n"); - /* Handle is per-process, so we close it here instead of in the originating thread */ + /* + * Handle is per-process, so we close it here instead of in the + * originating thread + */ CloseHandle(childinfo->procHandle); - /* Free struct that was allocated before the call to RegisterWaitForSingleObject() */ + /* + * Free struct that was allocated before the call to + * RegisterWaitForSingleObject() + */ free(childinfo); /* Queue SIGCHLD signal */ diff --git a/src/backend/postmaster/syslogger.c b/src/backend/postmaster/syslogger.c index 8ac38f0baa..0a255b5e07 100644 --- a/src/backend/postmaster/syslogger.c +++ b/src/backend/postmaster/syslogger.c @@ -18,7 +18,7 @@ * * * IDENTIFICATION - * $PostgreSQL: pgsql/src/backend/postmaster/syslogger.c,v 1.40 2007/09/22 18:19:18 tgl Exp $ + * $PostgreSQL: pgsql/src/backend/postmaster/syslogger.c,v 1.41 2007/11/15 21:14:37 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -55,7 +55,7 @@ #define LBF_MODE _IOLBF #endif -/* +/* * We read() into a temp buffer twice as big as a chunk, so that any fragment * left after processing can be moved down to the front and we'll still have * room to read a full chunk. @@ -91,7 +91,7 @@ static FILE *csvlogFile = NULL; static char *last_file_name = NULL; static char *last_csvfile_name = NULL; -/* +/* * Buffers for saving partial messages from different backends. We don't expect * that there will be very many outstanding at one time, so 20 seems plenty of * leeway. If this array gets full we won't lose messages, but we will lose @@ -101,9 +101,9 @@ static char *last_csvfile_name = NULL; */ typedef struct { - int32 pid; /* PID of source process */ + int32 pid; /* PID of source process */ StringInfoData data; /* accumulated data, as a StringInfo */ -} save_buffer; +} save_buffer; #define CHUNK_SLOTS 20 static save_buffer saved_chunks[CHUNK_SLOTS]; @@ -140,7 +140,7 @@ static void open_csvlogfile(void); static unsigned int __stdcall pipeThread(void *arg); #endif static void logfile_rotate(bool time_based_rotation, int size_rotation_for); -static char *logfile_getname(pg_time_t timestamp, char * suffix); +static char *logfile_getname(pg_time_t timestamp, char *suffix); static void set_next_rotation_time(void); static void sigHupHandler(SIGNAL_ARGS); static void sigUsr1Handler(SIGNAL_ARGS); @@ -165,7 +165,7 @@ SysLoggerMain(int argc, char *argv[]) MyProcPid = getpid(); /* reset MyProcPid */ - MyStartTime = time(NULL); /* set our start time in case we call elog */ + MyStartTime = time(NULL); /* set our start time in case we call elog */ #ifdef EXEC_BACKEND syslogger_parseArgs(argc, argv); @@ -199,13 +199,14 @@ SysLoggerMain(int argc, char *argv[]) close(fd); } - /* Syslogger's own stderr can't be the syslogPipe, so set it back to - * text mode if we didn't just close it. - * (It was set to binary in SubPostmasterMain). + /* + * Syslogger's own stderr can't be the syslogPipe, so set it back to text + * mode if we didn't just close it. (It was set to binary in + * SubPostmasterMain). */ #ifdef WIN32 else - _setmode(_fileno(stderr),_O_TEXT); + _setmode(_fileno(stderr), _O_TEXT); #endif /* @@ -225,9 +226,9 @@ SysLoggerMain(int argc, char *argv[]) /* * If possible, make this process a group leader, so that the postmaster - * can signal any child processes too. (syslogger probably never has - * any child processes, but for consistency we make all postmaster - * child processes do this.) + * can signal any child processes too. (syslogger probably never has any + * child processes, but for consistency we make all postmaster child + * processes do this.) */ #ifdef HAVE_SETSID if (setsid() < 0) @@ -284,7 +285,8 @@ SysLoggerMain(int argc, char *argv[]) for (;;) { bool time_based_rotation = false; - int size_rotation_for = 0; + int size_rotation_for = 0; + #ifndef WIN32 int bytesRead; int rc; @@ -348,14 +350,14 @@ SysLoggerMain(int argc, char *argv[]) rotation_requested = true; size_rotation_for |= LOG_DESTINATION_CSVLOG; } - + } if (rotation_requested) { /* - * Force rotation when both values are zero. - * It means the request was sent by pg_rotate_logfile. + * Force rotation when both values are zero. It means the request + * was sent by pg_rotate_logfile. */ if (!time_based_rotation && size_rotation_for == 0) size_rotation_for = LOG_DESTINATION_STDERR | LOG_DESTINATION_CSVLOG; @@ -425,8 +427,9 @@ SysLoggerMain(int argc, char *argv[]) if (pipe_eof_seen) { - /* seeing this message on the real stderr is annoying - so we - * make it DEBUG1 to suppress in normal use. + /* + * seeing this message on the real stderr is annoying - so we make + * it DEBUG1 to suppress in normal use. */ ereport(DEBUG1, (errmsg("logger shutting down"))); @@ -566,9 +569,9 @@ SysLogger_Start(void) int fd; /* - * open the pipe in binary mode and make sure - * stderr is binary after it's been dup'ed into, to avoid - * disturbing the pipe chunking protocol. + * open the pipe in binary mode and make sure stderr is binary + * after it's been dup'ed into, to avoid disturbing the pipe + * chunking protocol. */ fflush(stderr); fd = _open_osfhandle((long) syslogPipe[1], @@ -578,7 +581,7 @@ SysLogger_Start(void) (errcode_for_file_access(), errmsg("could not redirect stderr: %m"))); close(fd); - _setmode(_fileno(stderr),_O_BINARY); + _setmode(_fileno(stderr), _O_BINARY); /* Now we are done with the write end of the pipe. */ CloseHandle(syslogPipe[1]); syslogPipe[1] = 0; @@ -682,10 +685,10 @@ syslogger_parseArgs(int argc, char *argv[]) * Process data received through the syslogger pipe. * * This routine interprets the log pipe protocol which sends log messages as - * (hopefully atomic) chunks - such chunks are detected and reassembled here. + * (hopefully atomic) chunks - such chunks are detected and reassembled here. * * The protocol has a header that starts with two nul bytes, then has a 16 bit - * length, the pid of the sending process, and a flag to indicate if it is + * length, the pid of the sending process, and a flag to indicate if it is * the last chunk in a message. Incomplete chunks are saved until we read some * more, and non-final chunks are accumulated until we get the final chunk. * @@ -704,23 +707,23 @@ syslogger_parseArgs(int argc, char *argv[]) static void process_pipe_input(char *logbuffer, int *bytes_in_logbuffer) { - char *cursor = logbuffer; - int count = *bytes_in_logbuffer; - int dest = LOG_DESTINATION_STDERR; + char *cursor = logbuffer; + int count = *bytes_in_logbuffer; + int dest = LOG_DESTINATION_STDERR; /* While we have enough for a header, process data... */ while (count >= (int) sizeof(PipeProtoHeader)) { PipeProtoHeader p; - int chunklen; + int chunklen; /* Do we have a valid header? */ memcpy(&p, cursor, sizeof(PipeProtoHeader)); if (p.nuls[0] == '\0' && p.nuls[1] == '\0' && p.len > 0 && p.len <= PIPE_MAX_PAYLOAD && p.pid != 0 && - (p.is_last == 't' || p.is_last == 'f' || - p.is_last == 'T' || p.is_last == 'F' )) + (p.is_last == 't' || p.is_last == 'f' || + p.is_last == 'T' || p.is_last == 'F')) { chunklen = PIPE_HEADER_SIZE + p.len; @@ -728,18 +731,19 @@ process_pipe_input(char *logbuffer, int *bytes_in_logbuffer) if (count < chunklen) break; - dest = (p.is_last == 'T' || p.is_last == 'F' ) ? + dest = (p.is_last == 'T' || p.is_last == 'F') ? LOG_DESTINATION_CSVLOG : LOG_DESTINATION_STDERR; if (p.is_last == 'f' || p.is_last == 'F') { - /* - * Save a complete non-final chunk in the per-pid buffer - * if possible - if not just write it out. + /* + * Save a complete non-final chunk in the per-pid buffer if + * possible - if not just write it out. */ - int free_slot = -1, existing_slot = -1; - int i; - StringInfo str; + int free_slot = -1, + existing_slot = -1; + int i; + StringInfo str; for (i = 0; i < CHUNK_SLOTS; i++) { @@ -755,7 +759,7 @@ process_pipe_input(char *logbuffer, int *bytes_in_logbuffer) { str = &(saved_chunks[existing_slot].data); appendBinaryStringInfo(str, - cursor + PIPE_HEADER_SIZE, + cursor + PIPE_HEADER_SIZE, p.len); } else if (free_slot >= 0) @@ -764,29 +768,29 @@ process_pipe_input(char *logbuffer, int *bytes_in_logbuffer) str = &(saved_chunks[free_slot].data); initStringInfo(str); appendBinaryStringInfo(str, - cursor + PIPE_HEADER_SIZE, + cursor + PIPE_HEADER_SIZE, p.len); } else { - /* + /* * If there is no free slot we'll just have to take our * chances and write out a partial message and hope that * it's not followed by something from another pid. */ - write_syslogger_file(cursor + PIPE_HEADER_SIZE, p.len, + write_syslogger_file(cursor + PIPE_HEADER_SIZE, p.len, dest); } } else { - /* + /* * Final chunk --- add it to anything saved for that pid, and * either way write the whole thing out. */ - int existing_slot = -1; - int i; - StringInfo str; + int existing_slot = -1; + int i; + StringInfo str; for (i = 0; i < CHUNK_SLOTS; i++) { @@ -810,7 +814,7 @@ process_pipe_input(char *logbuffer, int *bytes_in_logbuffer) { /* The whole message was one chunk, evidently. */ write_syslogger_file(cursor + PIPE_HEADER_SIZE, p.len, - dest); + dest); } } @@ -818,18 +822,18 @@ process_pipe_input(char *logbuffer, int *bytes_in_logbuffer) cursor += chunklen; count -= chunklen; } - else + else { /* Process non-protocol data */ /* * Look for the start of a protocol header. If found, dump data * up to there and repeat the loop. Otherwise, dump it all and - * fall out of the loop. (Note: we want to dump it all if - * at all possible, so as to avoid dividing non-protocol messages - * across logfiles. We expect that in many scenarios, a - * non-protocol message will arrive all in one read(), and we - * want to respect the read() boundary if possible.) + * fall out of the loop. (Note: we want to dump it all if at all + * possible, so as to avoid dividing non-protocol messages across + * logfiles. We expect that in many scenarios, a non-protocol + * message will arrive all in one read(), and we want to respect + * the read() boundary if possible.) */ for (chunklen = 1; chunklen < count; chunklen++) { @@ -858,8 +862,8 @@ process_pipe_input(char *logbuffer, int *bytes_in_logbuffer) static void flush_pipe_input(char *logbuffer, int *bytes_in_logbuffer) { - int i; - StringInfo str; + int i; + StringInfo str; /* Dump any incomplete protocol messages */ for (i = 0; i < CHUNK_SLOTS; i++) @@ -872,12 +876,13 @@ flush_pipe_input(char *logbuffer, int *bytes_in_logbuffer) pfree(str->data); } } + /* * Force out any remaining pipe data as-is; we don't bother trying to * remove any protocol headers that may exist in it. */ if (*bytes_in_logbuffer > 0) - write_syslogger_file(logbuffer, *bytes_in_logbuffer, + write_syslogger_file(logbuffer, *bytes_in_logbuffer, LOG_DESTINATION_STDERR); *bytes_in_logbuffer = 0; } @@ -899,12 +904,12 @@ void write_syslogger_file(const char *buffer, int count, int destination) { int rc; - FILE * logfile; + FILE *logfile; if (destination == LOG_DESTINATION_CSVLOG && csvlogFile == NULL) open_csvlogfile(); - logfile = destination == LOG_DESTINATION_CSVLOG ? csvlogFile : syslogFile ; + logfile = destination == LOG_DESTINATION_CSVLOG ? csvlogFile : syslogFile; #ifndef WIN32 rc = fwrite(buffer, 1, count, logfile); @@ -972,16 +977,16 @@ pipeThread(void *arg) #endif /* WIN32 */ /* - * open the csv log file - we do this opportunistically, because + * open the csv log file - we do this opportunistically, because * we don't know if CSV logging will be wanted. */ static void open_csvlogfile(void) { - char *filename; - FILE *fh; + char *filename; + FILE *fh; - filename = logfile_getname(time(NULL),".csv"); + filename = logfile_getname(time(NULL), ".csv"); fh = fopen(filename, "a"); @@ -994,7 +999,7 @@ open_csvlogfile(void) setvbuf(fh, NULL, LBF_MODE, 0); #ifdef WIN32 - _setmode(_fileno(fh), _O_TEXT); /* use CRLF line endings on Windows */ + _setmode(_fileno(fh), _O_TEXT); /* use CRLF line endings on Windows */ #endif csvlogFile = fh; @@ -1010,7 +1015,7 @@ static void logfile_rotate(bool time_based_rotation, int size_rotation_for) { char *filename; - char *csvfilename = NULL; + char *csvfilename = NULL; FILE *fh; rotation_requested = false; @@ -1066,10 +1071,10 @@ logfile_rotate(bool time_based_rotation, int size_rotation_for) filename))); /* - * ENFILE/EMFILE are not too surprising on a busy system; just keep - * using the old file till we manage to get a new one. Otherwise, - * assume something's wrong with Log_directory and stop trying to - * create files. + * ENFILE/EMFILE are not too surprising on a busy system; just + * keep using the old file till we manage to get a new one. + * Otherwise, assume something's wrong with Log_directory and stop + * trying to create files. */ if (saveerrno != ENFILE && saveerrno != EMFILE) { @@ -1108,14 +1113,14 @@ logfile_rotate(bool time_based_rotation, int size_rotation_for) /* same as above, but for csv file. */ - if (csvlogFile != NULL && ( - time_based_rotation || - (size_rotation_for & LOG_DESTINATION_STDERR))) + if (csvlogFile != NULL && ( + time_based_rotation || + (size_rotation_for & LOG_DESTINATION_STDERR))) { if (Log_truncate_on_rotation && time_based_rotation && - last_csvfile_name != NULL && + last_csvfile_name != NULL && strcmp(csvfilename, last_csvfile_name) != 0) - + fh = fopen(csvfilename, "w"); else fh = fopen(csvfilename, "a"); @@ -1130,10 +1135,10 @@ logfile_rotate(bool time_based_rotation, int size_rotation_for) csvfilename))); /* - * ENFILE/EMFILE are not too surprising on a busy system; just keep - * using the old file till we manage to get a new one. Otherwise, - * assume something's wrong with Log_directory and stop trying to - * create files. + * ENFILE/EMFILE are not too surprising on a busy system; just + * keep using the old file till we manage to get a new one. + * Otherwise, assume something's wrong with Log_directory and stop + * trying to create files. */ if (saveerrno != ENFILE && saveerrno != EMFILE) { @@ -1179,7 +1184,7 @@ logfile_rotate(bool time_based_rotation, int size_rotation_for) * Result is palloc'd. */ static char * -logfile_getname(pg_time_t timestamp, char * suffix) +logfile_getname(pg_time_t timestamp, char *suffix) { char *filename; int len; @@ -1206,7 +1211,7 @@ logfile_getname(pg_time_t timestamp, char * suffix) if (suffix != NULL) { len = strlen(filename); - if (len > 4 && (strcmp(filename+(len-4),".log") == 0)) + if (len > 4 && (strcmp(filename + (len - 4), ".log") == 0)) len -= 4; strncpy(filename + len, suffix, MAXPGPATH - len); } diff --git a/src/backend/postmaster/walwriter.c b/src/backend/postmaster/walwriter.c index d5736b7e69..0780403a8d 100644 --- a/src/backend/postmaster/walwriter.c +++ b/src/backend/postmaster/walwriter.c @@ -34,7 +34,7 @@ * * * IDENTIFICATION - * $PostgreSQL: pgsql/src/backend/postmaster/walwriter.c,v 1.2 2007/09/11 17:15:33 tgl Exp $ + * $PostgreSQL: pgsql/src/backend/postmaster/walwriter.c,v 1.3 2007/11/15 21:14:37 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -92,9 +92,9 @@ WalWriterMain(void) /* * If possible, make this process a group leader, so that the postmaster - * can signal any child processes too. (walwriter probably never has - * any child processes, but for consistency we make all postmaster - * child processes do this.) + * can signal any child processes too. (walwriter probably never has any + * child processes, but for consistency we make all postmaster child + * processes do this.) */ #ifdef HAVE_SETSID if (setsid() < 0) @@ -107,14 +107,14 @@ WalWriterMain(void) * We have no particular use for SIGINT at the moment, but seems * reasonable to treat like SIGTERM. */ - pqsignal(SIGHUP, WalSigHupHandler); /* set flag to read config file */ + pqsignal(SIGHUP, WalSigHupHandler); /* set flag to read config file */ pqsignal(SIGINT, WalShutdownHandler); /* request shutdown */ pqsignal(SIGTERM, WalShutdownHandler); /* request shutdown */ - pqsignal(SIGQUIT, wal_quickdie); /* hard crash time */ + pqsignal(SIGQUIT, wal_quickdie); /* hard crash time */ pqsignal(SIGALRM, SIG_IGN); pqsignal(SIGPIPE, SIG_IGN); pqsignal(SIGUSR1, SIG_IGN); /* reserve for sinval */ - pqsignal(SIGUSR2, SIG_IGN); /* not used */ + pqsignal(SIGUSR2, SIG_IGN); /* not used */ /* * Reset some signals that are accepted by postmaster but not here @@ -133,8 +133,8 @@ WalWriterMain(void) #endif /* - * Create a resource owner to keep track of our resources (not clear - * that we need this, but may as well have one). + * Create a resource owner to keep track of our resources (not clear that + * we need this, but may as well have one). */ CurrentResourceOwner = ResourceOwnerCreate(NULL, "Wal Writer"); |
