Commit Graph

884 Commits

Author SHA1 Message Date
Alvaro Herrera a66ee69add Embedded list interface
Provide a common implementation of embedded singly-linked and
doubly-linked lists.  "Embedded" in the sense that the nodes'
next/previous pointers exist within some larger struct; this design
choice reduces memory allocation overhead.

Most of the implementation uses inlineable functions (where supported),
for performance.

Some existing uses of both types of lists have been converted to the new
code, for demonstration purposes.  Other uses can (and probably will) be
converted in the future.  Since dllist.c is unused after this conversion,
it has been removed.

Author: Andres Freund
Some tweaks by me
Reviewed by Tom Lane, Peter Geoghegan
2012-10-17 11:31:20 -03:00
Bruce Momjian 49ec613201 In our source code, make a copy of getopt's 'optarg' string arguments,
rather than just storing a pointer.
2012-10-12 13:35:43 -04:00
Peter Eisentraut c424d0d105 Remove redundant code for getnameinfo() replacement
Our getnameinfo() replacement implementation in getaddrinfo.c failed
unless NI_NUMERICHOST and NI_NUMERICSERV were given as flags, because
it doesn't resolve host names, only numeric IPs.  But per standard,
when those flags are not given, an implementation can still degrade to
not returning host names, so this restriction is unnecessary.  When we
remove it, we can eliminate some code in postmaster.c that apparently
tried to work around that.
2012-10-04 21:45:14 -04:00
Heikki Linnakangas 7c45e3a3c6 Parse pg_ident.conf when it's loaded, keeping it in memory in parsed format.
Similar changes were done to pg_hba.conf earlier already, this commit makes
pg_ident.conf to behave the same as pg_hba.conf.

This has two user-visible effects. First, if pg_ident.conf contains multiple
errors, the whole file is parsed at postmaster startup time and all the
errors are immediately reported. Before this patch, the file was parsed and
the errors were reported only when someone tries to connect using an
authentication method that uses the file, and the parsing stopped on first
error. Second, if you SIGHUP to reload the config files, and the new
pg_ident.conf file contains an error, the error is logged but the old file
stays in effect.

Also, regular expressions in pg_ident.conf are now compiled only once when
the file is loaded, rather than every time the a user is authenticated. That
should speed up authentication if you have a lot of regexps in the file.

Amit Kapila
2012-09-21 17:54:39 +03:00
Peter Eisentraut ffdd5a0ee3 Remove external PID file on postmaster exit 2012-08-20 23:47:11 -04:00
Tom Lane a67d6d9a78 Update overlooked comment. 2012-08-10 17:36:54 -04:00
Tom Lane c9b0cbe98b Support having multiple Unix-domain sockets per postmaster.
Replace unix_socket_directory with unix_socket_directories, which is a list
of socket directories, and adjust postmaster's code to allow zero or more
Unix-domain sockets to be created.

This is mostly a straightforward change, but since the Unix sockets ought
to be created after the TCP/IP sockets for safety reasons (better chance
of detecting a port number conflict), AddToDataDirLockFile needs to be
fixed to support out-of-order updates of data directory lockfile lines.
That's a change that had been foreseen to be necessary someday anyway.

Honza Horak, reviewed and revised by Tom Lane
2012-08-10 17:27:15 -04:00
Magnus Hagander b3055ab4fb Fix upper limit of superuser_reserved_connections, add limit for wal_senders
Should be limited to the maximum number of connections excluding
autovacuum workers, not including.

Add similar check for max_wal_senders, which should never be higher than
max_connections.
2012-08-10 14:50:45 +02:00
Tom Lane b76356ac22 Fix syslogger so that log_truncate_on_rotation works in the first rotation.
In the original coding of the log rotation stuff, we did not bother to make
the truncation logic work for the very first rotation after postmaster
start (or after a syslogger crash and restart).  It just always appended
in that case.  It did not seem terribly important at the time, but we've
recently had two separate complaints from people who expected it to work
unsurprisingly.  (Both users tend to restart the postmaster about as often
as a log rotation is configured to happen, which is maybe not typical use,
but still...)  Since the initial log file is opened in the postmaster,
fixing this requires passing down some more state to the syslogger child
process.

It's always been like this, so back-patch to all supported branches.
2012-07-31 14:36:54 -04:00
Tom Lane 57b9bdda39 Put back storage/proc.h in postmaster.c.
I took this out thinking it wasn't needed anymore, but the EXEC_BACKEND
code still needs it.  Per buildfarm.
2012-07-17 10:14:06 -04:00
Alvaro Herrera f34c68f096 Introduce timeout handling framework
Management of timeouts was getting a little cumbersome; what we
originally had was more than enough back when we were only concerned
about deadlocks and query cancel; however, when we added timeouts for
standby processes, the code got considerably messier.  Since there are
plans to add more complex timeouts, this seems a good time to introduce
a central timeout handling module.

External modules register their timeout handlers during process
initialization, and later enable and disable them as they see fit using
a simple API; timeout.c is in charge of keeping track of which timeouts
are in effect at any time, installing a common SIGALRM signal handler,
and calling setitimer() as appropriate to ensure timely firing of
external handlers.

timeout.c additionally supports pluggable modules to add their own
timeouts, though this capability isn't exercised anywhere yet.

Additionally, as of this commit, walsender processes are aware of
timeouts; we had a preexisting bug there that made those ignore SIGALRM,
thus being subject to unhandled deadlocks, particularly during the
authentication phase.  This has already been fixed in back branches in
commit 0bf8eb2a, which see for more details.

Main author: Zoltán Böszörményi
Some review and cleanup by Álvaro Herrera
Extensive reworking by Tom Lane
2012-07-16 22:55:33 -04:00
Tom Lane fc548b2296 Remove support for using wait3() in place of waitpid().
All Unix-oid platforms that we currently support should have waitpid(),
since it's in V2 of the Single Unix Spec.  Our git history shows that
the wait3 code was added to support NextStep, which we officially dropped
support for as of 9.2.  So get rid of the configure test, and simplify the
macro spaghetti in reaper().  Per suggestion from Fujii Masao.
2012-07-05 14:00:40 -04:00
Peter Eisentraut eeece9e609 Unify calling conventions for postgres/postmaster sub-main functions
There was a wild mix of calling conventions: Some were declared to
return void and didn't return, some returned an int exit code, some
claimed to return an exit code, which the callers checked, but
actually never returned, and so on.

Now all of these functions are declared to return void and decorated
with attribute noreturn and don't return.  That's easiest, and most
code already worked that way.
2012-06-25 21:30:12 +03:00
Bruce Momjian 927d61eeff Run pgindent on 9.2 source tree in preparation for first 9.3
commit-fest.
2012-06-10 15:20:04 -04:00
Simon Riggs a297d64d92 Checkpointer starts before bgwriter to avoid missing fsync requests.
Noted while testing Hot Standby startup.
2012-06-01 08:25:17 +01:00
Tom Lane b94ce6e807 Move postmaster's RemovePgTempFiles call to a less randomly chosen place.
There is no reason to do this as early as possible in postmaster startup,
and good reason not to do it until we have completely created the
postmaster's lock file, namely that it might contribute to pg_ctl thinking
that postmaster startup has timed out.  (This would require a rather
unusual amount of time to be spent scanning temp file directories, but we
have at least one field report of it happening reproducibly.)

Back-patch to 9.1.  Before that, pg_ctl didn't wait for additional info to
be added to the lock file, so it wasn't a problem.

Note that this is not a complete fix to the slow-start issue in 9.1,
because we still had identify_system_timezone being run during postmaster
start in 9.1.  But that's at least a reasonably well-defined delay, with
an easy workaround if needed, whereas the temp-files scan is not so
predictable and cannot be avoided.
2012-05-21 22:50:30 -04:00
Tom Lane d0c231d132 Cosmetic adjustments for postmaster's handling of checkpointer.
Correct some comments, order some operations a bit more consistently.
No functional changes.
2012-05-11 17:46:37 -04:00
Peter Eisentraut 48658a1b81 Fix some typos
Josh Kupershmidt
2012-04-22 19:23:47 +03:00
Heikki Linnakangas ef3883d130 Do stack-depth checking in all postmaster children.
We used to only initialize the stack base pointer when starting up a regular
backend, not in other processes. In particular, autovacuum workers can run
arbitrary user code, and without stack-depth checking, infinite recursion
in e.g an index expression will bring down the whole cluster.

The comment about PL/Java using set_stack_base() is not yet true. As the
code stands, PL/java still modifies the stack_base_ptr variable directly.
However, it's been discussed in the PL/Java mailing list that it should be
changed to use the function, because PL/Java is currently oblivious to the
register stack used on Itanium. There's another issues with PL/Java, namely
that the stack base pointer it sets is not really the base of the stack, it
could be something close to the bottom of the stack. That's a separate issue
that might need some further changes to this code, but that's a different
story.

Backpatch to all supported releases.
2012-04-08 19:07:55 +03:00
Heikki Linnakangas 5762a4d909 Inherit max_safe_fds to child processes in EXEC_BACKEND mode.
Postmaster sets max_safe_fds by testing how many open file descriptors it
can open, and that is normally inherited by all child processes at fork().
Not so on EXEC_BACKEND, ie. Windows, however. Because of that, we
effectively ignored max_files_per_process on Windows, and always assumed
a conservative default of 32 simultaneous open files. That could have an
impact on performance, if you need to access a lot of different files
in a query. After this patch, the value is passed to child processes by
save/restore_backend_variables() among many other global variables.

It has been like this forever, but given the lack of complaints about it,
I'm not backpatching this.
2012-03-29 08:19:11 +03:00
Tom Lane 442231d7f7 Fix postmaster to attempt restart after a hot-standby crash.
The postmaster was coded to treat any unexpected exit of the startup
process (i.e., the WAL replay process) as a catastrophic crash, and not try
to restart it. This was OK so long as the startup process could not have
any sibling postmaster children.  However, if a hot-standby backend
crashes, we SIGQUIT the startup process along with everything else, and the
resulting exit is hardly "unexpected".  Treating it as such meant we failed
to restart a standby server after any child crash at all, not only a crash
of the WAL replay process as intended.  Adjust that.  Back-patch to 9.0
where hot standby was introduced.
2012-02-06 15:30:21 -05:00
Simon Riggs ba1868ba31 Minor bug fix and cleanup from self-review of sync rep queues patch. 2012-01-30 14:36:17 +00:00
Simon Riggs 8366c7803e Allow pg_basebackup from standby node with safety checking.
Base backup follows recommended procedure, plus goes to great
lengths to ensure that partial page writes are avoided.

Jun Ishizuka and Fujii Masao, with minor modifications
2012-01-25 18:02:04 +00:00
Bruce Momjian e126958c2e Update copyright notices for year 2012. 2012-01-01 18:01:58 -05:00
Robert Haas ed0b409d22 Move "hot" members of PGPROC into a separate PGXACT array.
This speeds up snapshot-taking and reduces ProcArrayLock contention.
Also, the PGPROC (and PGXACT) structures used by two-phase commit are
now allocated as part of the main array, rather than in a separate
array, and we keep ProcArray sorted in pointer order.  These changes
are intended to minimize the number of cache lines that must be pulled
in to take a snapshot, and testing shows a substantial increase in
performance on both read and write workloads at high concurrencies.

Pavan Deolasee, Heikki Linnakangas, Robert Haas
2011-11-25 08:02:10 -05:00
Simon Riggs 806a2aee37 Split work of bgwriter between 2 processes: bgwriter and checkpointer.
bgwriter is now a much less important process, responsible for page
cleaning duties only. checkpointer is now responsible for checkpoints
and so has a key role in shutdown. Later patches will correct doc
references to the now old idea that bgwriter performs checkpoints.
Has beneficial effect on performance at high write rates, but mainly
refactoring to more easily allow changes for power reduction by
simplifying previously tortuous code around required to allow page
cleaning and checkpointing to time slice in the same process.

Patch by me, Review by Dickson Guedes
2011-11-01 17:14:47 +00:00
Tom Lane f9c92a5a3e Code review for pgstat_get_crashed_backend_activity patch.
Avoid possibly dumping core when pgstat_track_activity_query_size has a
less-than-default value; avoid uselessly searching for the query string
of a successfully-exited backend; don't bother putting out an ERRDETAIL if
we don't have a query to show; some other minor stylistic improvements.
2011-10-21 16:36:04 -04:00
Robert Haas c8e8b5a6e2 Try to log current the query string when a backend crashes.
To avoid minimize risk inside the postmaster, we subject this feature
to a number of significant limitations.  We very much wish to avoid
doing any complex processing inside the postmaster, due to the
posssibility that the crashed backend has completely corrupted shared
memory.  To that end, no encoding conversion is done; instead, we just
replace anything that doesn't look like an ASCII character with a
question mark.  We limit the amount of data copied to 1024 characters,
and carefully sanity check the source of that data.  While these
restrictions would doubtless be unacceptable in a general-purpose
logging facility, even this limited facility seems like an improvement
over the status quo ante.

Marti Raudsepp, reviewed by PDXPUG and myself
2011-10-21 13:26:40 -04:00
Bruce Momjian aaa6e1def2 Add postmaster -C option to query configuration parameters, and have
pg_ctl use that to query the data directory for config-only installs.
This fixes awkward or impossible pg_ctl operation for config-only
installs.
2011-10-06 09:38:39 -04:00
Bruce Momjian 054219c907 Fix pg_upgrade for EXEC_BACKEND builds (e.g. Windows) by properly
passing the -b/binary-upgrade flag.

Backpatch to 9.1.X.
2011-09-29 17:21:34 -04:00
Tom Lane ca4af308c3 Simplify handling of the timezone GUC by making initdb choose the default.
We were doing some amazingly complicated things in order to avoid running
the very expensive identify_system_timezone() procedure during GUC
initialization.  But there is an obvious fix for that, which is to do it
once during initdb and have initdb install the system-specific default into
postgresql.conf, as it already does for most other GUC variables that need
system-environment-dependent defaults.  This means that the timezone (and
log_timezone) settings no longer have any magic behavior in the server.
Per discussion.
2011-09-09 17:59:11 -04:00
Simon Riggs dde70cc313 Emit cascaded standby message on shutdown only when appropriate.
Adds additional test for active walsenders and closes a race
condition for when we failover when a new walsender was connecting.

Reported and fixed bu Fujii Masao. Review by Heikki Linnakangas
2011-09-07 09:09:47 +01:00
Peter Eisentraut 1af55e2751 Use consistent format for reporting GetLastError()
Use something like "error code %lu" for reporting GetLastError()
values on Windows.  Previously, a mix of different wordings and
formats were in use.
2011-08-23 22:00:52 +03:00
Peter Eisentraut f4a9da0a15 Use clearer notation for getnameinfo() return handling
Writing

    if (getnameinfo(...))
        handle_error();

reads quite strangely, so use something like

    if (getnameinfo(...) != 0)
        handle_error();

instead.
2011-08-09 18:30:32 +03:00
Heikki Linnakangas 5b6c8436d7 Fix grammar and spelling in log message. 2011-08-09 11:45:25 +03:00
Simon Riggs 5286105800 Cascading replication feature for streaming log-based replication.
Standby servers can now have WALSender processes, which can work with
either WALReceiver or archive_commands to pass data. Fully updated
docs, including new conceptual terms of sending server, upstream and
downstream servers. WALSenders terminated when promote to master.

Fujii Masao, review, rework and doc rewrite by Simon Riggs
2011-07-19 03:40:03 +01:00
Robert Haas 3cba8999b3 Create a "fast path" for acquiring weak relation locks.
When an AccessShareLock, RowShareLock, or RowExclusiveLock is requested
on an unshared database relation, and we can verify that no conflicting
locks can possibly be present, record the lock in a per-backend queue,
stored within the PGPROC, rather than in the primary lock table.  This
eliminates a great deal of contention on the lock manager LWLocks.

This patch also refactors the interface between GetLockStatusData() and
pg_lock_status() to be a bit more abstract, so that we don't rely so
heavily on the lock manager's internal representation details.  The new
fast path lock structures don't have a LOCK or PROCLOCK structure to
return, so we mustn't depend on that for purposes of listing outstanding
locks.

Review by Jeff Davis.
2011-07-18 00:49:28 -04:00
Heikki Linnakangas 89fd72cbf2 Introduce a pipe between postmaster and each backend, which can be used to
detect postmaster death. Postmaster keeps the write-end of the pipe open,
so when it dies, children get EOF in the read-end. That can conveniently
be waited for in select(), which allows eliminating some of the polling
loops that check for postmaster death. This patch doesn't yet change all
the loops to use the new mechanism, expect a follow-on patch to do that.

This changes the interface to WaitLatch, so that it takes as argument a
bitmask of events that it waits for. Possible events are latch set, timeout,
postmaster death, and socket becoming readable or writeable.

The pipe method behaves slightly differently from the kill() method
previously used in PostmasterIsAlive() in the case that postmaster has died,
but its parent has not yet read its exit code with waitpid(). The pipe
returns EOF as soon as the process dies, but kill() continues to return
true until waitpid() has been called (IOW while the process is a zombie).
Because of that, change PostmasterIsAlive() to use the pipe too, otherwise
WaitLatch() would return immediately with WL_POSTMASTER_DEATH, while
PostmasterIsAlive() would claim it's still alive. That could easily lead to
busy-waiting while postmaster is in zombie state.

Peter Geoghegan with further changes by me, reviewed by Fujii Masao and
Florian Pflug.
2011-07-08 18:44:07 +03:00
Peter Eisentraut 9a0bdc8db5 Message style improvements of errmsg_internal() calls 2011-07-05 23:01:35 +03:00
Heikki Linnakangas f7ea6beaf4 Remove silent_mode. You get the same functionality with "pg_ctl -l
postmaster.log", or nohup.

There was a small issue with LINUX_OOM_ADJ and silent_mode, namely that with
silent_mode the postmaster process incorrectly used the OOM settings meant
for backend processes. We certainly could've fixed that directly, but since
silent_mode was redundant anyway, we might as well just remove it.
2011-07-04 14:35:44 +03:00
Peter Eisentraut 223d14a984 Make external_pid_file world readable 2011-06-19 00:34:32 +03:00
Bruce Momjian 6560407c7d Pgindent run before 9.1 beta2. 2011-06-09 14:32:50 -04:00
Andrew Dunstan ab0ba6e73a Add some casts to try to silence most of the remaining format warnings on MinGW-W64. 2011-04-28 15:05:58 -04:00
Andrew Dunstan 348c10efe0 Revert "Remove hard coded formats for INT64 and use configured settings instead."
This reverts commit 9b1508af89.

As requested by Tom.
2011-04-27 11:28:14 -04:00
Andrew Dunstan 9b1508af89 Remove hard coded formats for INT64 and use configured settings instead. 2011-04-27 11:07:52 -04:00
Bruce Momjian 76dd09bbec Add postmaster/postgres undocumented -b option for binary upgrades.
This option turns off autovacuum, prevents non-super-user connections,
and enables oid setting hooks in the backend.  The code continues to use
the old autoavacuum disable settings for servers with earlier catalog
versions.

This includes a catalog version bump to identify servers that support
the -b option.
2011-04-25 12:00:21 -04:00
Bruce Momjian bf50caf105 pgindent run before PG 9.1 beta 1. 2011-04-10 11:42:00 -04:00
Robert Haas 38b27792ea Avoid possible hang during smart shutdown.
If a smart shutdown occurs just as a child is starting up, and the
child subsequently becomes a walsender, there is a race condition:
the postmaster might count the exstant backends, determine that there
is one normal backend, and wait for it to die off.  Had the walsender
transition already occurred before the postmaster counted, it would
have proceeded with the shutdown.

To fix this, have each child that transforms into a walsender kick
the postmaster just after doing so, so that the state machine is
certain to advance.

Fujii Masao
2011-04-03 19:42:00 -04:00
Robert Haas 19584ec659 Remove synchronous_replication/max_wal_senders cross-check.
This is no longer necessary, and might result in a situation where the
configuration file is reloaded (and everything seems OK) but a subsequent
restart of the database fails.

Per an observation from Fujii Masao.
2011-03-23 11:44:27 -04:00
Heikki Linnakangas 97e3dacd84 Begin error message with lower-case letter. 2011-03-07 10:41:13 +02:00
Simon Riggs a8a8a3e096 Efficient transaction-controlled synchronous replication.
If a standby is broadcasting reply messages and we have named
one or more standbys in synchronous_standby_names then allow
users who set synchronous_replication to wait for commit, which
then provides strict data integrity guarantees. Design avoids
sending and receiving transaction state information so minimises
bookkeeping overheads. We synchronize with the highest priority
standby that is connected and ready to synchronize. Other standbys
can be defined to takeover in case of standby failure.

This version has very strict behaviour; more relaxed options
may be added at a later date.

Simon Riggs and Fujii Masao, with reviews by Yeb Havinga, Jaime
Casanova, Heikki Linnakangas and Robert Haas, plus the assistance
of many other design reviewers.
2011-03-06 22:49:16 +00:00
Robert Haas 4695da5ae9 pg_ctl promote
Fujii Masao, reviewed by Robert Haas, Stephen Frost, and Magnus Hagander.
2011-02-15 21:30:23 -05:00
Robert Haas a0c75f5539 Avoid treating WAL senders as normal backends.
The previous coding treated anything that wasn't an autovacuum launcher
as a normal backend, which is wrong now that we also have WAL senders.

Fujii Masao, reviewed by Robert Haas, Alvaro Herrera, Tom Lane,
and Bernd Helmle.
2011-01-21 22:23:01 -05:00
Tom Lane 52948169bc Code review for postmaster.pid contents changes.
Fix broken test for pre-existing postmaster, caused by wrong code for
appending lines to the lockfile; don't write a failed listen_address
setting into the lockfile; don't arbitrarily change the location of the
data directory in the lockfile compared to previous releases; provide more
consistent and useful definitions of the socket path and listen_address
entries; avoid assuming that pg_ctl has the same DEFAULT_PGSOCKET_DIR as
the postmaster; assorted code style improvements.
2011-01-13 19:01:28 -05:00
Bruce Momjian 5d950e3b0c Stamp copyrights for year 2011. 2011-01-01 13:18:15 -05:00
Bruce Momjian 30aeda4394 Include the first valid listen address in pg_ctl to improve server start
"wait" detection and add postmaster start time to help determine if the
postmaster is actually using the specified data directory.
2010-12-31 17:25:02 -05:00
Alvaro Herrera b68193c0c7 Remove unnecessary definition for autovacuum in SignalSomeChildren. 2010-12-17 15:59:19 -03:00
Tom Lane 61b53695fb Remove optreset from src/port/ implementations of getopt and getopt_long.
We don't actually need optreset, because we can easily fix the code to
ensure that it's cleanly restartable after having completed a scan over the
argv array; which is the only case we need to restart in.  Getting rid of
it avoids a class of interactions with the system libraries and allows
reversion of my change of yesterday in postmaster.c and postgres.c.

Back-patch to 8.4.  Before that the getopt code was a bit different anyway.
2010-12-16 16:23:05 -05:00
Alvaro Herrera 16ca75baeb Simplify SignalSomeChildren(BACKEND_TYPE_ALL) to SignalChildren() 2010-12-16 12:23:07 -03:00
Tom Lane 5cdd65f324 Fix up getopt() reset management so it works on recent mingw.
The mingw people don't appear to care about compatibility with non-GNU
versions of getopt, so force use of our own copy of getopt on Windows.
Also, ensure that we make use of optreset when using our own copy.

Per report from Andrew Dunstan.  Back-patch to all versions supported
on Windows.
2010-12-15 23:50:41 -05:00
Tom Lane 04f4e10cfc Use symbolic names not octal constants for file permission flags.
Purely cosmetic patch to make our coding standards more consistent ---
we were doing symbolic some places and octal other places.  This patch
fixes all C-coded uses of mkdir, chmod, and umask.  There might be some
other calls I missed.  Inconsistency noted while researching tablespace
directory permissions issue.
2010-12-10 17:35:33 -05:00
Magnus Hagander 4acf99b2f3 Send paramHandle to subprocesses as 64-bit on Win64
The handle to the shared memory segment containing startup
parameters was sent as 32-bit even on 64-bit systems. Since
HANDLEs appear to be allocated sequentially this shouldn't
be a problem until we reach 2^32 open handles in the postmaster,
but a 64-bit value should be sent across as 64-bit, and not
zero out the top 32 bits.

Noted by Tom Lane.
2010-11-16 12:40:56 +01:00
Tom Lane 3892a2d861 Fix canAcceptConnections() bugs introduced by replication-related patches.
We must not return any "okay to proceed" result code without having checked
for too many children, else we might fail later on when trying to add the
new child to one of the per-child state arrays.  It's not clear whether
this oversight explains Stefan Kaltenbrunner's recent report, but it could
certainly produce a similar symptom.

Back-patch to 8.4; the logic was not broken before that.
2010-11-14 15:57:37 -05:00
Tom Lane e6721c6e16 Previous patch had no detectable virtue other than being a one-liner.
Try to make the code look self-consistent again, so it doesn't confuse
future developers.
2010-10-27 15:26:24 -04:00
Heikki Linnakangas 869af50fcf Fix long-standing segfault when accept() or one of the calls made right
after accepting a connection fails, and the server is compiled with GSSAPI
support. Report and patch by Alexander V. Chernikov, bug #5731.
2010-10-27 20:07:13 +03:00
Peter Eisentraut 6ab42ae367 Support host names in pg_hba.conf
Peter Eisentraut, reviewed by KaiGai Kohei and Tom Lane
2010-10-15 22:56:18 +03:00
Bruce Momjian 23177114c6 Improve comment about ignoring 128 error code on Windows:
* Microsoft reports it is related to mutex failure:
     *   http://archives.postgresql.org/pgsql-hackers/2010-09/msg00790.php
2010-10-15 01:58:11 +00:00
Magnus Hagander 9f2e211386 Remove cvs keywords from all files. 2010-09-20 22:08:53 +02:00
Magnus Hagander 594419e74a Treat exit code 128 (ERROR_WAIT_NO_CHILDREN) as non-fatal on Win32,
since it can happen when a process fails to start when the system
is under high load.

Per several bug reports and many peoples investigation.

Back-patch to 8.4, which is as far back as the "deadman-switch"
for shared memory access exists.
2010-09-16 20:37:13 +00:00
Robert Haas 5ffaa9005c Add restart_after_crash GUC.
Normally, we automatically restart after a backend crash, but in some
cases when PostgreSQL is invoked by clusterware it may be desirable to
suppress this behavior, so we provide an option which does this.
Since no existing GUC group quite fits, create a new group called
"error handling options" for this and the previously undocumented GUC
exit_on_error, which is now documented.

Review by Fujii Masao.
2010-07-20 00:47:53 +00:00
Bruce Momjian 239d769e7e pgindent run for 9.0, second run 2010-07-06 19:19:02 +00:00
Robert Haas 243bbe6ed8 Add stray "else" that seems to have gone missing. 2010-06-24 16:40:45 +00:00
Peter Eisentraut 418e1d82fd Refactor sprintf calls with computed format strings into multiple calls with
constant format strings, so that the compiler can more easily check the
formats for correctness.
2010-06-16 00:54:16 +00:00
Peter Eisentraut cb6038c168 Fix some inconsistent quoting of wal_level values in messages
When referring to postgresql.conf syntax, then it's without quotes
(wal_level=archive); in narrative it's with double quotes.  But never
single quotes.
2010-06-03 21:02:12 +00:00
Robert Haas 5e85315ea7 Avoid starting walreceiver in states where it shouldn't be running.
In particular, it's bad to start walreceiver when in state
PM_WAIT_BACKENDS, because we have no provision to kill walreceiver
when in that state.

Fujii Masao
2010-05-27 02:01:37 +00:00
Robert Haas 615704af1e More fixes for shutdown during recovery.
1. If we receive a fast shutdown request while in the PM_STARTUP state,
process it just as we would in PM_RECOVERY, PM_HOT_STANDBY, or PM_RUN.
Without this change, an early fast shutdown followed by Hot Standby causes
the database to get stuck in a state where a shutdown is pending (so no new
connections are allowed) but the shutdown request is never processed unless
we end Hot Standby and enter normal running.

2. Avoid removing the backup label file when a smart or fast shutdown occurs
during recovery.  It makes sense to do this once we've reached normal running,
since we must be taking a backup which now won't be valid.  But during
recovery we must be recovering from a previously taken backup, and any backup
label file is needed to restart recovery from the right place.

Fujii Masao and Robert Haas
2010-05-26 12:32:41 +00:00
Robert Haas ea9968c331 Rename PM_RECOVERY_CONSISTENT and PMSIGNAL_RECOVERY_CONSISTENT.
The new names PM_HOT_STANDBY and PMSIGNAL_BEGIN_HOT_STANDBY more accurately
reflect their actual function.
2010-05-15 20:01:32 +00:00
Robert Haas a724584735 We now accept read-only connections in state PM_RECOVERY_CONSISTENT. 2010-05-14 18:08:33 +00:00
Heikki Linnakangas 9b8a73326e Introduce wal_level GUC to explicitly control if information needed for
archival or hot standby should be WAL-logged, instead of deducing that from
other options like archive_mode. This replaces recovery_connections GUC in
the primary, where it now has no effect, but it's still used in the standby
to enable/disable hot standby.

Remove the WAL-logging of "unlogged operations", like creating an index
without WAL-logging and fsyncing it at the end. Instead, we keep a copy of
the wal_mode setting and the settings that affect how much shared memory a
hot standby server needs to track master transactions (max_connections,
max_prepared_xacts, max_locks_per_xact) in pg_control. Whenever the settings
change, at server restart, write a WAL record noting the new settings and
update pg_control. This allows us to notice the change in those settings in
the standby at the right moment, they used to be included in checkpoint
records, but that meant that a changed value was not reflected in the
standby until the first checkpoint after the change.

Bump PG_CONTROL_VERSION and XLOG_PAGE_MAGIC. Whack XLOG_PAGE_MAGIC back to
the sequence it used to follow, before hot standby and subsequent patches
changed it to 0x9003.
2010-04-28 16:10:43 +00:00
Robert Haas 1c850fa807 Make smart shutdown work in combination with Hot Standby/Streaming Replication.
At present, killing the startup process does not release any locks it holds,
so we must wait to stop the startup and walreceiver processes until all
read-only backends have exited.  Without this patch, the startup and
walreceiver processes never exit, so the server gets permanently stuck in
a half-shutdown state.

Fujii Masao, with review, docs, and comment adjustments by me.
2010-04-08 01:39:37 +00:00
Simon Riggs 65cd829232 Modify some new and pre-existing messages for translatability. 2010-03-25 20:40:17 +00:00
Bruce Momjian 65e806cba1 pgindent run for 9.0 2010-02-26 02:01:40 +00:00
Heikki Linnakangas 1bb2558046 Make standby server continuously retry restoring the next WAL segment with
restore_command, if the connection to the primary server is lost. This
ensures that the standby can recover automatically, if the connection is
lost for a long time and standby falls behind so much that the required
WAL segments have been archived and deleted in the master.

This also makes standby_mode useful without streaming replication; the
server will keep retrying restore_command every few seconds until the
trigger file is found. That's the same basic functionality pg_standby
offers, but without the bells and whistles.

To implement that, refactor the ReadRecord/FetchRecord functions. The
FetchRecord() function introduced in the original streaming replication
patch is removed, and all the retry logic is now in a new function called
XLogReadPage(). XLogReadPage() is now responsible for executing
restore_command, launching walreceiver, and waiting for new WAL to arrive
from primary, as required.

This also changes the life cycle of walreceiver. When launched, it now only
tries to connect to the master once, and exits if the connection fails, or
is lost during streaming for any reason. The startup process detects the
death, and re-launches walreceiver if necessary.
2010-01-27 15:27:51 +00:00
Heikki Linnakangas 40f908bdcd Introduce Streaming Replication.
This includes two new kinds of postmaster processes, walsenders and
walreceiver. Walreceiver is responsible for connecting to the primary server
and streaming WAL to disk, while walsender runs in the primary server and
streams WAL from disk to the client.

Documentation still needs work, but the basics are there. We will probably
pull the replication section to a new chapter later on, as well as the
sections describing file-based replication. But let's do that as a separate
patch, so that it's easier to see what has been added/changed. This patch
also adds a new section to the chapter about FE/BE protocol, documenting the
protocol used by walsender/walreceivxer.

Bump catalog version because of two new functions,
pg_last_xlog_receive_location() and pg_last_xlog_replay_location(), for
monitoring the progress of replication.

Fujii Masao, with additional hacking by me
2010-01-15 09:19:10 +00:00
Magnus Hagander 87091cb1f1 Create typedef pgsocket for storing socket descriptors.
This silences some warnings on Win64. Not using the proper SOCKET datatype
was actually wrong on Win32 as well, but didn't cause any warnings there.

Also create define PGINVALID_SOCKET to indicate an invalid/non-existing
socket, instead of using a hardcoded -1 value.
2010-01-10 14:16:08 +00:00
Bruce Momjian 0239800893 Update copyright for the year 2010. 2010-01-02 16:58:17 +00:00
Magnus Hagander 13c5fdb5c8 Fix one more cast for _open_osfhandle().
Tsutomu Yamada
2010-01-02 12:01:29 +00:00
Simon Riggs efc16ea520 Allow read only connections during recovery, known as Hot Standby.
Enabled by recovery_connections = on (default) and forcing archive recovery using a recovery.conf. Recovery processing now emulates the original transactions as they are replayed, providing full locking and MVCC behaviour for read only queries. Recovery must enter consistent state before connections are allowed, so there is a delay, typically short, before connections succeed. Replay of recovering transactions can conflict and in some cases deadlock with queries during recovery; these result in query cancellation after max_standby_delay seconds have expired. Infrastructure changes have minor effects on normal running, though introduce four new types of WAL record.

New test mode "make standbycheck" allows regression tests of static command behaviour on a standby server while in recovery. Typical and extreme dynamic behaviours have been checked via code inspection and manual testing. Few port specific behaviours have been utilised, though primary testing has been on Linux only so far.

This commit is the basic patch. Additional changes will follow in this release to enhance some aspects of behaviour, notably improved handling of conflicts, deadlock detection and query cancellation. Changes to VACUUM FULL are also required.

Simon Riggs, with significant and lengthy review by Heikki Linnakangas, including streamlined redesign of snapshot creation and two-phase commit.

Important contributions from Florian Pflug, Mark Kirkwood, Merlin Moncure, Greg Stark, Gianni Ciolli, Gabriele Bartolini, Hannu Krosing, Robert Haas, Tatsuo Ishii, Hiroyuki Yamada plus support and feedback from many other community members.
2009-12-19 01:32:45 +00:00
Tom Lane eeb6cb143a Add a boolean GUC parameter "bonjour" to control whether a Bonjour-enabled
build actually attempts to advertise itself via Bonjour.  Formerly it always
did so, which meant that packagers had to decide for their users whether
this behavior was wanted or not.  The default is "off" to be on the safe
side, though this represents a change in the default behavior of a
Bonjour-enabled build.  Per discussion.
2009-09-08 17:08:36 +00:00
Tom Lane 59b9f3d36d Replace use of the long-deprecated Bonjour API DNSServiceRegistrationCreate
with the not-so-deprecated DNSServiceRegister.  This patch shouldn't change
any user-visible behavior, it just gets rid of a deprecation warning in
--with-bonjour builds.  The new code will fail on OS X releases before 10.3,
but it seems unlikely that anyone will want to run Postgres 8.5 on 10.2.
2009-09-08 16:08:26 +00:00
Tom Lane 00e6a16d01 Change the autovacuum launcher to read pg_database directly, rather than
via the "flat files" facility.  This requires making it enough like a backend
to be able to run transactions; it's no longer an "auxiliary process" but
more like the autovacuum worker processes.  Also, its signal handling has
to be brought into line with backends/workers.  In particular, since it
now has to handle procsignal.c processing, the special autovac-launcher-only
signal conditions are moved to SIGUSR2.

Alvaro, with some cleanup from Tom
2009-08-31 19:41:00 +00:00
Tom Lane e710b65c1c Remove the use of the pg_auth flat file for client authentication.
(That flat file is now completely useless, but removal will come later.)

To do this, postpone client authentication into the startup transaction
that's run by InitPostgres.  We still collect the startup packet and do
SSL initialization (if needed) at the same time we did before.  The
AuthenticationTimeout is applied separately to startup packet collection
and the actual authentication cycle.  (This is a bit annoying, since it
means a couple extra syscalls; but the signal handling requirements inside
and outside a transaction are sufficiently different that it seems best
to treat the timeouts as completely independent.)

A small security disadvantage is that if the given database name is invalid,
this will be reported to the client before any authentication happens.
We could work around that by connecting to database "postgres" instead,
but consensus seems to be that it's not worth introducing such surprising
behavior.

Processing of all command-line switches and GUC options received from the
client is now postponed until after authentication.  This means that
PostAuthDelay is much less useful than it used to be --- if you need to
investigate problems during InitPostgres you'll have to set PreAuthDelay
instead.  However, allowing an unauthenticated user to set any GUC options
whatever seems a bit too risky, so we'll live with that.
2009-08-29 19:26:52 +00:00
Tom Lane 0a00c9a8ef Remove useless code that propagated FrontendProtocol to a backend via a
PostgresMain switch.  In point of fact, FrontendProtocol is already set
in a backend process, since ProcessStartupPacket() is executed inside
the backend --- it hasn't been run by the postmaster for many years.
And if it were, we'd still certainly want FrontendProtocol to be set before
we get as far as PostgresMain, so that startup errors get reported in the
right protocol.

-v might have some future use in standalone backends, so I didn't go so
far as to remove the switch outright.

Also, initialize FrontendProtocol to 0 not PG_PROTOCOL_LATEST.  The only
likely result of presetting it like that is to mask failure-to-set-it
mistakes.
2009-08-28 18:23:53 +00:00
Tom Lane c66d9ce774 Non-Windows EXEC_BACKEND path was broken by recent write_inheritable_socket
change ... it's got to return true.
2009-08-28 17:42:54 +00:00
Tom Lane 8bed238c87 Try to make silent_mode behave somewhat reasonably.
Instead of sending stdout/stderr to /dev/null after forking away from the
terminal, send them to postmaster.log within the data directory.  Since
this opens the door to indefinite logfile bloat, recommend even more
strongly that log output be redirected when using silent_mode.

Move the postmaster's initial calls of load_hba() and load_ident() down
to after we have started the log collector, if we are going to.  This
is so that errors reported by them will appear in the "usual" place.

Reclassify silent_mode as a LOGGING_WHERE, not LOGGING_WHEN, parameter,
since it's got absolutely nothing to do with the latter category.

In passing, fix some obsolete references to -S ... this option hasn't
had that switch letter for a long time.

Back-patch to 8.4, since as of 8.4 load_hba() and load_ident() are more
picky (and thus more likely to fail) than they used to be.  This entire
change was driven by a complaint about those errors disappearing into
the bit bucket.
2009-08-24 20:08:32 +00:00
Tom Lane 5a4f763841 Small correction to previous patch: we shouldn't ReleasePostmasterChildSlot
for a dead_end child, because we didn't AssignPostmasterChildSlot.
2009-08-24 18:09:37 +00:00
Alvaro Herrera 45f9b4646f Avoid calling kill() in a postmaster signal handler.
This causes problems when the system load is high, per report from Zdenek
Kotala in <1250860954.1239.114.camel@localhost>; instead of calling kill
directly, have the signal handler set a flag which is checked in ServerLoop.
This way, the handler can return before being called again by a subsequent
signal sent from the autovacuum launcher.  Also, increase the sleep in the
launcher in this failure path to 1 second.

Backpatch to 8.3, which is when the signalling between autovacuum
launcher/postmaster was introduced.

Also, add a couple of ReleasePostmasterChildSlot calls in error paths; this
part backpatched to 8.4 which is when the child slot stuff was introduced.
2009-08-24 17:23:02 +00:00
Heikki Linnakangas 06f1f53ea9 Fast shutdown stop should forcibly disconnect any active backends, even
if a smart shutdown is already in progress. Backpatch to 8.3, this was broken
in the patch that introduced "dead-end backends".

Per report by Itagaki Takahiro, patch by Fujii Masao.
2009-08-07 05:58:55 +00:00
Magnus Hagander 4000170535 Avoid terminating the postmaster on a number of "can't happen" cases during
backend startup on Win32. Instead, log the error and just forget about
the potentially dangling process, since we can't do anything about it anyway.
2009-08-06 09:50:22 +00:00
Magnus Hagander a7e587863c Reserve the shared memory region during backend startup on Windows, so
that memory allocated by starting third party DLLs doesn't end up
conflicting with it.

Hopefully this solves the long-time issue with "could not reattach
to shared memory" errors on Win32.

Patch from Tsutomu Yamada and me, based on idea from Trevor Talbot.
2009-07-24 20:12:42 +00:00
Tom Lane b11ce5608a Remove no-longer-necessary transmission of postmaster's LC_COLLATE and
LC_CTYPE settings to children via BackendParameters.  Per discussion,
the postmaster is now just using system defaults anyway, so we might as
well save a few cycles during backend startup.
2009-07-08 18:55:35 +00:00
Tom Lane 2de48a83e6 Cleanup and code review for the patch that made bgwriter active during
archive recovery.  Invent a separate state variable and inquiry function
for XLogInsertAllowed() to clarify some tests and make the management of
writing the end-of-recovery checkpoint less klugy.  Fix several places
that were incorrectly testing InRecovery when they should be looking at
RecoveryInProgress or XLogInsertAllowed (because they will now be executed
in the bgwriter not startup process).  Clarify handling of bad LSNs passed
to XLogFlush during recovery.  Use a spinlock for setting/testing
SharedRecoveryInProgress.  Improve quite a lot of comments.

Heikki and Tom
2009-06-26 20:29:04 +00:00
Bruce Momjian d747140279 8.4 pgindent run, with new combined Linux/FreeBSD/MinGW typedef list
provided by Andrew.
2009-06-11 14:49:15 +00:00
Tom Lane 969d7cd431 Install a "dead man switch" to allow the postmaster to detect cases where
a backend has done exit(0) or exit(1) without having disengaged itself
from shared memory.  We are at risk for this whenever third-party code is
loaded into a backend, since such code might not know it's supposed to go
through proc_exit() instead.  Also, it is reported that under Windows
there are ways to externally kill a process that cause the status code
returned to the postmaster to be indistinguishable from a voluntary exit
(thank you, Microsoft).  If this does happen then the system is probably
hosed --- for instance, the dead session might still be holding locks.
So the best recovery method is to treat this like a backend crash.

The dead man switch is armed for a particular child process when it
acquires a regular PGPROC, and disarmed when the PGPROC is released;
these should be the first and last touches of shared memory resources
in a backend, or close enough anyway.  This choice means there is no
coverage for auxiliary processes, but I doubt we need that, since they
shouldn't be executing any user-provided code anyway.

This patch also improves the management of the EXEC_BACKEND
ShmemBackendArray array a bit, by reducing search costs.

Although this problem is of long standing, the lack of field complaints
seems to mean it's not critical enough to risk back-patching; at least
not till we get some more testing of this mechanism.
2009-05-05 19:59:00 +00:00
Tom Lane 4071e0c242 Fix missed usage of DLNewElem() 2009-05-04 02:46:36 +00:00
Alvaro Herrera a1e1ef4f77 Avoid a memory allocation in the backend startup code, to avoid having to check
whether it failed.  Modelled after catcache.c's usage of DlList, per suggestion
from Tom.
2009-05-04 02:24:17 +00:00
Tom Lane d90984f4f6 Install some simple defenses in postmaster startup to help ensure a useful
error message if the installation directory layout is messed up (or at least,
something more useful than the behavior exhibited in bug #4787).  During
postmaster startup, check that get_pkglib_path resolves as a readable
directory; and if ParseTzFile() fails to open the expected timezone
abbreviation file, check the possibility that the directory is missing rather
than just the specified file.  In case of either failure, issue a hint
suggesting that the installation is broken.  These two checks cover the lib/
and share/ trees of a full installation, which should take care of most
scenarios where a sysadmin decides to get cute.
2009-05-02 22:02:37 +00:00
Tom Lane 27fbfd396c Remove a boatload of useless definitions of 'int optreset'. If we
are using our own ports of getopt or getopt_long, those will define
the variable for themselves; and if not, we don't need these, because
we never touch the variable anyway.
2009-04-05 04:19:59 +00:00
Heikki Linnakangas fb7df896fc Reload config file in startup process on SIGHUP.
Fujii Masao
2009-03-04 13:56:40 +00:00
Heikki Linnakangas fd75329e81 Fix copy-pasto in the patch to allow background writer to run during
recovery: if background writer or pgstat process dies during recovery (or
any other child process, but those two are the only ones running), send
SIGQUIT to the startup process using correct pid.
2009-03-03 10:42:05 +00:00
Heikki Linnakangas 0160cebee9 Put back a "continue" that went missing in the changes to start background
writer in WAL recovery.
2009-02-25 11:07:43 +00:00
Heikki Linnakangas bc134d7a51 Change the signaling of end-of-recovery. Startup process now indicates end
of recovery by exiting with exit code 0, like in previous releases. Per
Tom's suggestion.
2009-02-23 09:28:50 +00:00
Heikki Linnakangas 5717f3a3e6 Fix bogus comment, from the patch to start bgwriter during archive
recovery.
2009-02-19 16:43:13 +00:00
Heikki Linnakangas cdd46c7654 Start background writer during archive recovery. Background writer now performs
its usual buffer cleaning duties during archive recovery, and it's responsible
for performing restartpoints.

This requires some changes in postmaster. When the startup process has done
all the initialization and is ready to start WAL redo, it signals the
postmaster to launch the background writer. The postmaster is signaled again
when the point in recovery is reached where we know that the database is in
consistent state. Postmaster isn't interested in that at the moment, but
that's the point where we could let other backends in to perform read-only
queries. The postmaster is signaled third time when the recovery has ended,
so that postmaster knows that it's safe to start accepting connections.

The startup process now traps SIGTERM, and performs a "clean" shutdown. If
you do a fast shutdown during recovery, a shutdown restartpoint is performed,
like a shutdown checkpoint, and postmaster kills the processes cleanly. You
still have to continue the recovery at next startup, though.

Currently, the background writer is only launched during archive recovery.
We could launch it during crash recovery as well, but it seems better to keep
that codepath as simple as possible, for the sake of robustness. And it
couldn't do any restartpoints during crash recovery anyway, so it wouldn't be
that useful.

log_restartpoints is gone. Use log_checkpoints instead. This is yet to be
documented.

This whole operation is a pre-requisite for Hot Standby, but has some value of
its own whether the hot standby patch makes 8.4 or not.

Simon Riggs, with lots of modifications by me.
2009-02-18 15:58:41 +00:00
Tom Lane 7466eeac61 Add contrib/pg_stat_statements for server-wide tracking of statement execution
statistics.

Takahiro Itagaki
2009-01-04 22:19:59 +00:00
Tom Lane dad75a62bf Create a "shmem_startup_hook" to be called at the end of shared memory
initialization, to give loadable modules a reasonable place to perform
creation of any shared memory areas they need.  This is the logical conclusion
of our previous creation of RequestAddinShmemSpace() and RequestAddinLWLocks().
We don't need an explicit shmem_shutdown_hook, because the existing
on_shmem_exit and on_proc_exit mechanisms serve that need.

Also, adjust SubPostmasterMain so that libraries that got loaded into the
postmaster will be loaded into all child processes, not only regular backends.
This improves consistency with the non-EXEC_BACKEND behavior, and might be
necessary for functionality for some types of add-ons.
2009-01-03 17:08:39 +00:00
Bruce Momjian 511db38ace Update copyright for 2009. 2009-01-01 17:24:05 +00:00
Peter Eisentraut d9346f2186 The macros NULL_DEV and DEVNULL were both used to work around
platform-specific spellings of /dev/null.  But one should be enough, so
settle on DEVNULL.
2008-12-11 10:25:17 +00:00
Magnus Hagander 53a5026b5c Remove support for (insecure) crypt authentication.
This breaks compatibility with pre-7.2 versions.
2008-10-28 12:10:44 +00:00
Bruce Momjian 5f7b25d5d5 Add comment about the use of EXEC_BACKEND. 2008-09-23 20:35:38 +00:00
Heikki Linnakangas 61d9674988 Make LC_COLLATE and LC_CTYPE database-level settings. Collation and
ctype are now more like encoding, stored in new datcollate and datctype
columns in pg_database.

This is a stripped-down version of Radek Strnad's patch, with further
changes by me.
2008-09-23 09:20:39 +00:00
Magnus Hagander 9872381090 Parse pg_hba.conf in postmaster, instead of once in each backend for
each connection. This makes it possible to catch errors in the pg_hba
file when it's being reloaded, instead of silently reloading a broken
file and failing only when a user tries to connect.

This patch also makes the "sameuser" argument to ident authentication
optional.
2008-09-15 12:32:57 +00:00
Magnus Hagander be8d6c5c34 Make stats_temp_directory PGC_SIGHUP, and document how it may cause a temporary
"outage" of the statistics views.

This requires making the stats collector respond to SIGHUP, like the other
utility processes already did.
2008-08-25 15:11:01 +00:00
Bruce Momjian 067f1e5fa8 Fix 'pg_ctl restart' to preserve command-line arguments. 2008-06-26 02:47:19 +00:00
Bruce Momjian a1183238be Use SYSTEMQUOTE as concatentation to strings, rather than %s printf
patterns, for clarity.
2008-06-26 01:35:45 +00:00
Tom Lane fad153ec45 Rewrite the sinval messaging mechanism to reduce contention and avoid
unnecessary cache resets.  The major changes are:

* When the queue overflows, we only issue a cache reset to the specific
backend or backends that still haven't read the oldest message, rather
than resetting everyone as in the original coding.

* When we observe backend(s) falling well behind, we signal SIGUSR1
to only one backend, the one that is furthest behind and doesn't already
have a signal outstanding for it.  When it finishes catching up, it will
in turn signal SIGUSR1 to the next-furthest-back guy, if there is one that
is far enough behind to justify a signal.  The PMSIGNAL_WAKEN_CHILDREN
mechanism is removed.

* We don't attempt to clean out dead messages after every message-receipt
operation; rather, we do it on the insertion side, and only when the queue
fullness passes certain thresholds.

* Split SInvalLock into SInvalReadLock and SInvalWriteLock so that readers
don't block writers nor vice versa (except during the infrequent queue
cleanout operations).

* Transfer multiple sinval messages for each acquisition of a read or
write lock.
2008-06-19 21:32:56 +00:00
Alvaro Herrera e4ca6cac43 Change xlog.h to xlogdefs.h in bufpage.h, and fix fallout. 2008-06-06 22:35:22 +00:00
Tom Lane 600da67fbe Add pg_conf_load_time() function to report when the Postgres configuration
files were last loaded.

George Gensure
2008-05-04 21:13:36 +00:00
Tom Lane ea0382e370 Code review for recent patch to terminate online backup during shutdown:
do CancelBackup at a sane place, fix some oversights in the state transitions,
allow only superusers to connect while we are waiting for backup mode to end.
2008-04-26 22:47:40 +00:00
Magnus Hagander c979a1fefa Prevent shutdown in normal mode if online backup is running, and
have pg_ctl warn about this.

Cancel running online backups (by renaming the backup_label file,
thus rendering the backup useless) when shutting down in fast mode.

Laurenz Albe
2008-04-23 13:44:59 +00:00
Tom Lane 3405f2b925 Use error message wordings for permissions checks on .pgpass and SSL private
key files that are similar to the one for the postmaster's data directory
permissions check.  (I chose to standardize on that one since it's the most
heavily used and presumably best-wordsmithed by now.)  Also eliminate explicit
tests on file ownership in these places, since the ensuing read attempt must
fail anyway if it's wrong, and there seems no value in issuing the same error
message for distinct problems.  (But I left in the explicit ownership test in
postmaster.c, since it had its own error message anyway.)  Also be more
specific in the documentation's descriptions of these checks.  Per a gripe
from Kevin Hunter.
2008-03-31 02:43:14 +00:00
Tom Lane d9384a4b73 Remove postmaster.c's check that NBuffers is at least twice MaxBackends.
With the addition of multiple autovacuum workers, our choices were to delete
the check, document the interaction with autovacuum_max_workers, or complicate
the check to try to hide that interaction.  Since this restriction has never
been adequate to ensure backends can't run out of pinnable buffers, it doesn't
really have enough excuse to live to justify the second or third choices.
Per discussion of a complaint from Andreas Kling (see also bug #3888).

This commit also removes several documentation references to this restriction,
but I'm not sure I got them all.
2008-03-09 04:56:28 +00:00
Tom Lane 870993e871 Rename miscadmin.h's PG_VERSIONSTR macro to PG_BACKEND_VERSIONSTR to
make it a bit clearer what it is, and get rid of duplicate definitions
in initdb and pg_ctl.
2008-02-20 22:46:24 +00:00
Tom Lane e6a442c71b Restructure the shutdown procedure for the archiver process to allow it to
finish archiving everything (when there's no error), and to eliminate various
hazards as best we can.  This fixes a previous 8.3 patch that caused the
postmaster to kill and then restart the archiver during shutdown (!?).

The new behavior is that the archiver is allowed to run unmolested until
the bgwriter has exited; then it is sent SIGUSR2 to tell it to do a final
archiving cycle and quit.  We only SIGQUIT the archiver if we want a panic
stop; this is important since SIGQUIT will also be sent to any active
archive_command.  The postmaster also now doesn't SIGQUIT the stats collector
until the bgwriter is done, since the bgwriter can send stats messages in 8.3.
The postmaster will not exit until both the archiver and stats collector are
gone; this provides some defense (not too bulletproof) against conflicting
archiver or stats collector processes being started by a new postmaster
instance.  We continue the prior practice that the archiver will check
for postmaster death immediately before issuing any archive_command; that
gives some additional protection against conflicting archivers.

Also, modify the archiver process to notice SIGTERM and refuse to issue any
more archive commands if it gets it.  The postmaster doesn't ever send it
SIGTERM; we assume that any such signal came from init and is a notice of
impending whole-system shutdown.  In this situation it seems imprudent to try
to start new archive commands --- if they aren't extremely quick they're
likely to get SIGKILL'd by init.

All per discussion.
2008-01-11 00:54:09 +00:00
Bruce Momjian 9098ab9e32 Update copyrights in source tree to 2008. 2008-01-01 19:46:01 +00:00
Peter Eisentraut 5ca3d50db7 Clarify log messages 2007-12-13 11:55:44 +00:00
Bruce Momjian f6e8730d11 Re-run pgindent with updated list of typedefs. (Updated README should
avoid this problem in the future.)
2007-11-15 22:25:18 +00:00
Bruce Momjian fdf5a5efb7 pgindent run for 8.3. 2007-11-15 21:14:46 +00:00
Peter Eisentraut 166f67cebe Message improvements 2007-11-15 20:04:38 +00:00
Peter Eisentraut b5a47f245f Wording changes 2007-11-08 14:47:51 +00:00
Neil Conway 9a48d22ef5 Use LOG instead of DEBUG2 for logging invalid cancel requests. (That is,
cancel requests with an incorrect key, or with a non-existent PID). Per
recent discussion on -hackers.
2007-11-05 00:00:34 +00:00
Magnus Hagander bb98b2e27e Change win32 child-death tracking code to use a threadpool to wait for
childprocess deaths instead of using one thread per child. This drastastically
reduces the address space usage and should allow for more backends running.

Also change the win32_waitpid functionality to use an IO Completion Port for
queueing child death notices instead of using a fixed-size array.
2007-10-26 21:50:10 +00:00
Tom Lane f18dfc4835 Minor improvements in backup and recovery:
- create a separate archive_mode GUC, on which archive_command is dependent

- %r option in recovery.conf sends last restartpoint to recovery command

- %r used in pg_standby, updated README

- minor other code cleanup in pg_standby

- doc on Warm Standby now mentions pg_standby and %r

- log_restartpoints recovery option emits LOG message at each restartpoint

- end of recovery now displays last transaction end time, as requested
  by Warren Little; also shown at each restartpoint

- restart archiver if needed to carry away WAL files at shutdown

Simon Riggs
2007-09-26 22:36:30 +00:00
Andrew Dunstan fd801f4faa Provide for logfiles in machine readable CSV format. In consequence, rename
redirect_stderr to logging_collector.
Original patch from Arul Shaji, subsequently modified by Greg Smith, and then
heavily modified by me.
2007-08-19 01:41:25 +00:00
Tom Lane bbe3c02d38 Revise postmaster startup/shutdown logic to eliminate the problem that a
constant flow of new connection requests could prevent the postmaster from
completing a shutdown or crash restart.  This is done by labeling child
processes that are "dead ends", that is, we know that they were launched only
to tell a client that it can't connect.  These processes are managed
separately so that they don't confuse us into thinking that we can't advance
to the next stage of a shutdown or restart sequence, until the very end
where we must wait for them to drain out so we can delete the shmem segment.
Per discussion of a misbehavior reported by Keaton Adams.

Since this code was baroque already, and my first attempt at fixing the
problem made it entirely impenetrable, I took the opportunity to rewrite it
in a state-machine style.  That eliminates some duplicated code sections and
hopefully makes everything a bit clearer.
2007-08-09 01:18:43 +00:00
Tom Lane 0b9d3d4dcd Fix a problem in my recent patch to initialize cancel_key for autovac workers
as well as regular backends: if no regular backend launches before the autovac
launcher tries to start an autovac worker, the postmaster would get an Assert
fault due to calling PostmasterRandom before random_seed was initialized.
Cleanest solution seems to be to take the initialization of random_seed out
of ServerLoop and let PostmasterRandom do it for itself.
2007-08-04 03:15:49 +00:00
Tom Lane 73852bd520 Fix some sloppiness in the recent multiple-autovacuum-worker patch. It was
not bothering to initialize is_autovacuum for regular backends, meaning there
was a significant chance of the postmaster prematurely sending them SIGTERM
during database shutdown.  Also, leaving the cancel key unset for an autovac
worker meant that any client could send it SIGINT, which doesn't sound
especially good either.
2007-08-03 20:06:50 +00:00
Andrew Dunstan 63872601e8 Move session_start out of MyProcPort stucture and make it a global called MyStartTime,
so that we will be able to create a cookie for all processes for CSVlogs.
It is set wherever MyProcPid is set. Take the opportunity to remove the now
unnecessary session-only restriction on the %s and %c escapes in log_line_prefix.
2007-08-02 23:39:45 +00:00
Andrew Dunstan b34903453f Make sure syslogPipe runs in binary mode on Windows to avoid corrupting the pipe chunking protocol. Backport to 8.0 2007-08-02 23:15:27 +00:00
Tom Lane ad4295728e Create a new dedicated Postgres process, "wal writer", which exists to write
and fsync WAL at convenient intervals.  For the moment it just tries to
offload this work from backends, but soon it will be responsible for
guaranteeing a maximum delay before asynchronously-committed transactions
will be flushed to disk.

This is a portion of Simon Riggs' async-commit patch, committed to CVS
separately because a background WAL writer seems like it might be a good idea
independently of the async-commit feature.  I rebased walwriter.c on
bgwriter.c because it seemed like a more appropriate way of handling signals;
while the startup/shutdown logic in postmaster.c is more like autovac because
we want walwriter to quit before we start the shutdown checkpoint.
2007-07-24 04:54:09 +00:00
Magnus Hagander f70866fb23 SSPI authentication on Windows. GSSAPI compatible client when doing Kerberos
against a Unix server, and Windows-specific server-side authentication
using SSPI "negotiate" method (Kerberos or NTLM).

Only builds properly with MSVC for now.
2007-07-23 10:16:54 +00:00
Andrew Dunstan 0e5b4f0e23 Only use the pipe chunking protocol if we know the syslogger should
be catching stderr output, and we are not ourselves the
syslogger. Otherwise, go directly to stderr.
Bug noticed by Tom Lane.
Backpatch as far as 8.0.
2007-07-19 19:13:43 +00:00
Magnus Hagander 31013db0a1 A bunch of GSSAPI fixes per comments from Tom:
* use elog not ereport for debug
* fix debug levels for some output
* properly check for memory allocation errors in a couple of missed places
2007-07-11 08:27:33 +00:00
Magnus Hagander 6160106c74 Add support for GSSAPI authentication.
Documentation still being written, will be committed later.

Henry B. Hotz and Magnus Hagander
2007-07-10 13:14:22 +00:00
Tom Lane 421d50273f Treat the autovac launcher more like a regular backend, in that we wait
for it to die before telling the bgwriter to initiate shutdown checkpoint.
Since it's connected to shared memory, this seems more prudent than the
alternative of letting it quit asynchronously.  Resolves my complaint
of yesterday about repeated shutdown checkpoints in CVS HEAD.
2007-07-01 18:28:41 +00:00
Alvaro Herrera 10af02b912 Arrange for SIGINT in autovacuum workers to cancel the current table and
continue with the schedule.  Change current uses of SIGINT to abort a worker
into SIGTERM, which keeps the old behaviour of terminating the process.

Patch from ITAGAKI Takahiro, with some editorializing of my own.
2007-06-29 17:07:39 +00:00
Alvaro Herrera bae0b56880 Improve autovacuum launcher's ability to detect a problem in worker startup,
by having the postmaster signal it when certain failures occur.  This requires
the postmaster setting a flag in shared memory, but should be as safe as the
pmsignal.c code is.

Also make sure the launcher honor's a postgresql.conf change turning it off
on SIGHUP.
2007-06-25 16:09:03 +00:00
Bruce Momjian 686956375a Allow the pgstat process to restart immediately after a receiving
SIGQUIT signal, rather than waiting for PGSTAT_RESTART_INTERVAL.
2007-03-22 19:53:31 +00:00
Alvaro Herrera 626eb02198 Cleanup the bootstrap code a little, and rename "dummy procs" in the code
comments and variables to "auxiliary proc", per Heikki's request.
2007-03-07 13:35:03 +00:00
Tom Lane b6c9165ea0 Code review for SSLKEY patch. 2007-02-16 17:07:00 +00:00
Bruce Momjian c7b08050d9 SSL improvements:
o read global SSL configuration file
	o add GUC "ssl_ciphers" to control allowed ciphers
	o add libpq environment variable PGSSLKEY to control SSL hardware keys

Victor B. Wagner
2007-02-16 02:59:41 +00:00
Alvaro Herrera 68046a20c7 Remove useless database name from bootstrap argument processing (including
startup and bgwriter processes), and the -y flag.  It's not used anywhere.
2007-02-16 02:10:07 +00:00
Alvaro Herrera 1820650934 Restructure autovacuum in two processes: a dummy process, which runs
continuously, and requests vacuum runs of "autovacuum workers" to postmaster.
The workers do the actual vacuum work.  This allows for future improvements,
like allowing multiple autovacuum jobs running in parallel.

For now, the code keeps the original behavior of having a single autovac
process at any time by sleeping until the previous worker has finished.
2007-02-15 23:23:23 +00:00
Tom Lane cf4cc7843c Improve postmaster's behavior if an accept() call fails. Because the server
socket is still read-ready, the code was a tight loop, wasting lots of CPU.
We can't do anything to clear the failure, other than wait, but we should give
other processes more chance to finish and release FDs; so insert a small sleep.
Also, avoid bogus "close(-1)" in this case.  Per report from Jim Nasby.
2007-02-13 19:18:54 +00:00
Magnus Hagander b8188e1e64 Fix for early log messages during postmaster startup getting lost when
running as a service on Win32.

Per report from Harald Armin Massa.
2007-02-11 11:59:26 +00:00
Peter Eisentraut 4ab8fcba8a StrNCpy -> strlcpy (not complete) 2007-02-10 14:58:55 +00:00
Bruce Momjian a37b006d89 This patch fixes shared_preload_libraries on Windows hosts. It forces
ach backend to re-load all shared_preload_libraries.

Korry Douglas
2007-02-08 15:46:04 +00:00
Tom Lane 78d1216160 Remove the xlog-centric "database system is ready" message and replace it with
"database system is ready to accept connections", which is issued by the
postmaster when it really is ready to accept connections.  Per proposal from
Markus Schiltknecht and subsequent discussion.
2007-02-07 16:44:48 +00:00
Bruce Momjian 5b4fa95984 Update process termination message to display signal number and name
from exec.c and postmaster.c.
2007-01-29 20:17:40 +00:00
Tom Lane a9fa52504f Clean up broken usage of HAVE_DECL_SYS_SIGLIST and inconsistent/poorly
formatted error messages.
2007-01-28 06:32:03 +00:00
Bruce Momjian 91ed399517 Use autoconf build-in sys_siglist macro AC_DECL_SYS_SIGLIST, rather than
create our own.
2007-01-28 03:50:34 +00:00
Bruce Momjian 82480fc254 Use sys_siglist[] to print out signal names for signal exits, rather
than just numbers.
2007-01-28 01:12:05 +00:00
Bruce Momjian 882b9948d7 Back out use of FormatMessage(), does error values, not exception
values.  Point to /include/ntstatus.h for an exception list, rather than
a URL.
2007-01-23 03:28:49 +00:00
Bruce Momjian 610f60a092 Print meaningfull error text for abonormal process exit on Win32, rather
than hex codes, using FormatMessage().
2007-01-23 01:45:11 +00:00
Bruce Momjian 45e0736938 Use errhint() for WIN32 SIGTERM message, where possible. 2007-01-22 19:38:05 +00:00
Bruce Momjian 208ae0c290 When system() fails in Win32, report it as an exception, print the
exception value in hex, and give a URL where the value can be looked-up.
2007-01-22 18:31:51 +00:00
Alvaro Herrera eb63cc3da8 Arrange for autovacuum to be killed when another operation wants to be alone
accessing it, like DROP DATABASE.  This allows the regression tests to pass
with autovacuum enabled, which open the gates for finally enabling autovacuum
by default.
2007-01-16 13:28:57 +00:00
Bruce Momjian 29dccf5fe0 Update CVS HEAD for 2007 copyright. Back branches are typically not
back-stamped for this.
2007-01-05 22:20:05 +00:00
Tom Lane eeb2189112 Fix erroneous implementation of -s in postmaster.c (the switch doesn't take
an optarg).  Add some comments noting that code in three different files has
to be kept in sync.  Fix erroneous description of -S switch (it sets work_mem
not silent_mode), and do some light copy-editing elsewhere in postgres-ref.
2007-01-04 00:57:51 +00:00
Tom Lane 5f60086e10 Minor adjustments to make failures in startup/shutdown behave more cleanly.
StartupXLOG and ShutdownXLOG no longer need to be critical sections, because
in all contexts where they are invoked, elog(ERROR) would be translated to
elog(FATAL) anyway.  (One change in bgwriter.c is needed to make this true:
set ExitOnAnyError before trying to exit.  This is a good fix anyway since
the existing code would have gone into an infinite loop on elog(ERROR) during
shutdown.)  That avoids a misleading report of PANIC during semi-orderly
failures.  Modify the postmaster to include the startup process in the set of
processes that get SIGTERM when a fast shutdown is requested, and also fix it
to not try to restart the bgwriter if the bgwriter fails while trying to write
the shutdown checkpoint.  Net result is that "pg_ctl stop -m fast" does
something reasonable for a system in warm standby mode, and so should Unix
system shutdown (ie, universal SIGTERM).  Per gripe from Stephen Harris and
some corner-case testing of my own.
2006-11-30 18:29:12 +00:00
Peter Eisentraut a75ccd1def Fix some translator comments so that xgettext finds them and pgindent does
not destroy them.  Maybe we can adjust pgindent sometime.
2006-11-28 12:54:42 +00:00
Tom Lane 3ad0728c81 On systems that have setsid(2) (which should be just about everything except
Windows), arrange for each postmaster child process to be its own process
group leader, and deliver signals SIGINT, SIGTERM, SIGQUIT to the whole
process group not only the direct child process.  This provides saner behavior
for archive and recovery scripts; in particular, it's possible to shut down a
warm-standby recovery server using "pg_ctl stop -m immediate", since delivery
of SIGQUIT to the startup subprocess will result in killing the waiting
recovery_command.  Also, this makes Query Cancel and statement_timeout apply
to scripts being run from backends via system().  (There is no support in the
core backend for that, but it's widely done using untrusted PLs.)  Per gripe
from Stephen Harris and subsequent discussion.
2006-11-21 20:59:53 +00:00
Tom Lane e82d9e6283 Adjust elog.c so that elog(FATAL) exits (including cases where ERROR is
promoted to FATAL) end in exit(1) not exit(0).  Then change the postmaster to
allow exit(1) without a system-wide panic, but not for the startup subprocess
or the bgwriter.  There were a couple of places that were using exit(1) to
deliberately force a system-wide panic; adjust these to be exit(2) instead.
This fixes the problem noted back in July that if the startup process exits
with elog(ERROR), the postmaster would think everything is hunky-dory and
proceed to start up.  Alternative solutions such as trying to run the entire
startup process as a critical section seem less clean, primarily because of
the fact that a fair amount of startup code is shared by all postmaster
children in the EXEC_BACKEND case.  We'd need an ugly special case somewhere
near the head of main.c to make it work if it's the child process's
responsibility to determine what happens; and what's the point when the
postmaster already treats different children differently?
2006-11-21 00:49:55 +00:00
Tom Lane 48188e1621 Fix recently-understood problems with handling of XID freezing, particularly
in PITR scenarios.  We now WAL-log the replacement of old XIDs with
FrozenTransactionId, so that such replacement is guaranteed to propagate to
PITR slave databases.  Also, rather than relying on hint-bit updates to be
preserved, pg_clog is not truncated until all instances of an XID are known to
have been replaced by FrozenTransactionId.  Add new GUC variables and
pg_autovacuum columns to allow management of the freezing policy, so that
users can trade off the size of pg_clog against the amount of freezing work
done.  Revise the already-existing code that forces autovacuum of tables
approaching the wraparound point to make it more bulletproof; also, revise the
autovacuum logic so that anti-wraparound vacuuming is done per-table rather
than per-database.  initdb forced because of changes in pg_class, pg_database,
and pg_autovacuum catalogs.  Heikki Linnakangas, Simon Riggs, and Tom Lane.
2006-11-05 22:42:10 +00:00
Bruce Momjian f99a569a2e pgindent run for 8.2. 2006-10-04 00:30:14 +00:00
Tom Lane abc3120e9b Add server support for "plugin" libraries that can be used for add-on tasks
such as debugging and performance measurement.  This consists of two features:
a table of "rendezvous variables" that allows separately-loaded shared
libraries to communicate, and a new GUC setting "local_preload_libraries"
that allows libraries to be loaded into specific sessions without explicit
cooperation from the client application.  To make local_preload_libraries
as flexible as possible, we do not restrict its use to superusers; instead,
it is restricted to load only libraries stored in $libdir/plugins/.  The
existing LOAD command has also been modified to allow non-superusers to
LOAD libraries stored in this directory.

This patch also renames the existing GUC variable preload_libraries to
shared_preload_libraries (after a suggestion by Simon Riggs) and does some
code refactoring in dfmgr.c to improve clarity.

Korry Douglas, with a little help from Tom Lane.
2006-08-15 18:26:59 +00:00
Tom Lane b09bfcaa57 Add a feature for automatic initialization and finalization of dynamically
loaded libraries: call functions _PG_init() and _PG_fini() if the library
defines such symbols.  Hence we no longer need to specify an initialization
function in preload_libraries: we can assume that the library used the
_PG_init() convention, instead.  This removes one source of pilot error
in use of preloaded libraries.  Original patch by Ralf Engelschall,
preload_libraries changes by me.
2006-08-08 19:15:09 +00:00
Tom Lane 033a477e9e Adjust initialization sequence for timezone_abbreviations so that
it's handled just about like timezone; in particular, don't try
to read anything during InitializeGUCOptions.  Should solve current
startup failure on Windows, and avoid wasted cycles if a nondefault
setting is specified in postgresql.conf too.  Possibly we need to
think about a more general solution for handling 'expensive to set'
GUC options.
2006-07-29 03:02:56 +00:00
Tom Lane d0e4a076d1 Make the order of operations in PostmasterMain a bit saner ... some
recent patches had added stuff in rather random spots.
2006-07-25 01:23:34 +00:00
Tom Lane e96373aae5 Ensure that we retry rather than erroring out when send() or recv() return
EINTR; the stats code was failing to do this and so were a couple of places
in the postmaster.  The stats code assumed that recv() could not return EINTR
if a preceding select() showed the socket to be read-ready, but this is
demonstrably false with our Windows implementation of recv(), and it may
not be the case on all Unix variants either.  I think this explains the
intermittent stats regression test failures we've been seeing, as well
as reports of stats collector instability under high load on Windows.

Backpatch as far as 8.0.
2006-07-16 18:17:14 +00:00
Tom Lane daecd97617 Put back some more not-so-unused-as-all-that #includes. This un-breaks
the EXEC_BACKEND code on my machines, so hopefully it will fix the
Windows buildfarm members.
2006-07-15 15:47:17 +00:00
Bruce Momjian e0522505bd Remove 576 references of include files that were not needed. 2006-07-14 14:52:27 +00:00
Bruce Momjian a22d76d96a Allow include files to compile own their own.
Strip unused include files out unused include files, and add needed
includes to C files.

The next step is to remove unused include files in C files.
2006-07-13 16:49:20 +00:00
Alvaro Herrera d4cef0aa2a Improve vacuum code to track minimum Xids per table instead of per database.
To this end, add a couple of columns to pg_class, relminxid and relvacuumxid,
based on which we calculate the pg_database columns after each vacuum.

We now force all databases to be vacuumed, even template ones.  A backend
noticing too old a database (meaning pg_database.datminxid is in danger of
falling behind Xid wraparound) will signal the postmaster, which in turn will
start an autovacuum iteration to process the offending database.  In principle
this is only there to cope with frozen (non-connectable) databases without
forcing users to set them to connectable, but it could force regular user
database to go through a database-wide vacuum at any time.  Maybe we should
warn users about this somehow.  Of course the real solution will be to use
autovacuum all the time ;-)

There are some additional improvements we could have in this area: for example
the vacuum code could be smarter about not updating pg_database for each table
when called by autovacuum, and do it only once the whole autovacuum iteration
is done.

I updated the system catalogs documentation, but I didn't modify the
maintenance section.  Also having some regression tests for this would be nice
but it's not really a very straightforward thing to do.

Catalog version bumped due to system catalog changes.
2006-07-10 16:20:52 +00:00
Tom Lane 51e400c9c6 Remove the separate 'stats buffer' process, letting backend stats messages
be delivered directly to the collector process.  The extra process context
swaps required to transfer data through the buffer process seem to outweigh
any value the buffering might have.  Per recent discussion and tests.
I modified Bruce's draft patch to use poll() rather than select() where
available (this makes a noticeable difference on my system), and fixed
up the EXEC_BACKEND case.
2006-06-29 20:00:08 +00:00
Bruce Momjian 370a709c75 Add GUC update_process_title to control whether 'ps' display is updated
for every command, default to on.
2006-06-27 22:16:44 +00:00
Tom Lane 27c3e3de09 Remove redundant gettimeofday() calls to the extent practical without
changing semantics too much.  statement_timestamp is now set immediately
upon receipt of a client command message, and the various places that used
to do their own gettimeofday() calls to mark command startup are referenced
to that instead.  I have also made stats_command_string use that same
value for pg_stat_activity.query_start for both the command itself and
its eventual replacement by <IDLE> or <idle in transaction>.  There was
some debate about that, but no argument that seemed convincing enough to
justify an extra gettimeofday() call.
2006-06-20 22:52:00 +00:00
Tom Lane b13c9686d0 Take the statistics collector out of the loop for monitoring backends'
current commands; instead, store current-status information in shared
memory.  This substantially reduces the overhead of stats_command_string
and also ensures that pg_stat_activity is fully up to date at all times.
Per my recent proposal.
2006-06-19 01:51:22 +00:00
Peter Eisentraut 5266f221a2 Merge postmaster and postgres command into just postgres. postmaster
symlink is kept for now for compatibility.  To call single-user mode, use
postgres --single.
2006-06-18 15:38:37 +00:00
Bruce Momjian 399a36a75d Prepare code to be built by MSVC:
o  remove many WIN32_CLIENT_ONLY defines
	o  add WIN32_ONLY_COMPILER define
	o  add 3rd argument to open() for portability
	o  add include/port/win32_msvc directory for
	   system includes

Magnus Hagander
2006-06-07 22:24:46 +00:00
Alvaro Herrera 49b3462abb Have autovacuum report its activities to the stat collector. 2006-05-19 15:15:37 +00:00
Neil Conway a5dba02359 The call to DNSServiceRegistrationCreate in postmaster.c does incorrect
byte-swapping on the port number which causes the call to fail on Intel
Macs.

This patch uses htons() instead of htonl() and fixes this bug.

Ashley Clark
2006-03-18 22:09:58 +00:00
Bruce Momjian f2f5b05655 Update copyright for 2006. Update scripts. 2006-03-05 15:59:11 +00:00
Bruce Momjian 47a86fa02d Add code comment about Linux stack randomization and shared memory. 2006-02-01 16:00:06 +00:00
Bruce Momjian 62a142036b Set progname early in the postmaster/postgres binary, rather than doing
it later.  This fixes a problem where EXEC_BACKEND didn't have progname
set, causing a segfault if log_min_messages was set below debug2 and our
own snprintf.c was being used.

Also alway strdup() progname.

Backpatch to 8.1.X and 8.0.X.
2006-02-01 00:31:59 +00:00
Tom Lane a7812eb4be Fix Windows-only postmaster code to reject a connection request and continue,
rather than elog(FATAL), when there is no more room in ShmemBackendArray.
This is a security issue since too many connection requests arriving close
together could cause the postmaster to shut down, resulting in denial of
service.  Reported by Yoshiyuki Asaba, fixed by Magnus Hagander.
2006-01-06 02:58:25 +00:00
Peter Eisentraut 86c23a6eb2 Make all command-line options of postmaster and postgres the same. See
http://archives.postgresql.org/pgsql-hackers/2006-01/msg00151.php for the
complete plan.
2006-01-05 10:07:46 +00:00
Tom Lane 349f40b2c2 Rearrange backend startup sequence so that ShmemIndexLock can become
an LWLock instead of a spinlock.  This hardly matters on Unix machines
but should improve startup performance on Windows (or any port using
EXEC_BACKEND).  Per previous discussion.
2006-01-04 21:06:32 +00:00
Bruce Momjian 436a2956d8 Re-run pgindent, fixing a problem where comment lines after a blank
comment line where output as too long, and update typedefs for /lib
directory.  Also fix case where identifiers were used as variable names
in the backend, but as typedefs in ecpg (favor the backend for
indenting).

Backpatch to 8.1.X.
2005-11-22 18:17:34 +00:00
Tom Lane 48052de722 Repair an error introduced by log_line_prefix patch: it is not acceptable
to assume that the string pointer passed to set_ps_display is good forever.
There's no need to anyway since ps_status.c itself saves the string, and
we already had an API (get_ps_display) to return it.
I believe this explains Jim Nasby's report of intermittent crashes in
elog.c when %i format code is in use in log_line_prefix.
While at it, repair a previously unnoticed problem: on some platforms such as
Darwin, the string returned by get_ps_display was blank-padded to the maximum
length, meaning that lock.c's attempt to append " waiting" to it never worked.
2005-11-05 03:04:53 +00:00
Alvaro Herrera 66294e13fb Fix one overlooked ocurrence of "None" in EXEC_BACKEND block. 2005-11-03 20:02:50 +00:00
Alvaro Herrera 902377c465 Rename the members of CommandDest enum so they don't collide with other uses of
those names.  (Debug and None were pretty bad names anyway.)  I hope I catched
all uses of the names in comments too.
2005-11-03 17:11:40 +00:00
Andrew Dunstan 188c52497d minor code cleanup - replace useless struct timezone argument to
gettimeofday with NULL in a few places, making it consistent with
usage elsewhere.
2005-10-22 14:27:29 +00:00
Tom Lane 78ce809216 Postpone pg_timezone_initialize() until after creation of postmaster.pid,
since it can take a fair amount of time and this can confuse boot scripts
that expect postmaster.pid to appear quickly.  Move initialization of SSL
library and preloaded libraries to after that point, too, just for luck.
Per reports from Tony Caduto and others.
2005-10-20 20:05:45 +00:00
Tom Lane d330f1554d Clean up libpq's pollution of application namespace by renaming the
exported routines of ip.c, md5.c, and fe-auth.c to begin with 'pg_'.
Also get rid of the vestigial fe_setauthsvc/fe_getauthsvc routines
altogether.
2005-10-17 16:24:20 +00:00
Bruce Momjian 1dc3498251 Standard pgindent run for 8.1. 2005-10-15 02:49:52 +00:00
Bruce Momjian a3b9c6988d Suppress port number for unix domain sockets in log connect/disconnect
messages.
2005-09-22 15:33:36 +00:00
Tom Lane 0007490e09 Convert the arithmetic for shared memory size calculation from 'int'
to 'Size' (that is, size_t), and install overflow detection checks in it.
This allows us to remove the former arbitrary restrictions on NBuffers
etc.  It won't make any difference in a 32-bit machine, but in a 64-bit
machine you could theoretically have terabytes of shared buffers.
(How efficiently we could manage 'em remains to be seen.)  Similarly,
num_temp_buffers, work_mem, and maintenance_work_mem can be set above
2Gb on a 64-bit machine.  Original patch from Koichi Suzuki, additional
work by moi.
2005-08-20 23:26:37 +00:00
Bruce Momjian 3b0ee862d6 Reverse out changes to canonicalize_path(), per suggestion from Tom. 2005-08-12 19:43:32 +00:00
Bruce Momjian 35379e9079 Modify canonicalize_path() so if we would return a trailing "..", throw
an error instead.
2005-08-12 19:42:45 +00:00
Tom Lane a43ea120bf Code & docs review for server instrumentation patch. File timestamps
should surely be timestamptz not timestamp; fix some but not all of the
holes in check_and_make_absolute(); other minor cleanup.  Also put in
the missed catversion bump.
2005-08-12 18:23:56 +00:00
Bruce Momjian b609695b7a Add files to do read I/O on the cluster directory:
pg_stat_file()
	pg_read_file()
	pg_ls_dir()
	pg_reload_conf()
	pg_rotate_logfile()

Dave Page
Andreas Pflug
2005-08-12 03:25:13 +00:00
Tom Lane d90c531188 Autovacuum loose end mop-up. Provide autovacuum-specific vacuum cost
delay and limit, both as global GUCs and as table-specific entries in
pg_autovacuum.  stats_reset_on_server_start is now OFF by default,
but a reset is forced if we did WAL replay.  XID-wrap vacuums do not
ANALYZE, but do FREEZE if it's a template database.  Alvaro Herrera
2005-08-11 21:11:50 +00:00
Tom Lane 5d5f1a79e6 Clean up a number of autovacuum loose ends. Make the stats collector
track shared relations in a separate hashtable, so that operations done
from different databases are counted correctly.  Add proper support for
anti-XID-wraparound vacuuming, even in databases that are never connected
to and so have no stats entries.  Miscellaneous other bug fixes.
Alvaro Herrera, some additional fixes by Tom Lane.
2005-07-29 19:30:09 +00:00
Bruce Momjian a536b2dd80 Add time/date macros for code clarity:
#define DAYS_PER_YEAR   365.25
	#define MONTHS_PER_YEAR 12
	#define DAYS_PER_MONTH  30
	#define HOURS_PER_DAY   24
2005-07-21 03:56:25 +00:00
Tom Lane 29094193f5 Integrate autovacuum functionality into the backend. There's still a
few loose ends to be dealt with, but it seems to work.  Alvaro Herrera,
based on the contrib code by Matthew O'Connor.
2005-07-14 05:13:45 +00:00
Tom Lane eb5949d190 Arrange for the postmaster (and standalone backends, initdb, etc) to
chdir into PGDATA and subsequently use relative paths instead of absolute
paths to access all files under PGDATA.  This seems to give a small
performance improvement, and it should make the system more robust
against naive DBAs doing things like moving a database directory that
has a live postmaster in it.  Per recent discussion.
2005-07-04 04:51:52 +00:00
Peter Eisentraut 7a30b1fb96 Issue fatal error if no TCP/IP sockets could be created 2005-06-30 10:02:22 +00:00
Tom Lane b5f7cff84f Clean up the rather historically encumbered interface to now() and
current time: provide a GetCurrentTimestamp() function that returns
current time in the form of a TimestampTz, instead of separate time_t
and microseconds fields.  This is what all the callers really want
anyway, and it eliminates low-level dependencies on AbsoluteTime,
which is a deprecated datatype that will have to disappear eventually.
2005-06-29 22:51:57 +00:00
Tom Lane 7762619e95 Replace pg_shadow and pg_group by new role-capable catalogs pg_authid
and pg_auth_members.  There are still many loose ends to finish in this
patch (no documentation, no regression tests, no pg_dump support for
instance).  But I'm going to commit it now anyway so that Alvaro can
make some progress on shared dependencies.  The catalog changes should
be pretty much done.
2005-06-28 05:09:14 +00:00
Tom Lane d0a89683a3 Two-phase commit. Original patch by Heikki Linnakangas, with additional
hacking by Alvaro Herrera and Tom Lane.
2005-06-17 22:32:51 +00:00
Bruce Momjian f5835b4b8d Add pg_postmaster_start_time() function.
Euler Taveira de Oliveira
Matthias Schmidt
2005-06-14 21:04:42 +00:00
Tom Lane 7974c35020 Fix typo in comment, per Alvaro. 2005-06-09 22:01:12 +00:00
Bruce Momjian c9a382b2ed Rename Rendezvous to Bonjour to match OS/X renaming. 2005-05-15 00:26:19 +00:00
Tom Lane e6befdc9d1 Kerberos fixes from Magnus Hagander --- in theory Kerberos 5 auth
should work on Windows now.  Also, rename set_noblock to pg_set_noblock;
since it is included in libpq, the former name polluted application
namespace.
2005-03-25 00:34:31 +00:00
Bruce Momjian 7604267de8 Set socket timer to 58 instead of 60 minutes for hour-old cleaners:
* Touch the socket and lock file at least every hour, to
         * ensure that they are not removed by overzealous /tmp-cleaning
         * tasks.  Set to 58 minutes so a cleaner never sees the
         * file as an hour old.
2005-03-24 18:16:17 +00:00
Bruce Momjian 218705958a Touch postmaster log file every hour, rather than every 10 minutes, to
prevent complaints from laptop users who don't like their hard drives
starting up every 10 minutes.
2005-03-24 05:19:05 +00:00
Tom Lane 7a969cad2e Treat EPERM as a non-error case when checking to see if old postmaster
is still alive.  This improves our odds of not getting fooled by an
unrelated process when checking a stale lock file.  Other checks already
in place, plus one newly added in checkDataDir(), ensure that we cannot
attempt to usurp the place of a postmaster belonging to a different userid,
so there is no need to error out.  Add comments indicating the importance
of these other checks.
2005-03-18 03:48:49 +00:00
Neil Conway 164adc4d39 Refactor fork()-related code. We need to do various housekeeping tasks
before we can invoke fork() -- flush stdio buffers, save and restore the
profiling timer on Linux with LINUX_PROFILE, and handle BeOS stuff. This
patch moves that code into a single function, fork_process(), instead of
duplicating it at the various callsites of fork().

This patch doesn't address the EXEC_BACKEND case; there is room for
further cleanup there.
2005-03-10 07:14:03 +00:00
Bruce Momjian 0542b1e2fe Use _() macro consistently rather than gettext(). Add translation
macros around strings that were missing them.
2005-02-22 04:43:23 +00:00
Tom Lane 60b2444cc3 Add code to prevent transaction ID wraparound by enforcing a safe limit
in GetNewTransactionId().  Since the limit value has to be computed
before we run any real transactions, this requires adding code to database
startup to scan pg_database and determine the oldest datfrozenxid.
This can conveniently be combined with the first stage of an attack on
the problem that the 'flat file' copies of pg_shadow and pg_group are
not properly updated during WAL recovery.  The code I've added to
startup resides in a new file src/backend/utils/init/flatfiles.c, and
it is responsible for rewriting the flat files as well as initializing
the XID wraparound limit value.  This will eventually allow us to get
rid of GetRawDatabaseInfo too, but we'll need an initdb so we can add
a trigger to pg_database.
2005-02-20 02:22:07 +00:00
Tom Lane 8251e0b2fb Increase MAXLISTEN to a more generous value, and add an error message
telling when it has been exceeded.  Per trouble report from
Jean-GÅrard Pailloncy.
2005-01-12 16:38:17 +00:00
PostgreSQL Daemon 2ff501590b Tag appropriate files for rc3
Also performed an initial run through of upgrading our Copyright date to
extend to 2005 ... first run here was very simple ... change everything
where: grep 1996-2004 && the word 'Copyright' ... scanned through the
generated list with 'less' first, and after, to make sure that I only
picked up the right entries ...
2004-12-31 22:04:05 +00:00
Tom Lane eee5abce46 Refactor EXEC_BACKEND code so that postmaster child processes reattach
to shared memory as soon as possible, ie, right after read_backend_variables.
The effective difference from the original code is that this happens
before instead of after read_nondefault_variables(), which loads GUC
information and is apparently capable of expanding the backend's memory
allocation more than you'd think it should.  This should fix the
failure-to-attach-to-shared-memory reports we've been seeing on Windows.
Also clean up a few bits of unnecessarily grotty EXEC_BACKEND code.
2004-12-29 21:36:09 +00:00
Neil Conway 2fa36d7e41 Win32 build cleanups, from Andrew Dunstan. 2004-11-17 08:30:11 +00:00
Tom Lane 0021ae06be Fix Win32 problems with signals and sockets, by making the forkexec code
even uglier than it was already :-(.  Also, on Windows only, use temporary
shared memory segments instead of ordinary files to pass over critical
variable values from postmaster to child processes.  Magnus Hagander
2004-11-17 00:14:14 +00:00
Tom Lane ea23ec82c2 Remove GUC USERLIMIT variable category, making the affected variables
plain SUSET instead.  Also delay processing of options received in
client connection request until after we know if the user is a superuser,
so that SUSET values can be set that way by legitimate superusers.
Per recent discussion.
2004-11-14 19:35:35 +00:00
Peter Eisentraut 3c093ff151 Clarify some error messages 2004-11-09 13:01:27 +00:00
Bruce Momjian 0c3663b47d Add comment to postmaster.c that get_progname() will call exit if it
can't strdup().
2004-11-02 03:34:50 +00:00
Tom Lane 380bd04c16 Standardize on using the Min, Max, and Abs macros that are in our c.h file,
getting rid of numerous ad-hoc versions that have popped up in various
places.  Shortens code and avoids conflict with Windows min() and max()
macros.
2004-10-21 19:28:36 +00:00