1 /*-------------------------------------------------------------------------
3 * pg_ctl --- start/stops/restarts the PostgreSQL server
5 * Portions Copyright (c) 1996-2022, PostgreSQL Global Development Group
7 * src/bin/pg_ctl/pg_ctl.c
9 *-------------------------------------------------------------------------
12 #include "postgres_fe.h"
17 #include <sys/resource.h>
24 #include "catalog/pg_control.h"
25 #include "common/controldata_utils.h"
26 #include "common/file_perm.h"
27 #include "common/logging.h"
28 #include "common/string.h"
29 #include "getopt_long.h"
30 #include "utils/pidfile.h"
32 #ifdef WIN32 /* on Unix, we don't need libpq */
33 #include "pqexpbuffer.h"
36 /* PID can be negative for standalone backend */
50 POSTMASTER_STILL_STARTING
,
68 RUN_AS_SERVICE_COMMAND
71 #define DEFAULT_WAIT 60
73 #define USEC_PER_SEC 1000000
75 #define WAITS_PER_SEC 10 /* should divide USEC_PER_SEC evenly */
77 static bool do_wait
= true;
78 static int wait_seconds
= DEFAULT_WAIT
;
79 static bool wait_seconds_arg
= false;
80 static bool silent_mode
= false;
81 static ShutdownMode shutdown_mode
= FAST_MODE
;
82 static int sig
= SIGINT
; /* default */
83 static CtlCommand ctl_command
= NO_COMMAND
;
84 static char *pg_data
= NULL
;
85 static char *pg_config
= NULL
;
86 static char *pgdata_opt
= NULL
;
87 static char *post_opts
= NULL
;
88 static const char *progname
;
89 static char *log_file
= NULL
;
90 static char *exec_path
= NULL
;
91 static char *event_source
= NULL
;
92 static char *register_servicename
= "PostgreSQL"; /* FIXME: + version ID? */
93 static char *register_username
= NULL
;
94 static char *register_password
= NULL
;
95 static char *argv0
= NULL
;
96 static bool allow_core_files
= false;
97 static time_t start_time
;
99 static char postopts_file
[MAXPGPATH
];
100 static char version_file
[MAXPGPATH
];
101 static char pid_file
[MAXPGPATH
];
102 static char backup_file
[MAXPGPATH
];
103 static char promote_file
[MAXPGPATH
];
104 static char logrotate_file
[MAXPGPATH
];
106 static volatile pgpid_t postmasterPID
= -1;
109 static DWORD pgctl_start_type
= SERVICE_AUTO_START
;
110 static SERVICE_STATUS status
;
111 static SERVICE_STATUS_HANDLE hStatus
= (SERVICE_STATUS_HANDLE
) 0;
112 static HANDLE shutdownHandles
[2];
114 #define shutdownEvent shutdownHandles[0]
115 #define postmasterProcess shutdownHandles[1]
119 static void write_stderr(const char *fmt
,...) pg_attribute_printf(1, 2);
120 static void do_advice(void);
121 static void do_help(void);
122 static void set_mode(char *modeopt
);
123 static void set_sig(char *signame
);
124 static void do_init(void);
125 static void do_start(void);
126 static void do_stop(void);
127 static void do_restart(void);
128 static void do_reload(void);
129 static void do_status(void);
130 static void do_promote(void);
131 static void do_logrotate(void);
132 static void do_kill(pgpid_t pid
);
133 static void print_msg(const char *msg
);
134 static void adjust_data_dir(void);
137 #include <versionhelpers.h>
138 static bool pgwin32_IsInstalled(SC_HANDLE
);
139 static char *pgwin32_CommandLine(bool);
140 static void pgwin32_doRegister(void);
141 static void pgwin32_doUnregister(void);
142 static void pgwin32_SetServiceStatus(DWORD
);
143 static void WINAPI
pgwin32_ServiceHandler(DWORD
);
144 static void WINAPI
pgwin32_ServiceMain(DWORD
, LPTSTR
*);
145 static void pgwin32_doRunAsService(void);
146 static int CreateRestrictedProcess(char *cmd
, PROCESS_INFORMATION
*processInfo
, bool as_service
);
147 static PTOKEN_PRIVILEGES
GetPrivilegesToDelete(HANDLE hToken
);
150 static pgpid_t
get_pgpid(bool is_status_request
);
151 static char **readfile(const char *path
, int *numlines
);
152 static void free_readfile(char **optlines
);
153 static pgpid_t
start_postmaster(void);
154 static void read_post_opts(void);
156 static WaitPMResult
wait_for_postmaster_start(pgpid_t pm_pid
, bool do_checkpoint
);
157 static bool wait_for_postmaster_stop(void);
158 static bool wait_for_postmaster_promote(void);
159 static bool postmaster_is_alive(pid_t pid
);
161 #if defined(HAVE_GETRLIMIT)
162 static void unlimit_core_size(void);
165 static DBState
get_control_dbstate(void);
170 write_eventlog(int level
, const char *line
)
172 static HANDLE evtHandle
= INVALID_HANDLE_VALUE
;
174 if (silent_mode
&& level
== EVENTLOG_INFORMATION_TYPE
)
177 if (evtHandle
== INVALID_HANDLE_VALUE
)
179 evtHandle
= RegisterEventSource(NULL
,
180 event_source
? event_source
: DEFAULT_EVENT_SOURCE
);
181 if (evtHandle
== NULL
)
183 evtHandle
= INVALID_HANDLE_VALUE
;
188 ReportEvent(evtHandle
,
191 0, /* All events are Id 0 */
201 * Write errors to stderr (or by equal means when stderr is
205 write_stderr(const char *fmt
,...)
211 /* On Unix, we just fprintf to stderr */
212 vfprintf(stderr
, fmt
, ap
);
216 * On Win32, we print to stderr if running on a console, or write to
217 * eventlog if running as a service
219 if (pgwin32_is_service()) /* Running as a service */
221 char errbuf
[2048]; /* Arbitrary size? */
223 vsnprintf(errbuf
, sizeof(errbuf
), fmt
, ap
);
225 write_eventlog(EVENTLOG_ERROR_TYPE
, errbuf
);
228 /* Not running as service, write to stderr */
229 vfprintf(stderr
, fmt
, ap
);
235 * Given an already-localized string, print it to stdout unless the
236 * user has specified that no messages should be printed.
239 print_msg(const char *msg
)
249 get_pgpid(bool is_status_request
)
255 if (stat(pg_data
, &statbuf
) != 0)
258 write_stderr(_("%s: directory \"%s\" does not exist\n"), progname
,
261 write_stderr(_("%s: could not access directory \"%s\": %s\n"), progname
,
262 pg_data
, strerror(errno
));
265 * The Linux Standard Base Core Specification 3.1 says this should
266 * return '4, program or service status is unknown'
267 * https://refspecs.linuxbase.org/LSB_3.1.0/LSB-Core-generic/LSB-Core-generic/iniscrptact.html
269 exit(is_status_request
? 4 : 1);
272 if (stat(version_file
, &statbuf
) != 0 && errno
== ENOENT
)
274 write_stderr(_("%s: directory \"%s\" is not a database cluster directory\n"),
276 exit(is_status_request
? 4 : 1);
279 pidf
= fopen(pid_file
, "r");
282 /* No pid file, not an error on startup */
287 write_stderr(_("%s: could not open PID file \"%s\": %s\n"),
288 progname
, pid_file
, strerror(errno
));
292 if (fscanf(pidf
, "%ld", &pid
) != 1)
294 /* Is the file empty? */
295 if (ftell(pidf
) == 0 && feof(pidf
))
296 write_stderr(_("%s: the PID file \"%s\" is empty\n"),
299 write_stderr(_("%s: invalid data in PID file \"%s\"\n"),
304 return (pgpid_t
) pid
;
309 * get the lines from a text file - return NULL if file can't be opened
311 * Trailing newlines are deleted from the lines (this is a change from pre-v10)
313 * *numlines is set to the number of line pointers returned; there is
314 * also an additional NULL pointer after the last real line.
317 readfile(const char *path
, int *numlines
)
329 *numlines
= 0; /* in case of failure or empty file */
332 * Slurp the file into memory.
334 * The file can change concurrently, so we read the whole file into memory
335 * with a single read() call. That's not guaranteed to get an atomic
336 * snapshot, but in practice, for a small file, it's close enough for the
339 fd
= open(path
, O_RDONLY
| PG_BINARY
, 0);
342 if (fstat(fd
, &statbuf
) < 0)
347 if (statbuf
.st_size
== 0)
351 result
= (char **) pg_malloc(sizeof(char *));
355 buffer
= pg_malloc(statbuf
.st_size
+ 1);
357 len
= read(fd
, buffer
, statbuf
.st_size
+ 1);
359 if (len
!= statbuf
.st_size
)
361 /* oops, the file size changed between fstat and read */
367 * Count newlines. We expect there to be a newline after each full line,
368 * including one at the end of file. If there isn't a newline at the end,
369 * any characters after the last newline will be ignored.
372 for (i
= 0; i
< len
; i
++)
374 if (buffer
[i
] == '\n')
378 /* set up the result buffer */
379 result
= (char **) pg_malloc((nlines
+ 1) * sizeof(char *));
382 /* now split the buffer into lines */
385 for (i
= 0; i
< len
; i
++)
387 if (buffer
[i
] == '\n')
389 int slen
= &buffer
[i
] - linebegin
;
390 char *linebuf
= pg_malloc(slen
+ 1);
392 memcpy(linebuf
, linebegin
, slen
);
393 /* we already dropped the \n, but get rid of any \r too */
394 if (slen
> 0 && linebuf
[slen
- 1] == '\r')
396 linebuf
[slen
] = '\0';
397 result
[n
++] = linebuf
;
398 linebegin
= &buffer
[i
+ 1];
410 * Free memory allocated for optlines through readfile()
413 free_readfile(char **optlines
)
415 char *curr_line
= NULL
;
421 while ((curr_line
= optlines
[i
++]))
428 * start/test/stop routines
432 * Start the postmaster and return its PID.
434 * Currently, on Windows what we return is the PID of the shell process
435 * that launched the postmaster (and, we trust, is waiting for it to exit).
436 * So the PID is usable for "is the postmaster still running" checks,
437 * but cannot be compared directly to postmaster.pid.
439 * On Windows, we also save aside a handle to the shell process in
440 * "postmasterProcess", which the caller should close when done with it.
443 start_postmaster(void)
450 /* Flush stdio channels just before fork, to avoid double-output problems */
461 write_stderr(_("%s: could not start server: %s\n"),
462 progname
, strerror(errno
));
467 /* fork succeeded, in parent */
471 /* fork succeeded, in child */
474 * If possible, detach the postmaster process from the launching process
475 * group and make it a group leader, so that it doesn't get signaled along
476 * with the current group that launched it.
481 write_stderr(_("%s: could not start server due to setsid() failure: %s\n"),
482 progname
, strerror(errno
));
488 * Since there might be quotes to handle here, it is easier simply to pass
489 * everything to a shell to process them. Use exec so that the postmaster
490 * has the same PID as the current child process.
492 if (log_file
!= NULL
)
493 cmd
= psprintf("exec \"%s\" %s%s < \"%s\" >> \"%s\" 2>&1",
494 exec_path
, pgdata_opt
, post_opts
,
497 cmd
= psprintf("exec \"%s\" %s%s < \"%s\" 2>&1",
498 exec_path
, pgdata_opt
, post_opts
, DEVNULL
);
500 (void) execl("/bin/sh", "/bin/sh", "-c", cmd
, (char *) NULL
);
503 write_stderr(_("%s: could not start server: %s\n"),
504 progname
, strerror(errno
));
507 return 0; /* keep dumb compilers quiet */
512 * As with the Unix case, it's easiest to use the shell (CMD.EXE) to
513 * handle redirection etc. Unfortunately CMD.EXE lacks any equivalent of
514 * "exec", so we don't get to find out the postmaster's PID immediately.
516 PROCESS_INFORMATION pi
;
519 /* Find CMD.EXE location using COMSPEC, if it's set */
520 comspec
= getenv("COMSPEC");
524 if (log_file
!= NULL
)
527 * First, open the log file if it exists. The idea is that if the
528 * file is still locked by a previous postmaster run, we'll wait until
529 * it comes free, instead of failing with ERROR_SHARING_VIOLATION.
530 * (It'd be better to open the file in a sharing-friendly mode, but we
531 * can't use CMD.EXE to do that, so work around it. Note that the
532 * previous postmaster will still have the file open for a short time
533 * after removing postmaster.pid.)
535 * If the log file doesn't exist, we *must not* create it here. If we
536 * were launched with higher privileges than the restricted process
537 * will have, the log file might end up with permissions settings that
538 * prevent the postmaster from writing on it.
540 int fd
= open(log_file
, O_RDWR
, 0);
545 * ENOENT is expectable since we didn't use O_CREAT. Otherwise
546 * complain. We could just fall through and let CMD.EXE report
547 * the problem, but its error reporting is pretty miserable.
551 write_stderr(_("%s: could not open log file \"%s\": %s\n"),
552 progname
, log_file
, strerror(errno
));
559 cmd
= psprintf("\"%s\" /C \"\"%s\" %s%s < \"%s\" >> \"%s\" 2>&1\"",
560 comspec
, exec_path
, pgdata_opt
, post_opts
, DEVNULL
, log_file
);
563 cmd
= psprintf("\"%s\" /C \"\"%s\" %s%s < \"%s\" 2>&1\"",
564 comspec
, exec_path
, pgdata_opt
, post_opts
, DEVNULL
);
566 if (!CreateRestrictedProcess(cmd
, &pi
, false))
568 write_stderr(_("%s: could not start server: error code %lu\n"),
569 progname
, (unsigned long) GetLastError());
572 /* Don't close command process handle here; caller must do so */
573 postmasterProcess
= pi
.hProcess
;
574 CloseHandle(pi
.hThread
);
575 return pi
.dwProcessId
; /* Shell's PID, not postmaster's! */
582 * Wait for the postmaster to become ready.
584 * On Unix, pm_pid is the PID of the just-launched postmaster. On Windows,
585 * it may be the PID of an ancestor shell process, so we can't check the
586 * contents of postmaster.pid quite as carefully.
588 * On Windows, the static variable postmasterProcess is an implicit argument
589 * to this routine; it contains a handle to the postmaster process or an
590 * ancestor shell process thereof.
592 * Note that the checkpoint parameter enables a Windows service control
593 * manager checkpoint, it's got nothing to do with database checkpoints!!
596 wait_for_postmaster_start(pgpid_t pm_pid
, bool do_checkpoint
)
600 for (i
= 0; i
< wait_seconds
* WAITS_PER_SEC
; i
++)
606 * Try to read the postmaster.pid file. If it's not valid, or if the
607 * status line isn't there yet, just keep waiting.
609 if ((optlines
= readfile(pid_file
, &numlines
)) != NULL
&&
610 numlines
>= LOCK_FILE_LINE_PM_STATUS
)
612 /* File is complete enough for us, parse it */
617 * Make sanity checks. If it's for the wrong PID, or the recorded
618 * start time is before pg_ctl started, then either we are looking
619 * at the wrong data directory, or this is a pre-existing pidfile
620 * that hasn't (yet?) been overwritten by our child postmaster.
621 * Allow 2 seconds slop for possible cross-process clock skew.
623 pmpid
= atol(optlines
[LOCK_FILE_LINE_PID
- 1]);
624 pmstart
= atol(optlines
[LOCK_FILE_LINE_START_TIME
- 1]);
625 if (pmstart
>= start_time
- 2 &&
629 /* Windows can only reject standalone-backend PIDs */
635 * OK, seems to be a valid pidfile from our child. Check the
636 * status line (this assumes a v10 or later server).
638 char *pmstatus
= optlines
[LOCK_FILE_LINE_PM_STATUS
- 1];
640 if (strcmp(pmstatus
, PM_STATUS_READY
) == 0 ||
641 strcmp(pmstatus
, PM_STATUS_STANDBY
) == 0)
643 /* postmaster is done starting up */
644 free_readfile(optlines
);
645 return POSTMASTER_READY
;
651 * Free the results of readfile.
653 * This is safe to call even if optlines is NULL.
655 free_readfile(optlines
);
658 * Check whether the child postmaster process is still alive. This
659 * lets us exit early if the postmaster fails during startup.
661 * On Windows, we may be checking the postmaster's parent shell, but
662 * that's fine for this purpose.
668 if (waitpid((pid_t
) pm_pid
, &exitstatus
, WNOHANG
) == (pid_t
) pm_pid
)
669 return POSTMASTER_FAILED
;
672 if (WaitForSingleObject(postmasterProcess
, 0) == WAIT_OBJECT_0
)
673 return POSTMASTER_FAILED
;
676 /* Startup still in process; wait, printing a dot once per second */
677 if (i
% WAITS_PER_SEC
== 0)
683 * Increment the wait hint by 6 secs (connection timeout +
684 * sleep). We must do this to indicate to the SCM that our
685 * startup time is changing, otherwise it'll usually send a
686 * stop signal after 20 seconds, despite incrementing the
687 * checkpoint counter.
689 status
.dwWaitHint
+= 6000;
690 status
.dwCheckPoint
++;
691 SetServiceStatus(hStatus
, (LPSERVICE_STATUS
) &status
);
698 pg_usleep(USEC_PER_SEC
/ WAITS_PER_SEC
);
701 /* out of patience; report that postmaster is still starting up */
702 return POSTMASTER_STILL_STARTING
;
707 * Wait for the postmaster to stop.
709 * Returns true if the postmaster stopped cleanly (i.e., removed its pidfile).
710 * Returns false if the postmaster dies uncleanly, or if we time out.
713 wait_for_postmaster_stop(void)
717 for (cnt
= 0; cnt
< wait_seconds
* WAITS_PER_SEC
; cnt
++)
721 if ((pid
= get_pgpid(false)) == 0)
722 return true; /* pid file is gone */
724 if (kill((pid_t
) pid
, 0) != 0)
727 * Postmaster seems to have died. Check the pid file once more to
728 * avoid a race condition, but give up waiting.
730 if (get_pgpid(false) == 0)
731 return true; /* pid file is gone */
732 return false; /* postmaster died untimely */
735 if (cnt
% WAITS_PER_SEC
== 0)
737 pg_usleep(USEC_PER_SEC
/ WAITS_PER_SEC
);
739 return false; /* timeout reached */
744 * Wait for the postmaster to promote.
746 * Returns true on success, else false.
747 * To avoid waiting uselessly, we check for postmaster death here too.
750 wait_for_postmaster_promote(void)
754 for (cnt
= 0; cnt
< wait_seconds
* WAITS_PER_SEC
; cnt
++)
759 if ((pid
= get_pgpid(false)) == 0)
760 return false; /* pid file is gone */
761 if (kill((pid_t
) pid
, 0) != 0)
762 return false; /* postmaster died */
764 state
= get_control_dbstate();
765 if (state
== DB_IN_PRODUCTION
)
766 return true; /* successful promotion */
768 if (cnt
% WAITS_PER_SEC
== 0)
770 pg_usleep(USEC_PER_SEC
/ WAITS_PER_SEC
);
772 return false; /* timeout reached */
776 #if defined(HAVE_GETRLIMIT)
778 unlimit_core_size(void)
782 getrlimit(RLIMIT_CORE
, &lim
);
783 if (lim
.rlim_max
== 0)
785 write_stderr(_("%s: cannot set core file size limit; disallowed by hard limit\n"),
789 else if (lim
.rlim_max
== RLIM_INFINITY
|| lim
.rlim_cur
< lim
.rlim_max
)
791 lim
.rlim_cur
= lim
.rlim_max
;
792 setrlimit(RLIMIT_CORE
, &lim
);
800 if (post_opts
== NULL
)
802 post_opts
= ""; /* default */
803 if (ctl_command
== RESTART_COMMAND
)
808 optlines
= readfile(postopts_file
, &numlines
);
809 if (optlines
== NULL
)
811 write_stderr(_("%s: could not read file \"%s\"\n"), progname
, postopts_file
);
814 else if (numlines
!= 1)
816 write_stderr(_("%s: option file \"%s\" must have exactly one line\n"),
817 progname
, postopts_file
);
825 optline
= optlines
[0];
828 * Are we at the first option, as defined by space and
831 if ((arg1
= strstr(optline
, " \"")) != NULL
)
833 *arg1
= '\0'; /* terminate so we get only program name */
834 post_opts
= pg_strdup(arg1
+ 1); /* point past whitespace */
836 if (exec_path
== NULL
)
837 exec_path
= pg_strdup(optline
);
840 /* Free the results of readfile. */
841 free_readfile(optlines
);
847 * SIGINT signal handler used while waiting for postmaster to start up.
848 * Forwards the SIGINT to the postmaster process, asking it to shut down,
849 * before terminating pg_ctl itself. This way, if the user hits CTRL-C while
850 * waiting for the server to start up, the server launch is aborted.
853 trap_sigint_during_startup(SIGNAL_ARGS
)
855 if (postmasterPID
!= -1)
857 if (kill(postmasterPID
, SIGINT
) != 0)
858 write_stderr(_("%s: could not send stop signal (PID: %ld): %s\n"),
859 progname
, (pgpid_t
) postmasterPID
, strerror(errno
));
863 * Clear the signal handler, and send the signal again, to terminate the
866 pqsignal(postgres_signal_arg
, SIG_DFL
);
867 raise(postgres_signal_arg
);
871 find_other_exec_or_die(const char *argv0
, const char *target
, const char *versionstr
)
876 found_path
= pg_malloc(MAXPGPATH
);
878 if ((ret
= find_other_exec(argv0
, target
, versionstr
, found_path
)) < 0)
880 char full_path
[MAXPGPATH
];
882 if (find_my_exec(argv0
, full_path
) < 0)
883 strlcpy(full_path
, progname
, sizeof(full_path
));
886 write_stderr(_("program \"%s\" is needed by %s but was not found in the same directory as \"%s\"\n"),
887 target
, progname
, full_path
);
889 write_stderr(_("program \"%s\" was found by \"%s\" but was not the same version as %s\n"),
890 target
, full_path
, progname
);
902 if (exec_path
== NULL
)
903 exec_path
= find_other_exec_or_die(argv0
, "initdb", "initdb (PostgreSQL) " PG_VERSION
"\n");
905 if (pgdata_opt
== NULL
)
908 if (post_opts
== NULL
)
912 cmd
= psprintf("\"%s\" %s%s",
913 exec_path
, pgdata_opt
, post_opts
);
915 cmd
= psprintf("\"%s\" %s%s > \"%s\"",
916 exec_path
, pgdata_opt
, post_opts
, DEVNULL
);
919 if (system(cmd
) != 0)
921 write_stderr(_("%s: database system initialization failed\n"), progname
);
932 if (ctl_command
!= RESTART_COMMAND
)
934 old_pid
= get_pgpid(false);
936 write_stderr(_("%s: another server might be running; "
937 "trying to start server anyway\n"),
943 /* No -D or -D already added during server start */
944 if (ctl_command
== RESTART_COMMAND
|| pgdata_opt
== NULL
)
947 if (exec_path
== NULL
)
948 exec_path
= find_other_exec_or_die(argv0
, "postgres", PG_BACKEND_VERSIONSTR
);
950 #if defined(HAVE_GETRLIMIT)
951 if (allow_core_files
)
956 * If possible, tell the postmaster our parent shell's PID (see the
957 * comments in CreateLockFile() for motivation). Windows hasn't got
958 * getppid() unfortunately.
964 snprintf(env_var
, sizeof(env_var
), "%d", (int) getppid());
965 setenv("PG_GRANDPARENT_PID", env_var
, 1);
969 pm_pid
= start_postmaster();
974 * If the user interrupts the startup (e.g. with CTRL-C), we'd like to
975 * abort the server launch. Install a signal handler that will
976 * forward SIGINT to the postmaster process, while we wait.
978 * (We don't bother to reset the signal handler after the launch, as
979 * we're about to exit, anyway.)
981 postmasterPID
= pm_pid
;
982 pqsignal(SIGINT
, trap_sigint_during_startup
);
984 print_msg(_("waiting for server to start..."));
986 switch (wait_for_postmaster_start(pm_pid
, false))
988 case POSTMASTER_READY
:
989 print_msg(_(" done\n"));
990 print_msg(_("server started\n"));
992 case POSTMASTER_STILL_STARTING
:
993 print_msg(_(" stopped waiting\n"));
994 write_stderr(_("%s: server did not start in time\n"),
998 case POSTMASTER_FAILED
:
999 print_msg(_(" stopped waiting\n"));
1000 write_stderr(_("%s: could not start server\n"
1001 "Examine the log output.\n"),
1008 print_msg(_("server starting\n"));
1011 /* Now we don't need the handle to the shell process anymore */
1012 CloseHandle(postmasterProcess
);
1013 postmasterProcess
= INVALID_HANDLE_VALUE
;
1023 pid
= get_pgpid(false);
1025 if (pid
== 0) /* no pid file */
1027 write_stderr(_("%s: PID file \"%s\" does not exist\n"), progname
, pid_file
);
1028 write_stderr(_("Is server running?\n"));
1031 else if (pid
< 0) /* standalone backend, not postmaster */
1034 write_stderr(_("%s: cannot stop server; "
1035 "single-user server is running (PID: %ld)\n"),
1040 if (kill((pid_t
) pid
, sig
) != 0)
1042 write_stderr(_("%s: could not send stop signal (PID: %ld): %s\n"), progname
, pid
,
1049 print_msg(_("server shutting down\n"));
1054 print_msg(_("waiting for server to shut down..."));
1056 if (!wait_for_postmaster_stop())
1058 print_msg(_(" failed\n"));
1060 write_stderr(_("%s: server does not shut down\n"), progname
);
1061 if (shutdown_mode
== SMART_MODE
)
1062 write_stderr(_("HINT: The \"-m fast\" option immediately disconnects sessions rather than\n"
1063 "waiting for session-initiated disconnection.\n"));
1066 print_msg(_(" done\n"));
1068 print_msg(_("server stopped\n"));
1074 * restart/reload routines
1082 pid
= get_pgpid(false);
1084 if (pid
== 0) /* no pid file */
1086 write_stderr(_("%s: PID file \"%s\" does not exist\n"),
1087 progname
, pid_file
);
1088 write_stderr(_("Is server running?\n"));
1089 write_stderr(_("trying to start server anyway\n"));
1093 else if (pid
< 0) /* standalone backend, not postmaster */
1096 if (postmaster_is_alive((pid_t
) pid
))
1098 write_stderr(_("%s: cannot restart server; "
1099 "single-user server is running (PID: %ld)\n"),
1101 write_stderr(_("Please terminate the single-user server and try again.\n"));
1106 if (postmaster_is_alive((pid_t
) pid
))
1108 if (kill((pid_t
) pid
, sig
) != 0)
1110 write_stderr(_("%s: could not send stop signal (PID: %ld): %s\n"), progname
, pid
,
1115 print_msg(_("waiting for server to shut down..."));
1117 /* always wait for restart */
1118 if (!wait_for_postmaster_stop())
1120 print_msg(_(" failed\n"));
1122 write_stderr(_("%s: server does not shut down\n"), progname
);
1123 if (shutdown_mode
== SMART_MODE
)
1124 write_stderr(_("HINT: The \"-m fast\" option immediately disconnects sessions rather than\n"
1125 "waiting for session-initiated disconnection.\n"));
1129 print_msg(_(" done\n"));
1130 print_msg(_("server stopped\n"));
1134 write_stderr(_("%s: old server process (PID: %ld) seems to be gone\n"),
1136 write_stderr(_("starting server anyway\n"));
1147 pid
= get_pgpid(false);
1148 if (pid
== 0) /* no pid file */
1150 write_stderr(_("%s: PID file \"%s\" does not exist\n"), progname
, pid_file
);
1151 write_stderr(_("Is server running?\n"));
1154 else if (pid
< 0) /* standalone backend, not postmaster */
1157 write_stderr(_("%s: cannot reload server; "
1158 "single-user server is running (PID: %ld)\n"),
1160 write_stderr(_("Please terminate the single-user server and try again.\n"));
1164 if (kill((pid_t
) pid
, sig
) != 0)
1166 write_stderr(_("%s: could not send reload signal (PID: %ld): %s\n"),
1167 progname
, pid
, strerror(errno
));
1171 print_msg(_("server signaled\n"));
1185 pid
= get_pgpid(false);
1187 if (pid
== 0) /* no pid file */
1189 write_stderr(_("%s: PID file \"%s\" does not exist\n"), progname
, pid_file
);
1190 write_stderr(_("Is server running?\n"));
1193 else if (pid
< 0) /* standalone backend, not postmaster */
1196 write_stderr(_("%s: cannot promote server; "
1197 "single-user server is running (PID: %ld)\n"),
1202 if (get_control_dbstate() != DB_IN_ARCHIVE_RECOVERY
)
1204 write_stderr(_("%s: cannot promote server; "
1205 "server is not in standby mode\n"),
1210 snprintf(promote_file
, MAXPGPATH
, "%s/promote", pg_data
);
1212 if ((prmfile
= fopen(promote_file
, "w")) == NULL
)
1214 write_stderr(_("%s: could not create promote signal file \"%s\": %s\n"),
1215 progname
, promote_file
, strerror(errno
));
1218 if (fclose(prmfile
))
1220 write_stderr(_("%s: could not write promote signal file \"%s\": %s\n"),
1221 progname
, promote_file
, strerror(errno
));
1226 if (kill((pid_t
) pid
, sig
) != 0)
1228 write_stderr(_("%s: could not send promote signal (PID: %ld): %s\n"),
1229 progname
, pid
, strerror(errno
));
1230 if (unlink(promote_file
) != 0)
1231 write_stderr(_("%s: could not remove promote signal file \"%s\": %s\n"),
1232 progname
, promote_file
, strerror(errno
));
1238 print_msg(_("waiting for server to promote..."));
1239 if (wait_for_postmaster_promote())
1241 print_msg(_(" done\n"));
1242 print_msg(_("server promoted\n"));
1246 print_msg(_(" stopped waiting\n"));
1247 write_stderr(_("%s: server did not promote in time\n"),
1253 print_msg(_("server promoting\n"));
1263 FILE *logrotatefile
;
1266 pid
= get_pgpid(false);
1268 if (pid
== 0) /* no pid file */
1270 write_stderr(_("%s: PID file \"%s\" does not exist\n"), progname
, pid_file
);
1271 write_stderr(_("Is server running?\n"));
1274 else if (pid
< 0) /* standalone backend, not postmaster */
1277 write_stderr(_("%s: cannot rotate log file; "
1278 "single-user server is running (PID: %ld)\n"),
1283 snprintf(logrotate_file
, MAXPGPATH
, "%s/logrotate", pg_data
);
1285 if ((logrotatefile
= fopen(logrotate_file
, "w")) == NULL
)
1287 write_stderr(_("%s: could not create log rotation signal file \"%s\": %s\n"),
1288 progname
, logrotate_file
, strerror(errno
));
1291 if (fclose(logrotatefile
))
1293 write_stderr(_("%s: could not write log rotation signal file \"%s\": %s\n"),
1294 progname
, logrotate_file
, strerror(errno
));
1299 if (kill((pid_t
) pid
, sig
) != 0)
1301 write_stderr(_("%s: could not send log rotation signal (PID: %ld): %s\n"),
1302 progname
, pid
, strerror(errno
));
1303 if (unlink(logrotate_file
) != 0)
1304 write_stderr(_("%s: could not remove log rotation signal file \"%s\": %s\n"),
1305 progname
, logrotate_file
, strerror(errno
));
1309 print_msg(_("server signaled to rotate log file\n"));
1318 postmaster_is_alive(pid_t pid
)
1321 * Test to see if the process is still there. Note that we do not
1322 * consider an EPERM failure to mean that the process is still there;
1323 * EPERM must mean that the given PID belongs to some other userid, and
1324 * considering the permissions on $PGDATA, that means it's not the
1325 * postmaster we are after.
1327 * Don't believe that our own PID or parent shell's PID is the postmaster,
1328 * either. (Windows hasn't got getppid(), though.)
1330 if (pid
== getpid())
1333 if (pid
== getppid())
1336 if (kill(pid
, 0) == 0)
1346 pid
= get_pgpid(true);
1347 /* Is there a pid file? */
1350 /* standalone backend? */
1354 if (postmaster_is_alive((pid_t
) pid
))
1356 printf(_("%s: single-user server is running (PID: %ld)\n"),
1362 /* must be a postmaster */
1364 if (postmaster_is_alive((pid_t
) pid
))
1370 printf(_("%s: server is running (PID: %ld)\n"),
1373 optlines
= readfile(postopts_file
, &numlines
);
1374 if (optlines
!= NULL
)
1376 for (curr_line
= optlines
; *curr_line
!= NULL
; curr_line
++)
1379 /* Free the results of readfile */
1380 free_readfile(optlines
);
1386 printf(_("%s: no server running\n"), progname
);
1389 * The Linux Standard Base Core Specification 3.1 says this should return
1390 * '3, program is not running'
1391 * https://refspecs.linuxbase.org/LSB_3.1.0/LSB-Core-generic/LSB-Core-generic/iniscrptact.html
1399 do_kill(pgpid_t pid
)
1401 if (kill((pid_t
) pid
, sig
) != 0)
1403 write_stderr(_("%s: could not send signal %d (PID: %ld): %s\n"),
1404 progname
, sig
, pid
, strerror(errno
));
1412 pgwin32_IsInstalled(SC_HANDLE hSCM
)
1414 SC_HANDLE hService
= OpenService(hSCM
, register_servicename
, SERVICE_QUERY_CONFIG
);
1415 bool bResult
= (hService
!= NULL
);
1418 CloseServiceHandle(hService
);
1423 pgwin32_CommandLine(bool registration
)
1425 PQExpBuffer cmdLine
= createPQExpBuffer();
1426 char cmdPath
[MAXPGPATH
];
1431 ret
= find_my_exec(argv0
, cmdPath
);
1434 write_stderr(_("%s: could not find own program executable\n"), progname
);
1440 ret
= find_other_exec(argv0
, "postgres", PG_BACKEND_VERSIONSTR
,
1444 write_stderr(_("%s: could not find postgres program executable\n"), progname
);
1449 /* if path does not end in .exe, append it */
1450 if (strlen(cmdPath
) < 4 ||
1451 pg_strcasecmp(cmdPath
+ strlen(cmdPath
) - 4, ".exe") != 0)
1452 snprintf(cmdPath
+ strlen(cmdPath
), sizeof(cmdPath
) - strlen(cmdPath
),
1455 /* use backslashes in path to avoid problems with some third-party tools */
1456 make_native_path(cmdPath
);
1458 /* be sure to double-quote the executable's name in the command */
1459 appendPQExpBuffer(cmdLine
, "\"%s\"", cmdPath
);
1461 /* append assorted switches to the command line, as needed */
1464 appendPQExpBuffer(cmdLine
, " runservice -N \"%s\"",
1465 register_servicename
);
1469 /* We need the -D path to be absolute */
1472 if ((dataDir
= make_absolute_path(pg_config
)) == NULL
)
1474 /* make_absolute_path already reported the error */
1477 make_native_path(dataDir
);
1478 appendPQExpBuffer(cmdLine
, " -D \"%s\"", dataDir
);
1482 if (registration
&& event_source
!= NULL
)
1483 appendPQExpBuffer(cmdLine
, " -e \"%s\"", event_source
);
1485 if (registration
&& do_wait
)
1486 appendPQExpBufferStr(cmdLine
, " -w");
1488 /* Don't propagate a value from an environment variable. */
1489 if (registration
&& wait_seconds_arg
&& wait_seconds
!= DEFAULT_WAIT
)
1490 appendPQExpBuffer(cmdLine
, " -t %d", wait_seconds
);
1492 if (registration
&& silent_mode
)
1493 appendPQExpBufferStr(cmdLine
, " -s");
1498 appendPQExpBuffer(cmdLine
, " -o \"%s\"", post_opts
);
1500 appendPQExpBuffer(cmdLine
, " %s", post_opts
);
1503 return cmdLine
->data
;
1507 pgwin32_doRegister(void)
1510 SC_HANDLE hSCM
= OpenSCManager(NULL
, NULL
, SC_MANAGER_ALL_ACCESS
);
1514 write_stderr(_("%s: could not open service manager\n"), progname
);
1517 if (pgwin32_IsInstalled(hSCM
))
1519 CloseServiceHandle(hSCM
);
1520 write_stderr(_("%s: service \"%s\" already registered\n"), progname
, register_servicename
);
1524 if ((hService
= CreateService(hSCM
, register_servicename
, register_servicename
,
1525 SERVICE_ALL_ACCESS
, SERVICE_WIN32_OWN_PROCESS
,
1526 pgctl_start_type
, SERVICE_ERROR_NORMAL
,
1527 pgwin32_CommandLine(true),
1528 NULL
, NULL
, "RPCSS\0", register_username
, register_password
)) == NULL
)
1530 CloseServiceHandle(hSCM
);
1531 write_stderr(_("%s: could not register service \"%s\": error code %lu\n"),
1532 progname
, register_servicename
,
1533 (unsigned long) GetLastError());
1536 CloseServiceHandle(hService
);
1537 CloseServiceHandle(hSCM
);
1541 pgwin32_doUnregister(void)
1544 SC_HANDLE hSCM
= OpenSCManager(NULL
, NULL
, SC_MANAGER_ALL_ACCESS
);
1548 write_stderr(_("%s: could not open service manager\n"), progname
);
1551 if (!pgwin32_IsInstalled(hSCM
))
1553 CloseServiceHandle(hSCM
);
1554 write_stderr(_("%s: service \"%s\" not registered\n"), progname
, register_servicename
);
1558 if ((hService
= OpenService(hSCM
, register_servicename
, DELETE
)) == NULL
)
1560 CloseServiceHandle(hSCM
);
1561 write_stderr(_("%s: could not open service \"%s\": error code %lu\n"),
1562 progname
, register_servicename
,
1563 (unsigned long) GetLastError());
1566 if (!DeleteService(hService
))
1568 CloseServiceHandle(hService
);
1569 CloseServiceHandle(hSCM
);
1570 write_stderr(_("%s: could not unregister service \"%s\": error code %lu\n"),
1571 progname
, register_servicename
,
1572 (unsigned long) GetLastError());
1575 CloseServiceHandle(hService
);
1576 CloseServiceHandle(hSCM
);
1580 pgwin32_SetServiceStatus(DWORD currentState
)
1582 status
.dwCurrentState
= currentState
;
1583 SetServiceStatus(hStatus
, (LPSERVICE_STATUS
) &status
);
1587 pgwin32_ServiceHandler(DWORD request
)
1591 case SERVICE_CONTROL_STOP
:
1592 case SERVICE_CONTROL_SHUTDOWN
:
1595 * We only need a short wait hint here as it just needs to wait
1596 * for the next checkpoint. They occur every 5 seconds during
1599 status
.dwWaitHint
= 10000;
1600 pgwin32_SetServiceStatus(SERVICE_STOP_PENDING
);
1601 SetEvent(shutdownEvent
);
1604 case SERVICE_CONTROL_PAUSE
:
1605 /* Win32 config reloading */
1606 status
.dwWaitHint
= 5000;
1607 kill(postmasterPID
, SIGHUP
);
1610 /* FIXME: These could be used to replace other signals etc */
1611 case SERVICE_CONTROL_CONTINUE
:
1612 case SERVICE_CONTROL_INTERROGATE
:
1619 pgwin32_ServiceMain(DWORD argc
, LPTSTR
*argv
)
1621 PROCESS_INFORMATION pi
;
1624 /* Initialize variables */
1625 status
.dwWin32ExitCode
= S_OK
;
1626 status
.dwCheckPoint
= 0;
1627 status
.dwWaitHint
= 60000;
1628 status
.dwServiceType
= SERVICE_WIN32_OWN_PROCESS
;
1629 status
.dwControlsAccepted
= SERVICE_ACCEPT_STOP
| SERVICE_ACCEPT_SHUTDOWN
| SERVICE_ACCEPT_PAUSE_CONTINUE
;
1630 status
.dwServiceSpecificExitCode
= 0;
1631 status
.dwCurrentState
= SERVICE_START_PENDING
;
1633 memset(&pi
, 0, sizeof(pi
));
1637 /* Register the control request handler */
1638 if ((hStatus
= RegisterServiceCtrlHandler(register_servicename
, pgwin32_ServiceHandler
)) == (SERVICE_STATUS_HANDLE
) 0)
1641 if ((shutdownEvent
= CreateEvent(NULL
, true, false, NULL
)) == NULL
)
1644 /* Start the postmaster */
1645 pgwin32_SetServiceStatus(SERVICE_START_PENDING
);
1646 if (!CreateRestrictedProcess(pgwin32_CommandLine(false), &pi
, true))
1648 pgwin32_SetServiceStatus(SERVICE_STOPPED
);
1651 postmasterPID
= pi
.dwProcessId
;
1652 postmasterProcess
= pi
.hProcess
;
1653 CloseHandle(pi
.hThread
);
1657 write_eventlog(EVENTLOG_INFORMATION_TYPE
, _("Waiting for server startup...\n"));
1658 if (wait_for_postmaster_start(postmasterPID
, true) != POSTMASTER_READY
)
1660 write_eventlog(EVENTLOG_ERROR_TYPE
, _("Timed out waiting for server startup\n"));
1661 pgwin32_SetServiceStatus(SERVICE_STOPPED
);
1664 write_eventlog(EVENTLOG_INFORMATION_TYPE
, _("Server started and accepting connections\n"));
1667 pgwin32_SetServiceStatus(SERVICE_RUNNING
);
1669 /* Wait for quit... */
1670 ret
= WaitForMultipleObjects(2, shutdownHandles
, FALSE
, INFINITE
);
1672 pgwin32_SetServiceStatus(SERVICE_STOP_PENDING
);
1675 case WAIT_OBJECT_0
: /* shutdown event */
1678 * status.dwCheckPoint can be incremented by
1679 * wait_for_postmaster_start(), so it might not start from 0.
1681 int maxShutdownCheckPoint
= status
.dwCheckPoint
+ 12;
1683 kill(postmasterPID
, SIGINT
);
1686 * Increment the checkpoint and try again. Abort after 12
1687 * checkpoints as the postmaster has probably hung.
1689 while (WaitForSingleObject(postmasterProcess
, 5000) == WAIT_TIMEOUT
&& status
.dwCheckPoint
< maxShutdownCheckPoint
)
1691 status
.dwCheckPoint
++;
1692 SetServiceStatus(hStatus
, (LPSERVICE_STATUS
) &status
);
1697 case (WAIT_OBJECT_0
+ 1): /* postmaster went down */
1701 /* shouldn't get here? */
1705 CloseHandle(shutdownEvent
);
1706 CloseHandle(postmasterProcess
);
1708 pgwin32_SetServiceStatus(SERVICE_STOPPED
);
1712 pgwin32_doRunAsService(void)
1714 SERVICE_TABLE_ENTRY st
[] = {{register_servicename
, pgwin32_ServiceMain
},
1717 if (StartServiceCtrlDispatcher(st
) == 0)
1719 write_stderr(_("%s: could not start service \"%s\": error code %lu\n"),
1720 progname
, register_servicename
,
1721 (unsigned long) GetLastError());
1728 * Set up STARTUPINFO for the new process to inherit this process' handles.
1730 * Process started as services appear to have "empty" handles (GetStdHandle()
1731 * returns NULL) rather than invalid ones. But passing down NULL ourselves
1732 * doesn't work, it's interpreted as STARTUPINFO->hStd* not being set. But we
1733 * can pass down INVALID_HANDLE_VALUE - which makes GetStdHandle() in the new
1734 * process (and its child processes!) return INVALID_HANDLE_VALUE. Which
1735 * achieves the goal of postmaster running in a similar environment as pg_ctl.
1738 InheritStdHandles(STARTUPINFO
*si
)
1740 si
->dwFlags
|= STARTF_USESTDHANDLES
;
1741 si
->hStdInput
= GetStdHandle(STD_INPUT_HANDLE
);
1742 if (si
->hStdInput
== NULL
)
1743 si
->hStdInput
= INVALID_HANDLE_VALUE
;
1744 si
->hStdOutput
= GetStdHandle(STD_OUTPUT_HANDLE
);
1745 if (si
->hStdOutput
== NULL
)
1746 si
->hStdOutput
= INVALID_HANDLE_VALUE
;
1747 si
->hStdError
= GetStdHandle(STD_ERROR_HANDLE
);
1748 if (si
->hStdError
== NULL
)
1749 si
->hStdError
= INVALID_HANDLE_VALUE
;
1753 * Create a restricted token, a job object sandbox, and execute the specified
1756 * Returns 0 on success, non-zero on failure, same as CreateProcess().
1758 * NOTE! Job object will only work when running as a service, because it's
1759 * automatically destroyed when pg_ctl exits.
1762 CreateRestrictedProcess(char *cmd
, PROCESS_INFORMATION
*processInfo
, bool as_service
)
1768 HANDLE restrictedToken
;
1770 SID_IDENTIFIER_AUTHORITY NtAuthority
= {SECURITY_NT_AUTHORITY
};
1771 SID_AND_ATTRIBUTES dropSids
[2];
1772 PTOKEN_PRIVILEGES delPrivs
;
1774 ZeroMemory(&si
, sizeof(si
));
1778 * Set stdin/stdout/stderr handles to be inherited in the child process.
1779 * That allows postmaster and the processes it starts to perform
1780 * additional checks to see if running in a service (otherwise they get
1781 * the default console handles - which point to "somewhere").
1783 InheritStdHandles(&si
);
1785 /* Open the current token to use as a base for the restricted one */
1786 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS
, &origToken
))
1789 * Most Windows targets make DWORD a 32-bit unsigned long, but in case
1790 * it doesn't cast DWORD before printing.
1792 write_stderr(_("%s: could not open process token: error code %lu\n"),
1793 progname
, (unsigned long) GetLastError());
1797 /* Allocate list of SIDs to remove */
1798 ZeroMemory(&dropSids
, sizeof(dropSids
));
1799 if (!AllocateAndInitializeSid(&NtAuthority
, 2,
1800 SECURITY_BUILTIN_DOMAIN_RID
, DOMAIN_ALIAS_RID_ADMINS
, 0, 0, 0, 0, 0,
1801 0, &dropSids
[0].Sid
) ||
1802 !AllocateAndInitializeSid(&NtAuthority
, 2,
1803 SECURITY_BUILTIN_DOMAIN_RID
, DOMAIN_ALIAS_RID_POWER_USERS
, 0, 0, 0, 0, 0,
1804 0, &dropSids
[1].Sid
))
1806 write_stderr(_("%s: could not allocate SIDs: error code %lu\n"),
1807 progname
, (unsigned long) GetLastError());
1811 /* Get list of privileges to remove */
1812 delPrivs
= GetPrivilegesToDelete(origToken
);
1813 if (delPrivs
== NULL
)
1814 /* Error message already printed */
1817 b
= CreateRestrictedToken(origToken
,
1819 sizeof(dropSids
) / sizeof(dropSids
[0]),
1821 delPrivs
->PrivilegeCount
, delPrivs
->Privileges
,
1826 FreeSid(dropSids
[1].Sid
);
1827 FreeSid(dropSids
[0].Sid
);
1828 CloseHandle(origToken
);
1832 write_stderr(_("%s: could not create restricted token: error code %lu\n"),
1833 progname
, (unsigned long) GetLastError());
1837 AddUserToTokenDacl(restrictedToken
);
1838 r
= CreateProcessAsUser(restrictedToken
, NULL
, cmd
, NULL
, NULL
, TRUE
, CREATE_SUSPENDED
, NULL
, NULL
, &si
, processInfo
);
1840 if (IsProcessInJob(processInfo
->hProcess
, NULL
, &inJob
))
1845 * Job objects are working, and the new process isn't in one, so
1846 * we can create one safely. If any problems show up when setting
1847 * it, we're going to ignore them.
1852 sprintf(jobname
, "PostgreSQL_%lu",
1853 (unsigned long) processInfo
->dwProcessId
);
1855 job
= CreateJobObject(NULL
, jobname
);
1858 JOBOBJECT_BASIC_LIMIT_INFORMATION basicLimit
;
1859 JOBOBJECT_BASIC_UI_RESTRICTIONS uiRestrictions
;
1860 JOBOBJECT_SECURITY_LIMIT_INFORMATION securityLimit
;
1862 ZeroMemory(&basicLimit
, sizeof(basicLimit
));
1863 ZeroMemory(&uiRestrictions
, sizeof(uiRestrictions
));
1864 ZeroMemory(&securityLimit
, sizeof(securityLimit
));
1866 basicLimit
.LimitFlags
= JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION
| JOB_OBJECT_LIMIT_PRIORITY_CLASS
;
1867 basicLimit
.PriorityClass
= NORMAL_PRIORITY_CLASS
;
1868 SetInformationJobObject(job
, JobObjectBasicLimitInformation
, &basicLimit
, sizeof(basicLimit
));
1870 uiRestrictions
.UIRestrictionsClass
= JOB_OBJECT_UILIMIT_DESKTOP
| JOB_OBJECT_UILIMIT_DISPLAYSETTINGS
|
1871 JOB_OBJECT_UILIMIT_EXITWINDOWS
| JOB_OBJECT_UILIMIT_READCLIPBOARD
|
1872 JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS
| JOB_OBJECT_UILIMIT_WRITECLIPBOARD
;
1874 SetInformationJobObject(job
, JobObjectBasicUIRestrictions
, &uiRestrictions
, sizeof(uiRestrictions
));
1876 securityLimit
.SecurityLimitFlags
= JOB_OBJECT_SECURITY_NO_ADMIN
| JOB_OBJECT_SECURITY_ONLY_TOKEN
;
1877 securityLimit
.JobToken
= restrictedToken
;
1878 SetInformationJobObject(job
, JobObjectSecurityLimitInformation
, &securityLimit
, sizeof(securityLimit
));
1880 AssignProcessToJobObject(job
, processInfo
->hProcess
);
1885 CloseHandle(restrictedToken
);
1887 ResumeThread(processInfo
->hThread
);
1890 * We intentionally don't close the job object handle, because we want the
1891 * object to live on until pg_ctl shuts down.
1897 * Get a list of privileges to delete from the access token. We delete all privileges
1898 * except SeLockMemoryPrivilege which is needed to use large pages, and
1899 * SeChangeNotifyPrivilege which is enabled by default in DISABLE_MAX_PRIVILEGE.
1901 static PTOKEN_PRIVILEGES
1902 GetPrivilegesToDelete(HANDLE hToken
)
1907 PTOKEN_PRIVILEGES tokenPrivs
;
1909 LUID luidChangeNotify
;
1911 if (!LookupPrivilegeValue(NULL
, SE_LOCK_MEMORY_NAME
, &luidLockPages
) ||
1912 !LookupPrivilegeValue(NULL
, SE_CHANGE_NOTIFY_NAME
, &luidChangeNotify
))
1914 write_stderr(_("%s: could not get LUIDs for privileges: error code %lu\n"),
1915 progname
, (unsigned long) GetLastError());
1919 if (!GetTokenInformation(hToken
, TokenPrivileges
, NULL
, 0, &length
) &&
1920 GetLastError() != ERROR_INSUFFICIENT_BUFFER
)
1922 write_stderr(_("%s: could not get token information: error code %lu\n"),
1923 progname
, (unsigned long) GetLastError());
1927 tokenPrivs
= (PTOKEN_PRIVILEGES
) pg_malloc_extended(length
,
1929 if (tokenPrivs
== NULL
)
1931 write_stderr(_("%s: out of memory\n"), progname
);
1935 if (!GetTokenInformation(hToken
, TokenPrivileges
, tokenPrivs
, length
, &length
))
1937 write_stderr(_("%s: could not get token information: error code %lu\n"),
1938 progname
, (unsigned long) GetLastError());
1943 for (i
= 0; i
< tokenPrivs
->PrivilegeCount
; i
++)
1945 if (memcmp(&tokenPrivs
->Privileges
[i
].Luid
, &luidLockPages
, sizeof(LUID
)) == 0 ||
1946 memcmp(&tokenPrivs
->Privileges
[i
].Luid
, &luidChangeNotify
, sizeof(LUID
)) == 0)
1948 for (j
= i
; j
< tokenPrivs
->PrivilegeCount
- 1; j
++)
1949 tokenPrivs
->Privileges
[j
] = tokenPrivs
->Privileges
[j
+ 1];
1950 tokenPrivs
->PrivilegeCount
--;
1961 write_stderr(_("Try \"%s --help\" for more information.\n"), progname
);
1969 printf(_("%s is a utility to initialize, start, stop, or control a PostgreSQL server.\n\n"), progname
);
1970 printf(_("Usage:\n"));
1971 printf(_(" %s init[db] [-D DATADIR] [-s] [-o OPTIONS]\n"), progname
);
1972 printf(_(" %s start [-D DATADIR] [-l FILENAME] [-W] [-t SECS] [-s]\n"
1973 " [-o OPTIONS] [-p PATH] [-c]\n"), progname
);
1974 printf(_(" %s stop [-D DATADIR] [-m SHUTDOWN-MODE] [-W] [-t SECS] [-s]\n"), progname
);
1975 printf(_(" %s restart [-D DATADIR] [-m SHUTDOWN-MODE] [-W] [-t SECS] [-s]\n"
1976 " [-o OPTIONS] [-c]\n"), progname
);
1977 printf(_(" %s reload [-D DATADIR] [-s]\n"), progname
);
1978 printf(_(" %s status [-D DATADIR]\n"), progname
);
1979 printf(_(" %s promote [-D DATADIR] [-W] [-t SECS] [-s]\n"), progname
);
1980 printf(_(" %s logrotate [-D DATADIR] [-s]\n"), progname
);
1981 printf(_(" %s kill SIGNALNAME PID\n"), progname
);
1983 printf(_(" %s register [-D DATADIR] [-N SERVICENAME] [-U USERNAME] [-P PASSWORD]\n"
1984 " [-S START-TYPE] [-e SOURCE] [-W] [-t SECS] [-s] [-o OPTIONS]\n"), progname
);
1985 printf(_(" %s unregister [-N SERVICENAME]\n"), progname
);
1988 printf(_("\nCommon options:\n"));
1989 printf(_(" -D, --pgdata=DATADIR location of the database storage area\n"));
1991 printf(_(" -e SOURCE event source for logging when running as a service\n"));
1993 printf(_(" -s, --silent only print errors, no informational messages\n"));
1994 printf(_(" -t, --timeout=SECS seconds to wait when using -w option\n"));
1995 printf(_(" -V, --version output version information, then exit\n"));
1996 printf(_(" -w, --wait wait until operation completes (default)\n"));
1997 printf(_(" -W, --no-wait do not wait until operation completes\n"));
1998 printf(_(" -?, --help show this help, then exit\n"));
1999 printf(_("If the -D option is omitted, the environment variable PGDATA is used.\n"));
2001 printf(_("\nOptions for start or restart:\n"));
2002 #if defined(HAVE_GETRLIMIT)
2003 printf(_(" -c, --core-files allow postgres to produce core files\n"));
2005 printf(_(" -c, --core-files not applicable on this platform\n"));
2007 printf(_(" -l, --log=FILENAME write (or append) server log to FILENAME\n"));
2008 printf(_(" -o, --options=OPTIONS command line options to pass to postgres\n"
2009 " (PostgreSQL server executable) or initdb\n"));
2010 printf(_(" -p PATH-TO-POSTGRES normally not necessary\n"));
2011 printf(_("\nOptions for stop or restart:\n"));
2012 printf(_(" -m, --mode=MODE MODE can be \"smart\", \"fast\", or \"immediate\"\n"));
2014 printf(_("\nShutdown modes are:\n"));
2015 printf(_(" smart quit after all clients have disconnected\n"));
2016 printf(_(" fast quit directly, with proper shutdown (default)\n"));
2017 printf(_(" immediate quit without complete shutdown; will lead to recovery on restart\n"));
2019 printf(_("\nAllowed signal names for kill:\n"));
2020 printf(" ABRT HUP INT KILL QUIT TERM USR1 USR2\n");
2023 printf(_("\nOptions for register and unregister:\n"));
2024 printf(_(" -N SERVICENAME service name with which to register PostgreSQL server\n"));
2025 printf(_(" -P PASSWORD password of account to register PostgreSQL server\n"));
2026 printf(_(" -U USERNAME user name of account to register PostgreSQL server\n"));
2027 printf(_(" -S START-TYPE service start type to register PostgreSQL server\n"));
2029 printf(_("\nStart types are:\n"));
2030 printf(_(" auto start service automatically during system startup (default)\n"));
2031 printf(_(" demand start service on demand\n"));
2034 printf(_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT
);
2035 printf(_("%s home page: <%s>\n"), PACKAGE_NAME
, PACKAGE_URL
);
2041 set_mode(char *modeopt
)
2043 if (strcmp(modeopt
, "s") == 0 || strcmp(modeopt
, "smart") == 0)
2045 shutdown_mode
= SMART_MODE
;
2048 else if (strcmp(modeopt
, "f") == 0 || strcmp(modeopt
, "fast") == 0)
2050 shutdown_mode
= FAST_MODE
;
2053 else if (strcmp(modeopt
, "i") == 0 || strcmp(modeopt
, "immediate") == 0)
2055 shutdown_mode
= IMMEDIATE_MODE
;
2060 write_stderr(_("%s: unrecognized shutdown mode \"%s\"\n"), progname
, modeopt
);
2069 set_sig(char *signame
)
2071 if (strcmp(signame
, "HUP") == 0)
2073 else if (strcmp(signame
, "INT") == 0)
2075 else if (strcmp(signame
, "QUIT") == 0)
2077 else if (strcmp(signame
, "ABRT") == 0)
2079 else if (strcmp(signame
, "KILL") == 0)
2081 else if (strcmp(signame
, "TERM") == 0)
2083 else if (strcmp(signame
, "USR1") == 0)
2085 else if (strcmp(signame
, "USR2") == 0)
2089 write_stderr(_("%s: unrecognized signal name \"%s\"\n"), progname
, signame
);
2098 set_starttype(char *starttypeopt
)
2100 if (strcmp(starttypeopt
, "a") == 0 || strcmp(starttypeopt
, "auto") == 0)
2101 pgctl_start_type
= SERVICE_AUTO_START
;
2102 else if (strcmp(starttypeopt
, "d") == 0 || strcmp(starttypeopt
, "demand") == 0)
2103 pgctl_start_type
= SERVICE_DEMAND_START
;
2106 write_stderr(_("%s: unrecognized start type \"%s\"\n"), progname
, starttypeopt
);
2116 * If a configuration-only directory was specified, find the real data dir.
2119 adjust_data_dir(void)
2121 char filename
[MAXPGPATH
];
2126 /* do nothing if we're working without knowledge of data dir */
2127 if (pg_config
== NULL
)
2130 /* If there is no postgresql.conf, it can't be a config-only dir */
2131 snprintf(filename
, sizeof(filename
), "%s/postgresql.conf", pg_config
);
2132 if ((fd
= fopen(filename
, "r")) == NULL
)
2136 /* If PG_VERSION exists, it can't be a config-only dir */
2137 snprintf(filename
, sizeof(filename
), "%s/PG_VERSION", pg_config
);
2138 if ((fd
= fopen(filename
, "r")) != NULL
)
2144 /* Must be a configuration directory, so find the data directory */
2146 /* we use a private my_exec_path to avoid interfering with later uses */
2147 if (exec_path
== NULL
)
2148 my_exec_path
= find_other_exec_or_die(argv0
, "postgres", PG_BACKEND_VERSIONSTR
);
2150 my_exec_path
= pg_strdup(exec_path
);
2152 /* it's important for -C to be the first option, see main.c */
2153 cmd
= psprintf("\"%s\" -C data_directory %s%s",
2155 pgdata_opt
? pgdata_opt
: "",
2156 post_opts
? post_opts
: "");
2159 fd
= popen(cmd
, "r");
2160 if (fd
== NULL
|| fgets(filename
, sizeof(filename
), fd
) == NULL
)
2162 write_stderr(_("%s: could not determine the data directory using command \"%s\"\n"), progname
, cmd
);
2168 /* strip trailing newline and carriage return */
2169 (void) pg_strip_crlf(filename
);
2172 pg_data
= pg_strdup(filename
);
2173 canonicalize_path(pg_data
);
2178 get_control_dbstate(void)
2182 ControlFileData
*control_file_data
= get_controlfile(pg_data
, &crc_ok
);
2186 write_stderr(_("%s: control file appears to be corrupt\n"), progname
);
2190 ret
= control_file_data
->state
;
2191 pfree(control_file_data
);
2197 main(int argc
, char **argv
)
2199 static struct option long_options
[] = {
2200 {"help", no_argument
, NULL
, '?'},
2201 {"version", no_argument
, NULL
, 'V'},
2202 {"log", required_argument
, NULL
, 'l'},
2203 {"mode", required_argument
, NULL
, 'm'},
2204 {"pgdata", required_argument
, NULL
, 'D'},
2205 {"options", required_argument
, NULL
, 'o'},
2206 {"silent", no_argument
, NULL
, 's'},
2207 {"timeout", required_argument
, NULL
, 't'},
2208 {"core-files", no_argument
, NULL
, 'c'},
2209 {"wait", no_argument
, NULL
, 'w'},
2210 {"no-wait", no_argument
, NULL
, 'W'},
2217 pgpid_t killproc
= 0;
2219 pg_logging_init(argv
[0]);
2220 progname
= get_progname(argv
[0]);
2221 set_pglocale_pgservice(argv
[0], PG_TEXTDOMAIN("pg_ctl"));
2222 start_time
= time(NULL
);
2225 * save argv[0] so do_start() can look for the postmaster if necessary. we
2226 * don't look for postmaster here because in many cases we won't need it.
2230 /* Set restrictive mode mask until PGDATA permissions are checked */
2231 umask(PG_MODE_MASK_OWNER
);
2233 /* support --help and --version even if invoked as root */
2236 if (strcmp(argv
[1], "--help") == 0 || strcmp(argv
[1], "-?") == 0)
2241 else if (strcmp(argv
[1], "--version") == 0 || strcmp(argv
[1], "-V") == 0)
2243 puts("pg_ctl (PostgreSQL) " PG_VERSION
);
2249 * Disallow running as root, to forestall any possible security holes.
2254 write_stderr(_("%s: cannot be run as root\n"
2255 "Please log in (using, e.g., \"su\") as the "
2256 "(unprivileged) user that will\n"
2257 "own the server process.\n"),
2263 env_wait
= getenv("PGCTLTIMEOUT");
2264 if (env_wait
!= NULL
)
2265 wait_seconds
= atoi(env_wait
);
2268 * 'Action' can be before or after args so loop over both. Some
2269 * getopt_long() implementations will reorder argv[] to place all flags
2270 * first (GNU?), but we don't rely on it. Our /port version doesn't do
2275 /* process command-line options */
2276 while (optind
< argc
)
2278 while ((c
= getopt_long(argc
, argv
, "cD:e:l:m:N:o:p:P:sS:t:U:wW",
2279 long_options
, &option_index
)) != -1)
2287 pgdata_D
= pg_strdup(optarg
);
2288 canonicalize_path(pgdata_D
);
2289 setenv("PGDATA", pgdata_D
, 1);
2292 * We could pass PGDATA just in an environment
2293 * variable but we do -D too for clearer postmaster
2296 pgdata_opt
= psprintf("-D \"%s\" ", pgdata_D
);
2301 event_source
= pg_strdup(optarg
);
2304 log_file
= pg_strdup(optarg
);
2310 register_servicename
= pg_strdup(optarg
);
2313 /* append option? */
2315 post_opts
= pg_strdup(optarg
);
2318 char *old_post_opts
= post_opts
;
2320 post_opts
= psprintf("%s %s", old_post_opts
, optarg
);
2321 free(old_post_opts
);
2325 exec_path
= pg_strdup(optarg
);
2328 register_password
= pg_strdup(optarg
);
2335 set_starttype(optarg
);
2337 write_stderr(_("%s: -S option not supported on this platform\n"),
2343 wait_seconds
= atoi(optarg
);
2344 wait_seconds_arg
= true;
2347 if (strchr(optarg
, '\\'))
2348 register_username
= pg_strdup(optarg
);
2350 /* Prepend .\ for local accounts */
2351 register_username
= psprintf(".\\%s", optarg
);
2360 allow_core_files
= true;
2363 /* getopt_long already issued a suitable error message */
2369 /* Process an action */
2372 if (ctl_command
!= NO_COMMAND
)
2374 write_stderr(_("%s: too many command-line arguments (first is \"%s\")\n"), progname
, argv
[optind
]);
2379 if (strcmp(argv
[optind
], "init") == 0
2380 || strcmp(argv
[optind
], "initdb") == 0)
2381 ctl_command
= INIT_COMMAND
;
2382 else if (strcmp(argv
[optind
], "start") == 0)
2383 ctl_command
= START_COMMAND
;
2384 else if (strcmp(argv
[optind
], "stop") == 0)
2385 ctl_command
= STOP_COMMAND
;
2386 else if (strcmp(argv
[optind
], "restart") == 0)
2387 ctl_command
= RESTART_COMMAND
;
2388 else if (strcmp(argv
[optind
], "reload") == 0)
2389 ctl_command
= RELOAD_COMMAND
;
2390 else if (strcmp(argv
[optind
], "status") == 0)
2391 ctl_command
= STATUS_COMMAND
;
2392 else if (strcmp(argv
[optind
], "promote") == 0)
2393 ctl_command
= PROMOTE_COMMAND
;
2394 else if (strcmp(argv
[optind
], "logrotate") == 0)
2395 ctl_command
= LOGROTATE_COMMAND
;
2396 else if (strcmp(argv
[optind
], "kill") == 0)
2398 if (argc
- optind
< 3)
2400 write_stderr(_("%s: missing arguments for kill mode\n"), progname
);
2404 ctl_command
= KILL_COMMAND
;
2405 set_sig(argv
[++optind
]);
2406 killproc
= atol(argv
[++optind
]);
2409 else if (strcmp(argv
[optind
], "register") == 0)
2410 ctl_command
= REGISTER_COMMAND
;
2411 else if (strcmp(argv
[optind
], "unregister") == 0)
2412 ctl_command
= UNREGISTER_COMMAND
;
2413 else if (strcmp(argv
[optind
], "runservice") == 0)
2414 ctl_command
= RUN_AS_SERVICE_COMMAND
;
2418 write_stderr(_("%s: unrecognized operation mode \"%s\"\n"), progname
, argv
[optind
]);
2426 if (ctl_command
== NO_COMMAND
)
2428 write_stderr(_("%s: no operation specified\n"), progname
);
2433 /* Note we put any -D switch into the env var above */
2434 pg_config
= getenv("PGDATA");
2437 pg_config
= pg_strdup(pg_config
);
2438 canonicalize_path(pg_config
);
2439 pg_data
= pg_strdup(pg_config
);
2442 /* -D might point at config-only directory; if so find the real PGDATA */
2445 /* Complain if -D needed and not provided */
2446 if (pg_config
== NULL
&&
2447 ctl_command
!= KILL_COMMAND
&& ctl_command
!= UNREGISTER_COMMAND
)
2449 write_stderr(_("%s: no database directory specified and environment variable PGDATA unset\n"),
2455 if (ctl_command
== RELOAD_COMMAND
)
2463 snprintf(postopts_file
, MAXPGPATH
, "%s/postmaster.opts", pg_data
);
2464 snprintf(version_file
, MAXPGPATH
, "%s/PG_VERSION", pg_data
);
2465 snprintf(pid_file
, MAXPGPATH
, "%s/postmaster.pid", pg_data
);
2466 snprintf(backup_file
, MAXPGPATH
, "%s/backup_label", pg_data
);
2469 * Set mask based on PGDATA permissions,
2471 * Don't error here if the data directory cannot be stat'd. This is
2472 * handled differently based on the command and we don't want to
2473 * interfere with that logic.
2475 if (GetDataDirectoryCreatePerm(pg_data
))
2476 umask(pg_mode_mask
);
2479 switch (ctl_command
)
2484 case STATUS_COMMAND
:
2493 case RESTART_COMMAND
:
2496 case RELOAD_COMMAND
:
2499 case PROMOTE_COMMAND
:
2502 case LOGROTATE_COMMAND
:
2509 case REGISTER_COMMAND
:
2510 pgwin32_doRegister();
2512 case UNREGISTER_COMMAND
:
2513 pgwin32_doUnregister();
2515 case RUN_AS_SERVICE_COMMAND
:
2516 pgwin32_doRunAsService();