1 /*-------------------------------------------------------------------------
3 * pg_ctl --- start/stops/restarts the PostgreSQL server
5 * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group
7 * src/bin/pg_ctl/pg_ctl.c
9 *-------------------------------------------------------------------------
14 * Need this to get defines for restricted tokens and jobs. And it
15 * has to be set before any header from the Win32 API is loaded.
17 #define _WIN32_WINNT 0x0501
20 #include "postgres_fe.h"
23 #include "pqexpbuffer.h"
29 #include <sys/types.h>
33 #ifdef HAVE_SYS_RESOURCE_H
35 #include <sys/resource.h>
38 #include "getopt_long.h"
39 #include "miscadmin.h"
41 #if defined(__CYGWIN__)
42 #include <sys/cygwin.h>
44 /* Cygwin defines WIN32 in windows.h, but we don't want it. */
48 /* PID can be negative for standalone backend */
73 RUN_AS_SERVICE_COMMAND
76 #define DEFAULT_WAIT 60
78 static bool do_wait = false;
79 static bool wait_set = false;
80 static int wait_seconds = DEFAULT_WAIT;
81 static bool silent_mode = false;
82 static ShutdownMode shutdown_mode = FAST_MODE;
83 static int sig = SIGINT; /* default */
84 static CtlCommand ctl_command = NO_COMMAND;
85 static char *pg_data = NULL;
86 static char *pg_config = NULL;
87 static char *pgdata_opt = NULL;
88 static char *post_opts = NULL;
89 static const char *progname;
90 static char *log_file = NULL;
91 static char *exec_path = NULL;
92 static char *event_source = NULL;
93 static char *register_servicename = "PostgreSQL"; /* FIXME: + version ID? */
94 static char *register_username = NULL;
95 static char *register_password = NULL;
96 static char *argv0 = NULL;
97 static bool allow_core_files = false;
98 static time_t start_time;
100 static char postopts_file[MAXPGPATH];
101 static char version_file[MAXPGPATH];
102 static char pid_file[MAXPGPATH];
103 static char backup_file[MAXPGPATH];
104 static char recovery_file[MAXPGPATH];
105 static char promote_file[MAXPGPATH];
107 #if defined(WIN32) || defined(__CYGWIN__)
108 static DWORD pgctl_start_type = SERVICE_AUTO_START;
109 static SERVICE_STATUS status;
110 static SERVICE_STATUS_HANDLE hStatus = (SERVICE_STATUS_HANDLE) 0;
111 static HANDLE shutdownHandles[2];
112 static pid_t postmasterPID = -1;
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_kill(pgpid_t pid);
132 static void print_msg(const char *msg);
133 static void adjust_data_dir(void);
135 #if defined(WIN32) || defined(__CYGWIN__)
136 #if (_MSC_VER >= 1800)
137 #include <versionhelpers.h>
139 static bool IsWindowsXPOrGreater(void);
140 static bool IsWindows7OrGreater(void);
142 static bool pgwin32_IsInstalled(SC_HANDLE);
143 static char *pgwin32_CommandLine(bool);
144 static void pgwin32_doRegister(void);
145 static void pgwin32_doUnregister(void);
146 static void pgwin32_SetServiceStatus(DWORD);
147 static void WINAPI pgwin32_ServiceHandler(DWORD);
148 static void WINAPI pgwin32_ServiceMain(DWORD, LPTSTR *);
149 static void pgwin32_doRunAsService(void);
150 static int CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, bool as_service);
153 static pgpid_t get_pgpid(bool is_status_request);
154 static char **readfile(const char *path);
155 static void free_readfile(char **optlines);
156 static int start_postmaster(void);
157 static void read_post_opts(void);
159 static PGPing test_postmaster_connection(bool);
160 static bool postmaster_is_alive(pid_t pid);
162 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_CORE)
163 static void unlimit_core_size(void);
167 #if defined(WIN32) || defined(__CYGWIN__)
169 write_eventlog(int level, const char *line)
171 static HANDLE evtHandle = INVALID_HANDLE_VALUE;
173 if (silent_mode && level == EVENTLOG_INFORMATION_TYPE)
176 if (evtHandle == INVALID_HANDLE_VALUE)
178 evtHandle = RegisterEventSource(NULL,
179 event_source ? event_source : DEFAULT_EVENT_SOURCE);
180 if (evtHandle == NULL)
182 evtHandle = INVALID_HANDLE_VALUE;
187 ReportEvent(evtHandle,
190 0, /* All events are Id 0 */
200 * Write errors to stderr (or by equal means when stderr is
204 write_stderr(const char *fmt,...)
209 #if !defined(WIN32) && !defined(__CYGWIN__)
210 /* On Unix, we just fprintf to stderr */
211 vfprintf(stderr, fmt, ap);
215 * On Win32, we print to stderr if running on a console, or write to
216 * eventlog if running as a service
218 if (!isatty(fileno(stderr))) /* Running as a service */
220 char errbuf[2048]; /* Arbitrary size? */
222 vsnprintf(errbuf, sizeof(errbuf), fmt, ap);
224 write_eventlog(EVENTLOG_ERROR_TYPE, errbuf);
227 /* Not running as service, write to stderr */
228 vfprintf(stderr, fmt, ap);
234 * Given an already-localized string, print it to stdout unless the
235 * user has specified that no messages should be printed.
238 print_msg(const char *msg)
248 get_pgpid(bool is_status_request)
254 if (stat(pg_data, &statbuf) != 0)
257 write_stderr(_("%s: directory \"%s\" does not exist\n"), progname,
260 write_stderr(_("%s: could not access directory \"%s\": %s\n"), progname,
261 pg_data, strerror(errno));
264 * The Linux Standard Base Core Specification 3.1 says this should
265 * return '4, program or service status is unknown'
266 * https://refspecs.linuxbase.org/LSB_3.1.0/LSB-Core-generic/LSB-Core-g
267 * eneric/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
312 readfile(const char *path)
325 * Slurp the file into memory.
327 * The file can change concurrently, so we read the whole file into memory
328 * with a single read() call. That's not guaranteed to get an atomic
329 * snapshot, but in practice, for a small file, it's close enough for the
332 fd = open(path, O_RDONLY | PG_BINARY, 0);
335 if (fstat(fd, &statbuf) < 0)
340 if (statbuf.st_size == 0)
344 result = (char **) pg_malloc(sizeof(char *));
348 buffer = pg_malloc(statbuf.st_size + 1);
350 len = read(fd, buffer, statbuf.st_size + 1);
352 if (len != statbuf.st_size)
354 /* oops, the file size changed between fstat and read */
360 * Count newlines. We expect there to be a newline after each full line,
361 * including one at the end of file. If there isn't a newline at the end,
362 * any characters after the last newline will be ignored.
365 for (i = 0; i < len; i++)
367 if (buffer[i] == '\n')
371 /* set up the result buffer */
372 result = (char **) pg_malloc((nlines + 1) * sizeof(char *));
374 /* now split the buffer into lines */
377 for (i = 0; i < len; i++)
379 if (buffer[i] == '\n')
381 int slen = &buffer[i] - linebegin + 1;
382 char *linebuf = pg_malloc(slen + 1);
384 memcpy(linebuf, linebegin, slen);
385 linebuf[slen] = '\0';
386 result[n++] = linebuf;
387 linebegin = &buffer[i + 1];
399 * Free memory allocated for optlines through readfile()
402 free_readfile(char **optlines)
404 char *curr_line = NULL;
410 while ((curr_line = optlines[i++]))
419 * start/test/stop routines
423 start_postmaster(void)
430 * Since there might be quotes to handle here, it is easier simply to pass
431 * everything to a shell to process them.
433 * XXX it would be better to fork and exec so that we would know the child
434 * postmaster's PID directly; then test_postmaster_connection could use
435 * the PID without having to rely on reading it back from the pidfile.
437 if (log_file != NULL)
438 snprintf(cmd, MAXPGPATH, "\"%s\" %s%s < \"%s\" >> \"%s\" 2>&1 &",
439 exec_path, pgdata_opt, post_opts,
442 snprintf(cmd, MAXPGPATH, "\"%s\" %s%s < \"%s\" 2>&1 &",
443 exec_path, pgdata_opt, post_opts, DEVNULL);
449 * On win32 we don't use system(). So we don't need to use & (which would
450 * be START /B on win32). However, we still call the shell (CMD.EXE) with
451 * it to handle redirection etc.
453 PROCESS_INFORMATION pi;
455 if (log_file != NULL)
456 snprintf(cmd, MAXPGPATH, "CMD /C \"\"%s\" %s%s < \"%s\" >> \"%s\" 2>&1\"",
457 exec_path, pgdata_opt, post_opts, DEVNULL, log_file);
459 snprintf(cmd, MAXPGPATH, "CMD /C \"\"%s\" %s%s < \"%s\" 2>&1\"",
460 exec_path, pgdata_opt, post_opts, DEVNULL);
462 if (!CreateRestrictedProcess(cmd, &pi, false))
463 return GetLastError();
464 CloseHandle(pi.hProcess);
465 CloseHandle(pi.hThread);
473 * Find the pgport and try a connection
475 * Note that the checkpoint parameter enables a Windows service control
476 * manager checkpoint, it's got nothing to do with database checkpoints!!
479 test_postmaster_connection(bool do_checkpoint)
481 PGPing ret = PQPING_NO_RESPONSE;
482 bool found_stale_pidfile = false;
484 char connstr[MAXPGPATH * 2 + 256];
487 /* if requested wait time is zero, return "still starting up" code */
488 if (wait_seconds <= 0)
489 return PQPING_REJECT;
493 for (i = 0; i < wait_seconds; i++)
495 /* Do we need a connection string? */
496 if (connstr[0] == '\0')
499 * The number of lines in postmaster.pid tells us several things:
502 * 0 lock file created but status not written
503 * 2 pre-9.1 server, shared memory not created
504 * 3 pre-9.1 server, shared memory created
505 * 5 9.1+ server, ports not opened
506 * 6 9.1+ server, shared memory not created
507 * 7 9.1+ server, shared memory created
509 * This code does not support pre-9.1 servers. On Unix machines
510 * we could consider extracting the port number from the shmem
511 * key, but that (a) is not robust, and (b) doesn't help with
512 * finding out the socket directory. And it wouldn't work anyway
515 * If we see less than 6 lines in postmaster.pid, just keep
521 /* Try to read the postmaster.pid file */
522 if ((optlines = readfile(pid_file)) != NULL &&
523 optlines[0] != NULL &&
524 optlines[1] != NULL &&
527 if (optlines[3] == NULL)
529 /* File is exactly three lines, must be pre-9.1 */
530 write_stderr(_("\n%s: -w option is not supported when starting a pre-9.1 server\n"),
532 return PQPING_NO_ATTEMPT;
534 else if (optlines[4] != NULL &&
537 /* File is complete enough for us, parse it */
542 * Make sanity checks. If it's for a standalone backend
543 * (negative PID), or the recorded start time is before
544 * pg_ctl started, then either we are looking at the wrong
545 * data directory, or this is a pre-existing pidfile that
546 * hasn't (yet?) been overwritten by our child postmaster.
547 * Allow 2 seconds slop for possible cross-process clock
550 pmpid = atol(optlines[LOCK_FILE_LINE_PID - 1]);
551 pmstart = atol(optlines[LOCK_FILE_LINE_START_TIME - 1]);
552 if (pmpid <= 0 || pmstart < start_time - 2)
555 * Set flag to report stale pidfile if it doesn't get
556 * overwritten before we give up waiting.
558 found_stale_pidfile = true;
563 * OK, seems to be a valid pidfile from our child.
568 char host_str[MAXPGPATH];
570 found_stale_pidfile = false;
571 pm_pid = (pgpid_t) pmpid;
574 * Extract port number and host string to use. Prefer
575 * using Unix socket if available.
577 portnum = atoi(optlines[LOCK_FILE_LINE_PORT - 1]);
578 sockdir = optlines[LOCK_FILE_LINE_SOCKET_DIR - 1];
579 hostaddr = optlines[LOCK_FILE_LINE_LISTEN_ADDR - 1];
582 * While unix_socket_directories can accept relative
583 * directories, libpq's host parameter must have a
584 * leading slash to indicate a socket directory. So,
585 * ignore sockdir if it's relative, and try to use TCP
588 if (sockdir[0] == '/')
589 strlcpy(host_str, sockdir, sizeof(host_str));
591 strlcpy(host_str, hostaddr, sizeof(host_str));
593 /* remove trailing newline */
594 if (strchr(host_str, '\n') != NULL)
595 *strchr(host_str, '\n') = '\0';
597 /* Fail if couldn't get either sockdir or host addr */
598 if (host_str[0] == '\0')
600 write_stderr(_("\n%s: -w option cannot use a relative socket directory specification\n"),
602 return PQPING_NO_ATTEMPT;
605 /* If postmaster is listening on "*", use localhost */
606 if (strcmp(host_str, "*") == 0)
607 strcpy(host_str, "localhost");
610 * We need to set connect_timeout otherwise on Windows
611 * the Service Control Manager (SCM) will probably
614 snprintf(connstr, sizeof(connstr),
615 "dbname=postgres port=%d host='%s' connect_timeout=5",
622 * Free the results of readfile.
624 * This is safe to call even if optlines is NULL.
626 free_readfile(optlines);
629 /* If we have a connection string, ping the server */
630 if (connstr[0] != '\0')
632 ret = PQping(connstr);
633 if (ret == PQPING_OK || ret == PQPING_NO_ATTEMPT)
638 * The postmaster should create postmaster.pid very soon after being
639 * started. If it's not there after we've waited 5 or more seconds,
640 * assume startup failed and give up waiting. (Note this covers both
641 * cases where the pidfile was never created, and where it was created
642 * and then removed during postmaster exit.) Also, if there *is* a
643 * file there but it appears stale, issue a suitable warning and give
650 if (stat(pid_file, &statbuf) != 0)
653 write_stderr(_("\n%s: could not stat file \"%s\": %s\n"),
654 progname, pid_file, strerror(errno));
655 return PQPING_NO_RESPONSE;
658 if (found_stale_pidfile)
660 write_stderr(_("\n%s: this data directory appears to be running a pre-existing postmaster\n"),
662 return PQPING_NO_RESPONSE;
667 * If we've been able to identify the child postmaster's PID, check
668 * the process is still alive. This covers cases where the postmaster
669 * successfully created the pidfile but then crashed without removing
672 if (pm_pid > 0 && !postmaster_is_alive((pid_t) pm_pid))
673 return PQPING_NO_RESPONSE;
675 /* No response, or startup still in process; wait */
680 * Increment the wait hint by 6 secs (connection timeout + sleep)
681 * We must do this to indicate to the SCM that our startup time is
682 * changing, otherwise it'll usually send a stop signal after 20
683 * seconds, despite incrementing the checkpoint counter.
685 status.dwWaitHint += 6000;
686 status.dwCheckPoint++;
687 SetServiceStatus(hStatus, (LPSERVICE_STATUS) &status);
693 pg_usleep(1000000); /* 1 sec */
696 /* return result of last call to PQping */
701 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_CORE)
703 unlimit_core_size(void)
707 getrlimit(RLIMIT_CORE, &lim);
708 if (lim.rlim_max == 0)
710 write_stderr(_("%s: cannot set core file size limit; disallowed by hard limit\n"),
714 else if (lim.rlim_max == RLIM_INFINITY || lim.rlim_cur < lim.rlim_max)
716 lim.rlim_cur = lim.rlim_max;
717 setrlimit(RLIMIT_CORE, &lim);
725 if (post_opts == NULL)
727 post_opts = ""; /* default */
728 if (ctl_command == RESTART_COMMAND)
732 optlines = readfile(postopts_file);
733 if (optlines == NULL)
735 write_stderr(_("%s: could not read file \"%s\"\n"), progname, postopts_file);
738 else if (optlines[0] == NULL || optlines[1] != NULL)
740 write_stderr(_("%s: option file \"%s\" must have exactly one line\n"),
741 progname, postopts_file);
750 optline = optlines[0];
751 /* trim off line endings */
752 len = strcspn(optline, "\r\n");
756 * Are we at the first option, as defined by space and
759 if ((arg1 = strstr(optline, " \"")) != NULL)
761 *arg1 = '\0'; /* terminate so we get only program
763 post_opts = pg_strdup(arg1 + 1); /* point past whitespace */
765 if (exec_path == NULL)
766 exec_path = pg_strdup(optline);
769 /* Free the results of readfile. */
770 free_readfile(optlines);
776 find_other_exec_or_die(const char *argv0, const char *target, const char *versionstr)
781 found_path = pg_malloc(MAXPGPATH);
783 if ((ret = find_other_exec(argv0, target, versionstr, found_path)) < 0)
785 char full_path[MAXPGPATH];
787 if (find_my_exec(argv0, full_path) < 0)
788 strlcpy(full_path, progname, sizeof(full_path));
791 write_stderr(_("The program \"%s\" is needed by %s "
792 "but was not found in the\n"
793 "same directory as \"%s\".\n"
794 "Check your installation.\n"),
795 target, progname, full_path);
797 write_stderr(_("The program \"%s\" was found by \"%s\"\n"
798 "but was not the same version as %s.\n"
799 "Check your installation.\n"),
800 target, full_path, progname);
812 if (exec_path == NULL)
813 exec_path = find_other_exec_or_die(argv0, "initdb", "initdb (PostgreSQL) " PG_VERSION "\n");
815 if (pgdata_opt == NULL)
818 if (post_opts == NULL)
822 snprintf(cmd, MAXPGPATH, "\"%s\" %s%s",
823 exec_path, pgdata_opt, post_opts);
825 snprintf(cmd, MAXPGPATH, "\"%s\" %s%s > \"%s\"",
826 exec_path, pgdata_opt, post_opts, DEVNULL);
828 if (system(cmd) != 0)
830 write_stderr(_("%s: database system initialization failed\n"), progname);
841 if (ctl_command != RESTART_COMMAND)
843 old_pid = get_pgpid(false);
845 write_stderr(_("%s: another server might be running; "
846 "trying to start server anyway\n"),
852 /* No -D or -D already added during server start */
853 if (ctl_command == RESTART_COMMAND || pgdata_opt == NULL)
856 if (exec_path == NULL)
857 exec_path = find_other_exec_or_die(argv0, "postgres", PG_BACKEND_VERSIONSTR);
859 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_CORE)
860 if (allow_core_files)
865 * If possible, tell the postmaster our parent shell's PID (see the
866 * comments in CreateLockFile() for motivation). Windows hasn't got
867 * getppid() unfortunately.
871 static char env_var[32];
873 snprintf(env_var, sizeof(env_var), "PG_GRANDPARENT_PID=%d",
879 exitcode = start_postmaster();
882 write_stderr(_("%s: could not start server: exit code was %d\n"),
889 print_msg(_("waiting for server to start..."));
891 switch (test_postmaster_connection(false))
894 print_msg(_(" done\n"));
895 print_msg(_("server started\n"));
898 print_msg(_(" stopped waiting\n"));
899 print_msg(_("server is still starting up\n"));
901 case PQPING_NO_RESPONSE:
902 print_msg(_(" stopped waiting\n"));
903 write_stderr(_("%s: could not start server\n"
904 "Examine the log output.\n"),
908 case PQPING_NO_ATTEMPT:
909 print_msg(_(" failed\n"));
910 write_stderr(_("%s: could not wait for server because of misconfiguration\n"),
916 print_msg(_("server starting\n"));
927 pid = get_pgpid(false);
929 if (pid == 0) /* no pid file */
931 write_stderr(_("%s: PID file \"%s\" does not exist\n"), progname, pid_file);
932 write_stderr(_("Is server running?\n"));
935 else if (pid < 0) /* standalone backend, not postmaster */
938 write_stderr(_("%s: cannot stop server; "
939 "single-user server is running (PID: %ld)\n"),
944 if (kill((pid_t) pid, sig) != 0)
946 write_stderr(_("%s: could not send stop signal (PID: %ld): %s\n"), progname, pid,
953 print_msg(_("server shutting down\n"));
959 * If backup_label exists, an online backup is running. Warn the user
960 * that smart shutdown will wait for it to finish. However, if
961 * recovery.conf is also present, we're recovering from an online
962 * backup instead of performing one.
964 if (shutdown_mode == SMART_MODE &&
965 stat(backup_file, &statbuf) == 0 &&
966 stat(recovery_file, &statbuf) != 0)
968 print_msg(_("WARNING: online backup mode is active\n"
969 "Shutdown will not complete until pg_stop_backup() is called.\n\n"));
972 print_msg(_("waiting for server to shut down..."));
974 for (cnt = 0; cnt < wait_seconds; cnt++)
976 if ((pid = get_pgpid(false)) != 0)
979 pg_usleep(1000000); /* 1 sec */
985 if (pid != 0) /* pid file still exists */
987 print_msg(_(" failed\n"));
989 write_stderr(_("%s: server does not shut down\n"), progname);
990 if (shutdown_mode == SMART_MODE)
991 write_stderr(_("HINT: The \"-m fast\" option immediately disconnects sessions rather than\n"
992 "waiting for session-initiated disconnection.\n"));
995 print_msg(_(" done\n"));
997 print_msg(_("server stopped\n"));
1003 * restart/reload routines
1011 struct stat statbuf;
1013 pid = get_pgpid(false);
1015 if (pid == 0) /* no pid file */
1017 write_stderr(_("%s: PID file \"%s\" does not exist\n"),
1018 progname, pid_file);
1019 write_stderr(_("Is server running?\n"));
1020 write_stderr(_("starting server anyway\n"));
1024 else if (pid < 0) /* standalone backend, not postmaster */
1027 if (postmaster_is_alive((pid_t) pid))
1029 write_stderr(_("%s: cannot restart server; "
1030 "single-user server is running (PID: %ld)\n"),
1032 write_stderr(_("Please terminate the single-user server and try again.\n"));
1037 if (postmaster_is_alive((pid_t) pid))
1039 if (kill((pid_t) pid, sig) != 0)
1041 write_stderr(_("%s: could not send stop signal (PID: %ld): %s\n"), progname, pid,
1047 * If backup_label exists, an online backup is running. Warn the user
1048 * that smart shutdown will wait for it to finish. However, if
1049 * recovery.conf is also present, we're recovering from an online
1050 * backup instead of performing one.
1052 if (shutdown_mode == SMART_MODE &&
1053 stat(backup_file, &statbuf) == 0 &&
1054 stat(recovery_file, &statbuf) != 0)
1056 print_msg(_("WARNING: online backup mode is active\n"
1057 "Shutdown will not complete until pg_stop_backup() is called.\n\n"));
1060 print_msg(_("waiting for server to shut down..."));
1062 /* always wait for restart */
1064 for (cnt = 0; cnt < wait_seconds; cnt++)
1066 if ((pid = get_pgpid(false)) != 0)
1069 pg_usleep(1000000); /* 1 sec */
1075 if (pid != 0) /* pid file still exists */
1077 print_msg(_(" failed\n"));
1079 write_stderr(_("%s: server does not shut down\n"), progname);
1080 if (shutdown_mode == SMART_MODE)
1081 write_stderr(_("HINT: The \"-m fast\" option immediately disconnects sessions rather than\n"
1082 "waiting for session-initiated disconnection.\n"));
1086 print_msg(_(" done\n"));
1087 print_msg(_("server stopped\n"));
1091 write_stderr(_("%s: old server process (PID: %ld) seems to be gone\n"),
1093 write_stderr(_("starting server anyway\n"));
1104 pid = get_pgpid(false);
1105 if (pid == 0) /* no pid file */
1107 write_stderr(_("%s: PID file \"%s\" does not exist\n"), progname, pid_file);
1108 write_stderr(_("Is server running?\n"));
1111 else if (pid < 0) /* standalone backend, not postmaster */
1114 write_stderr(_("%s: cannot reload server; "
1115 "single-user server is running (PID: %ld)\n"),
1117 write_stderr(_("Please terminate the single-user server and try again.\n"));
1121 if (kill((pid_t) pid, sig) != 0)
1123 write_stderr(_("%s: could not send reload signal (PID: %ld): %s\n"),
1124 progname, pid, strerror(errno));
1128 print_msg(_("server signaled\n"));
1141 struct stat statbuf;
1143 pid = get_pgpid(false);
1145 if (pid == 0) /* no pid file */
1147 write_stderr(_("%s: PID file \"%s\" does not exist\n"), progname, pid_file);
1148 write_stderr(_("Is server running?\n"));
1151 else if (pid < 0) /* standalone backend, not postmaster */
1154 write_stderr(_("%s: cannot promote server; "
1155 "single-user server is running (PID: %ld)\n"),
1160 /* If recovery.conf doesn't exist, the server is not in standby mode */
1161 if (stat(recovery_file, &statbuf) != 0)
1163 write_stderr(_("%s: cannot promote server; "
1164 "server is not in standby mode\n"),
1170 * For 9.3 onwards, "fast" promotion is performed. Promotion with a full
1171 * checkpoint is still possible by writing a file called
1172 * "fallback_promote" instead of "promote"
1174 snprintf(promote_file, MAXPGPATH, "%s/promote", pg_data);
1176 if ((prmfile = fopen(promote_file, "w")) == NULL)
1178 write_stderr(_("%s: could not create promote signal file \"%s\": %s\n"),
1179 progname, promote_file, strerror(errno));
1182 if (fclose(prmfile))
1184 write_stderr(_("%s: could not write promote signal file \"%s\": %s\n"),
1185 progname, promote_file, strerror(errno));
1190 if (kill((pid_t) pid, sig) != 0)
1192 write_stderr(_("%s: could not send promote signal (PID: %ld): %s\n"),
1193 progname, pid, strerror(errno));
1194 if (unlink(promote_file) != 0)
1195 write_stderr(_("%s: could not remove promote signal file \"%s\": %s\n"),
1196 progname, promote_file, strerror(errno));
1200 print_msg(_("server promoting\n"));
1209 postmaster_is_alive(pid_t pid)
1212 * Test to see if the process is still there. Note that we do not
1213 * consider an EPERM failure to mean that the process is still there;
1214 * EPERM must mean that the given PID belongs to some other userid, and
1215 * considering the permissions on $PGDATA, that means it's not the
1216 * postmaster we are after.
1218 * Don't believe that our own PID or parent shell's PID is the postmaster,
1219 * either. (Windows hasn't got getppid(), though.)
1221 if (pid == getpid())
1224 if (pid == getppid())
1227 if (kill(pid, 0) == 0)
1237 pid = get_pgpid(true);
1238 /* Is there a pid file? */
1241 /* standalone backend? */
1245 if (postmaster_is_alive((pid_t) pid))
1247 printf(_("%s: single-user server is running (PID: %ld)\n"),
1253 /* must be a postmaster */
1255 if (postmaster_is_alive((pid_t) pid))
1260 printf(_("%s: server is running (PID: %ld)\n"),
1263 optlines = readfile(postopts_file);
1264 if (optlines != NULL)
1266 for (curr_line = optlines; *curr_line != NULL; curr_line++)
1267 fputs(*curr_line, stdout);
1269 /* Free the results of readfile */
1270 free_readfile(optlines);
1276 printf(_("%s: no server running\n"), progname);
1279 * The Linux Standard Base Core Specification 3.1 says this should return
1280 * '3, program is not running'
1281 * https://refspecs.linuxbase.org/LSB_3.1.0/LSB-Core-generic/LSB-Core-gener
1282 * ic/iniscrptact.html
1290 do_kill(pgpid_t pid)
1292 if (kill((pid_t) pid, sig) != 0)
1294 write_stderr(_("%s: could not send signal %d (PID: %ld): %s\n"),
1295 progname, sig, pid, strerror(errno));
1300 #if defined(WIN32) || defined(__CYGWIN__)
1302 #if (_MSC_VER < 1800)
1304 IsWindowsXPOrGreater(void)
1308 osv.dwOSVersionInfoSize = sizeof(osv);
1310 /* Windows XP = Version 5.1 */
1311 return (!GetVersionEx(&osv) || /* could not get version */
1312 osv.dwMajorVersion > 5 || (osv.dwMajorVersion == 5 && osv.dwMinorVersion >= 1));
1316 IsWindows7OrGreater(void)
1320 osv.dwOSVersionInfoSize = sizeof(osv);
1322 /* Windows 7 = Version 6.0 */
1323 return (!GetVersionEx(&osv) || /* could not get version */
1324 osv.dwMajorVersion > 6 || (osv.dwMajorVersion == 6 && osv.dwMinorVersion >= 0));
1329 pgwin32_IsInstalled(SC_HANDLE hSCM)
1331 SC_HANDLE hService = OpenService(hSCM, register_servicename, SERVICE_QUERY_CONFIG);
1332 bool bResult = (hService != NULL);
1335 CloseServiceHandle(hService);
1340 pgwin32_CommandLine(bool registration)
1342 PQExpBuffer cmdLine = createPQExpBuffer();
1343 char cmdPath[MAXPGPATH];
1348 ret = find_my_exec(argv0, cmdPath);
1351 write_stderr(_("%s: could not find own program executable\n"), progname);
1357 ret = find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
1361 write_stderr(_("%s: could not find postgres program executable\n"), progname);
1367 /* need to convert to windows path */
1369 char buf[MAXPGPATH];
1371 #if CYGWIN_VERSION_DLL_MAJOR >= 1007
1372 cygwin_conv_path(CCP_POSIX_TO_WIN_A, cmdPath, buf, sizeof(buf));
1374 cygwin_conv_to_full_win32_path(cmdPath, buf);
1376 strcpy(cmdPath, buf);
1380 /* if path does not end in .exe, append it */
1381 if (strlen(cmdPath) < 4 ||
1382 pg_strcasecmp(cmdPath + strlen(cmdPath) - 4, ".exe") != 0)
1383 snprintf(cmdPath + strlen(cmdPath), sizeof(cmdPath) - strlen(cmdPath),
1386 /* use backslashes in path to avoid problems with some third-party tools */
1387 make_native_path(cmdPath);
1389 /* be sure to double-quote the executable's name in the command */
1390 appendPQExpBuffer(cmdLine, "\"%s\"", cmdPath);
1392 /* append assorted switches to the command line, as needed */
1395 appendPQExpBuffer(cmdLine, " runservice -N \"%s\"",
1396 register_servicename);
1400 /* We need the -D path to be absolute */
1403 if ((dataDir = make_absolute_path(pg_config)) == NULL)
1405 /* make_absolute_path already reported the error */
1408 make_native_path(dataDir);
1409 appendPQExpBuffer(cmdLine, " -D \"%s\"", dataDir);
1413 if (registration && event_source != NULL)
1414 appendPQExpBuffer(cmdLine, " -e \"%s\"", event_source);
1416 if (registration && do_wait)
1417 appendPQExpBuffer(cmdLine, " -w");
1419 if (registration && wait_seconds != DEFAULT_WAIT)
1420 appendPQExpBuffer(cmdLine, " -t %d", wait_seconds);
1422 if (registration && silent_mode)
1423 appendPQExpBuffer(cmdLine, " -s");
1428 appendPQExpBuffer(cmdLine, " -o \"%s\"", post_opts);
1430 appendPQExpBuffer(cmdLine, " %s", post_opts);
1433 return cmdLine->data;
1437 pgwin32_doRegister(void)
1440 SC_HANDLE hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
1444 write_stderr(_("%s: could not open service manager\n"), progname);
1447 if (pgwin32_IsInstalled(hSCM))
1449 CloseServiceHandle(hSCM);
1450 write_stderr(_("%s: service \"%s\" already registered\n"), progname, register_servicename);
1454 if ((hService = CreateService(hSCM, register_servicename, register_servicename,
1455 SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
1456 pgctl_start_type, SERVICE_ERROR_NORMAL,
1457 pgwin32_CommandLine(true),
1458 NULL, NULL, "RPCSS\0", register_username, register_password)) == NULL)
1460 CloseServiceHandle(hSCM);
1461 write_stderr(_("%s: could not register service \"%s\": error code %lu\n"),
1462 progname, register_servicename,
1463 (unsigned long) GetLastError());
1466 CloseServiceHandle(hService);
1467 CloseServiceHandle(hSCM);
1471 pgwin32_doUnregister(void)
1474 SC_HANDLE hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
1478 write_stderr(_("%s: could not open service manager\n"), progname);
1481 if (!pgwin32_IsInstalled(hSCM))
1483 CloseServiceHandle(hSCM);
1484 write_stderr(_("%s: service \"%s\" not registered\n"), progname, register_servicename);
1488 if ((hService = OpenService(hSCM, register_servicename, DELETE)) == NULL)
1490 CloseServiceHandle(hSCM);
1491 write_stderr(_("%s: could not open service \"%s\": error code %lu\n"),
1492 progname, register_servicename,
1493 (unsigned long) GetLastError());
1496 if (!DeleteService(hService))
1498 CloseServiceHandle(hService);
1499 CloseServiceHandle(hSCM);
1500 write_stderr(_("%s: could not unregister service \"%s\": error code %lu\n"),
1501 progname, register_servicename,
1502 (unsigned long) GetLastError());
1505 CloseServiceHandle(hService);
1506 CloseServiceHandle(hSCM);
1510 pgwin32_SetServiceStatus(DWORD currentState)
1512 status.dwCurrentState = currentState;
1513 SetServiceStatus(hStatus, (LPSERVICE_STATUS) &status);
1517 pgwin32_ServiceHandler(DWORD request)
1521 case SERVICE_CONTROL_STOP:
1522 case SERVICE_CONTROL_SHUTDOWN:
1525 * We only need a short wait hint here as it just needs to wait
1526 * for the next checkpoint. They occur every 5 seconds during
1529 status.dwWaitHint = 10000;
1530 pgwin32_SetServiceStatus(SERVICE_STOP_PENDING);
1531 SetEvent(shutdownEvent);
1534 case SERVICE_CONTROL_PAUSE:
1535 /* Win32 config reloading */
1536 status.dwWaitHint = 5000;
1537 kill(postmasterPID, SIGHUP);
1540 /* FIXME: These could be used to replace other signals etc */
1541 case SERVICE_CONTROL_CONTINUE:
1542 case SERVICE_CONTROL_INTERROGATE:
1549 pgwin32_ServiceMain(DWORD argc, LPTSTR *argv)
1551 PROCESS_INFORMATION pi;
1554 /* Initialize variables */
1555 status.dwWin32ExitCode = S_OK;
1556 status.dwCheckPoint = 0;
1557 status.dwWaitHint = 60000;
1558 status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
1559 status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_PAUSE_CONTINUE;
1560 status.dwServiceSpecificExitCode = 0;
1561 status.dwCurrentState = SERVICE_START_PENDING;
1563 memset(&pi, 0, sizeof(pi));
1567 /* Register the control request handler */
1568 if ((hStatus = RegisterServiceCtrlHandler(register_servicename, pgwin32_ServiceHandler)) == (SERVICE_STATUS_HANDLE) 0)
1571 if ((shutdownEvent = CreateEvent(NULL, true, false, NULL)) == NULL)
1574 /* Start the postmaster */
1575 pgwin32_SetServiceStatus(SERVICE_START_PENDING);
1576 if (!CreateRestrictedProcess(pgwin32_CommandLine(false), &pi, true))
1578 pgwin32_SetServiceStatus(SERVICE_STOPPED);
1581 postmasterPID = pi.dwProcessId;
1582 postmasterProcess = pi.hProcess;
1583 CloseHandle(pi.hThread);
1587 write_eventlog(EVENTLOG_INFORMATION_TYPE, _("Waiting for server startup...\n"));
1588 if (test_postmaster_connection(true) != PQPING_OK)
1590 write_eventlog(EVENTLOG_ERROR_TYPE, _("Timed out waiting for server startup\n"));
1591 pgwin32_SetServiceStatus(SERVICE_STOPPED);
1594 write_eventlog(EVENTLOG_INFORMATION_TYPE, _("Server started and accepting connections\n"));
1597 pgwin32_SetServiceStatus(SERVICE_RUNNING);
1599 /* Wait for quit... */
1600 ret = WaitForMultipleObjects(2, shutdownHandles, FALSE, INFINITE);
1602 pgwin32_SetServiceStatus(SERVICE_STOP_PENDING);
1605 case WAIT_OBJECT_0: /* shutdown event */
1608 * status.dwCheckPoint can be incremented by
1609 * test_postmaster_connection(true), so it might not start
1612 int maxShutdownCheckPoint = status.dwCheckPoint + 12;;
1614 kill(postmasterPID, SIGINT);
1617 * Increment the checkpoint and try again. Abort after 12
1618 * checkpoints as the postmaster has probably hung.
1620 while (WaitForSingleObject(postmasterProcess, 5000) == WAIT_TIMEOUT && status.dwCheckPoint < maxShutdownCheckPoint)
1622 status.dwCheckPoint++;
1623 SetServiceStatus(hStatus, (LPSERVICE_STATUS) &status);
1628 case (WAIT_OBJECT_0 + 1): /* postmaster went down */
1632 /* shouldn't get here? */
1636 CloseHandle(shutdownEvent);
1637 CloseHandle(postmasterProcess);
1639 pgwin32_SetServiceStatus(SERVICE_STOPPED);
1643 pgwin32_doRunAsService(void)
1645 SERVICE_TABLE_ENTRY st[] = {{register_servicename, pgwin32_ServiceMain},
1648 if (StartServiceCtrlDispatcher(st) == 0)
1650 write_stderr(_("%s: could not start service \"%s\": error code %lu\n"),
1651 progname, register_servicename,
1652 (unsigned long) GetLastError());
1659 * Mingw headers are incomplete, and so are the libraries. So we have to load
1660 * a whole lot of API functions dynamically. Since we have to do this anyway,
1661 * also load the couple of functions that *do* exist in minwg headers but not
1662 * on NT4. That way, we don't break on NT4.
1664 typedef BOOL (WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE);
1665 typedef BOOL (WINAPI * __IsProcessInJob) (HANDLE, HANDLE, PBOOL);
1666 typedef HANDLE (WINAPI * __CreateJobObject) (LPSECURITY_ATTRIBUTES, LPCTSTR);
1667 typedef BOOL (WINAPI * __SetInformationJobObject) (HANDLE, JOBOBJECTINFOCLASS, LPVOID, DWORD);
1668 typedef BOOL (WINAPI * __AssignProcessToJobObject) (HANDLE, HANDLE);
1669 typedef BOOL (WINAPI * __QueryInformationJobObject) (HANDLE, JOBOBJECTINFOCLASS, LPVOID, DWORD, LPDWORD);
1671 /* Windows API define missing from some versions of MingW headers */
1672 #ifndef DISABLE_MAX_PRIVILEGE
1673 #define DISABLE_MAX_PRIVILEGE 0x1
1677 * Create a restricted token, a job object sandbox, and execute the specified
1680 * Returns 0 on success, non-zero on failure, same as CreateProcess().
1682 * On NT4, or any other system not containing the required functions, will
1683 * launch the process under the current token without doing any modifications.
1685 * NOTE! Job object will only work when running as a service, because it's
1686 * automatically destroyed when pg_ctl exits.
1689 CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, bool as_service)
1695 HANDLE restrictedToken;
1696 SID_IDENTIFIER_AUTHORITY NtAuthority = {SECURITY_NT_AUTHORITY};
1697 SID_AND_ATTRIBUTES dropSids[2];
1699 /* Functions loaded dynamically */
1700 __CreateRestrictedToken _CreateRestrictedToken = NULL;
1701 __IsProcessInJob _IsProcessInJob = NULL;
1702 __CreateJobObject _CreateJobObject = NULL;
1703 __SetInformationJobObject _SetInformationJobObject = NULL;
1704 __AssignProcessToJobObject _AssignProcessToJobObject = NULL;
1705 __QueryInformationJobObject _QueryInformationJobObject = NULL;
1706 HANDLE Kernel32Handle;
1707 HANDLE Advapi32Handle;
1709 ZeroMemory(&si, sizeof(si));
1712 Advapi32Handle = LoadLibrary("ADVAPI32.DLL");
1713 if (Advapi32Handle != NULL)
1715 _CreateRestrictedToken = (__CreateRestrictedToken) GetProcAddress(Advapi32Handle, "CreateRestrictedToken");
1718 if (_CreateRestrictedToken == NULL)
1721 * NT4 doesn't have CreateRestrictedToken, so just call ordinary
1724 write_stderr(_("%s: WARNING: cannot create restricted tokens on this platform\n"), progname);
1725 if (Advapi32Handle != NULL)
1726 FreeLibrary(Advapi32Handle);
1727 return CreateProcess(NULL, cmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, processInfo);
1730 /* Open the current token to use as a base for the restricted one */
1731 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken))
1734 * Most Windows targets make DWORD a 32-bit unsigned long. Cygwin
1735 * x86_64, an LP64 target, makes it a 32-bit unsigned int. In code
1736 * built for Cygwin as well as for native Windows targets, cast DWORD
1739 write_stderr(_("%s: could not open process token: error code %lu\n"),
1740 progname, (unsigned long) GetLastError());
1744 /* Allocate list of SIDs to remove */
1745 ZeroMemory(&dropSids, sizeof(dropSids));
1746 if (!AllocateAndInitializeSid(&NtAuthority, 2,
1747 SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0,
1748 0, &dropSids[0].Sid) ||
1749 !AllocateAndInitializeSid(&NtAuthority, 2,
1750 SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0,
1751 0, &dropSids[1].Sid))
1753 write_stderr(_("%s: could not allocate SIDs: error code %lu\n"),
1754 progname, (unsigned long) GetLastError());
1758 b = _CreateRestrictedToken(origToken,
1759 DISABLE_MAX_PRIVILEGE,
1760 sizeof(dropSids) / sizeof(dropSids[0]),
1766 FreeSid(dropSids[1].Sid);
1767 FreeSid(dropSids[0].Sid);
1768 CloseHandle(origToken);
1769 FreeLibrary(Advapi32Handle);
1773 write_stderr(_("%s: could not create restricted token: error code %lu\n"),
1774 progname, (unsigned long) GetLastError());
1779 AddUserToTokenDacl(restrictedToken);
1782 r = CreateProcessAsUser(restrictedToken, NULL, cmd, NULL, NULL, TRUE, CREATE_SUSPENDED, NULL, NULL, &si, processInfo);
1784 Kernel32Handle = LoadLibrary("KERNEL32.DLL");
1785 if (Kernel32Handle != NULL)
1787 _IsProcessInJob = (__IsProcessInJob) GetProcAddress(Kernel32Handle, "IsProcessInJob");
1788 _CreateJobObject = (__CreateJobObject) GetProcAddress(Kernel32Handle, "CreateJobObjectA");
1789 _SetInformationJobObject = (__SetInformationJobObject) GetProcAddress(Kernel32Handle, "SetInformationJobObject");
1790 _AssignProcessToJobObject = (__AssignProcessToJobObject) GetProcAddress(Kernel32Handle, "AssignProcessToJobObject");
1791 _QueryInformationJobObject = (__QueryInformationJobObject) GetProcAddress(Kernel32Handle, "QueryInformationJobObject");
1794 /* Verify that we found all functions */
1795 if (_IsProcessInJob == NULL || _CreateJobObject == NULL || _SetInformationJobObject == NULL || _AssignProcessToJobObject == NULL || _QueryInformationJobObject == NULL)
1798 * IsProcessInJob() is not available on < WinXP, so there is no need
1799 * to log the error every time in that case
1801 if (IsWindowsXPOrGreater())
1804 * Log error if we can't get version, or if we're on WinXP/2003 or
1807 write_stderr(_("%s: WARNING: could not locate all job object functions in system API\n"), progname);
1813 if (_IsProcessInJob(processInfo->hProcess, NULL, &inJob))
1818 * Job objects are working, and the new process isn't in one,
1819 * so we can create one safely. If any problems show up when
1820 * setting it, we're going to ignore them.
1825 sprintf(jobname, "PostgreSQL_%lu",
1826 (unsigned long) processInfo->dwProcessId);
1828 job = _CreateJobObject(NULL, jobname);
1831 JOBOBJECT_BASIC_LIMIT_INFORMATION basicLimit;
1832 JOBOBJECT_BASIC_UI_RESTRICTIONS uiRestrictions;
1833 JOBOBJECT_SECURITY_LIMIT_INFORMATION securityLimit;
1835 ZeroMemory(&basicLimit, sizeof(basicLimit));
1836 ZeroMemory(&uiRestrictions, sizeof(uiRestrictions));
1837 ZeroMemory(&securityLimit, sizeof(securityLimit));
1839 basicLimit.LimitFlags = JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION | JOB_OBJECT_LIMIT_PRIORITY_CLASS;
1840 basicLimit.PriorityClass = NORMAL_PRIORITY_CLASS;
1841 _SetInformationJobObject(job, JobObjectBasicLimitInformation, &basicLimit, sizeof(basicLimit));
1843 uiRestrictions.UIRestrictionsClass = JOB_OBJECT_UILIMIT_DESKTOP | JOB_OBJECT_UILIMIT_DISPLAYSETTINGS |
1844 JOB_OBJECT_UILIMIT_EXITWINDOWS | JOB_OBJECT_UILIMIT_READCLIPBOARD |
1845 JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS | JOB_OBJECT_UILIMIT_WRITECLIPBOARD;
1849 if (!IsWindows7OrGreater())
1852 * On Windows 7 (and presumably later),
1853 * JOB_OBJECT_UILIMIT_HANDLES prevents us from
1854 * starting as a service. So we only enable it on
1855 * Vista and earlier (version <= 6.0)
1857 uiRestrictions.UIRestrictionsClass |= JOB_OBJECT_UILIMIT_HANDLES;
1860 _SetInformationJobObject(job, JobObjectBasicUIRestrictions, &uiRestrictions, sizeof(uiRestrictions));
1862 securityLimit.SecurityLimitFlags = JOB_OBJECT_SECURITY_NO_ADMIN | JOB_OBJECT_SECURITY_ONLY_TOKEN;
1863 securityLimit.JobToken = restrictedToken;
1864 _SetInformationJobObject(job, JobObjectSecurityLimitInformation, &securityLimit, sizeof(securityLimit));
1866 _AssignProcessToJobObject(job, processInfo->hProcess);
1873 CloseHandle(restrictedToken);
1875 ResumeThread(processInfo->hThread);
1877 FreeLibrary(Kernel32Handle);
1880 * We intentionally don't close the job object handle, because we want the
1881 * object to live on until pg_ctl shuts down.
1885 #endif /* defined(WIN32) || defined(__CYGWIN__) */
1890 write_stderr(_("Try \"%s --help\" for more information.\n"), progname);
1898 printf(_("%s is a utility to initialize, start, stop, or control a PostgreSQL server.\n\n"), progname);
1899 printf(_("Usage:\n"));
1900 printf(_(" %s init[db] [-D DATADIR] [-s] [-o \"OPTIONS\"]\n"), progname);
1901 printf(_(" %s start [-w] [-t SECS] [-D DATADIR] [-s] [-l FILENAME] [-o \"OPTIONS\"]\n"), progname);
1902 printf(_(" %s stop [-W] [-t SECS] [-D DATADIR] [-s] [-m SHUTDOWN-MODE]\n"), progname);
1903 printf(_(" %s restart [-w] [-t SECS] [-D DATADIR] [-s] [-m SHUTDOWN-MODE]\n"
1904 " [-o \"OPTIONS\"]\n"), progname);
1905 printf(_(" %s reload [-D DATADIR] [-s]\n"), progname);
1906 printf(_(" %s status [-D DATADIR]\n"), progname);
1907 printf(_(" %s promote [-D DATADIR] [-s]\n"), progname);
1908 printf(_(" %s kill SIGNALNAME PID\n"), progname);
1909 #if defined(WIN32) || defined(__CYGWIN__)
1910 printf(_(" %s register [-N SERVICENAME] [-U USERNAME] [-P PASSWORD] [-D DATADIR]\n"
1911 " [-S START-TYPE] [-w] [-t SECS] [-o \"OPTIONS\"]\n"), progname);
1912 printf(_(" %s unregister [-N SERVICENAME]\n"), progname);
1915 printf(_("\nCommon options:\n"));
1916 printf(_(" -D, --pgdata=DATADIR location of the database storage area\n"));
1917 #if defined(WIN32) || defined(__CYGWIN__)
1918 printf(_(" -e SOURCE event source for logging when running as a service\n"));
1920 printf(_(" -s, --silent only print errors, no informational messages\n"));
1921 printf(_(" -t, --timeout=SECS seconds to wait when using -w option\n"));
1922 printf(_(" -V, --version output version information, then exit\n"));
1923 printf(_(" -w wait until operation completes\n"));
1924 printf(_(" -W do not wait until operation completes\n"));
1925 printf(_(" -?, --help show this help, then exit\n"));
1926 printf(_("(The default is to wait for shutdown, but not for start or restart.)\n\n"));
1927 printf(_("If the -D option is omitted, the environment variable PGDATA is used.\n"));
1929 printf(_("\nOptions for start or restart:\n"));
1930 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_CORE)
1931 printf(_(" -c, --core-files allow postgres to produce core files\n"));
1933 printf(_(" -c, --core-files not applicable on this platform\n"));
1935 printf(_(" -l, --log=FILENAME write (or append) server log to FILENAME\n"));
1936 printf(_(" -o OPTIONS command line options to pass to postgres\n"
1937 " (PostgreSQL server executable) or initdb\n"));
1938 printf(_(" -p PATH-TO-POSTGRES normally not necessary\n"));
1939 printf(_("\nOptions for stop or restart:\n"));
1940 printf(_(" -m, --mode=MODE MODE can be \"smart\", \"fast\", or \"immediate\"\n"));
1942 printf(_("\nShutdown modes are:\n"));
1943 printf(_(" smart quit after all clients have disconnected\n"));
1944 printf(_(" fast quit directly, with proper shutdown\n"));
1945 printf(_(" immediate quit without complete shutdown; will lead to recovery on restart\n"));
1947 printf(_("\nAllowed signal names for kill:\n"));
1948 printf(" ABRT HUP INT QUIT TERM USR1 USR2\n");
1950 #if defined(WIN32) || defined(__CYGWIN__)
1951 printf(_("\nOptions for register and unregister:\n"));
1952 printf(_(" -N SERVICENAME service name with which to register PostgreSQL server\n"));
1953 printf(_(" -P PASSWORD password of account to register PostgreSQL server\n"));
1954 printf(_(" -U USERNAME user name of account to register PostgreSQL server\n"));
1955 printf(_(" -S START-TYPE service start type to register PostgreSQL server\n"));
1957 printf(_("\nStart types are:\n"));
1958 printf(_(" auto start service automatically during system startup (default)\n"));
1959 printf(_(" demand start service on demand\n"));
1962 printf(_("\nReport bugs to <pgsql-bugs@postgresql.org>.\n"));
1968 set_mode(char *modeopt)
1970 if (strcmp(modeopt, "s") == 0 || strcmp(modeopt, "smart") == 0)
1972 shutdown_mode = SMART_MODE;
1975 else if (strcmp(modeopt, "f") == 0 || strcmp(modeopt, "fast") == 0)
1977 shutdown_mode = FAST_MODE;
1980 else if (strcmp(modeopt, "i") == 0 || strcmp(modeopt, "immediate") == 0)
1982 shutdown_mode = IMMEDIATE_MODE;
1987 write_stderr(_("%s: unrecognized shutdown mode \"%s\"\n"), progname, modeopt);
1996 set_sig(char *signame)
1998 if (strcmp(signame, "HUP") == 0)
2000 else if (strcmp(signame, "INT") == 0)
2002 else if (strcmp(signame, "QUIT") == 0)
2004 else if (strcmp(signame, "ABRT") == 0)
2007 /* probably should NOT provide SIGKILL */
2008 else if (strcmp(signame, "KILL") == 0)
2011 else if (strcmp(signame, "TERM") == 0)
2013 else if (strcmp(signame, "USR1") == 0)
2015 else if (strcmp(signame, "USR2") == 0)
2019 write_stderr(_("%s: unrecognized signal name \"%s\"\n"), progname, signame);
2026 #if defined(WIN32) || defined(__CYGWIN__)
2028 set_starttype(char *starttypeopt)
2030 if (strcmp(starttypeopt, "a") == 0 || strcmp(starttypeopt, "auto") == 0)
2031 pgctl_start_type = SERVICE_AUTO_START;
2032 else if (strcmp(starttypeopt, "d") == 0 || strcmp(starttypeopt, "demand") == 0)
2033 pgctl_start_type = SERVICE_DEMAND_START;
2036 write_stderr(_("%s: unrecognized start type \"%s\"\n"), progname, starttypeopt);
2046 * If a configuration-only directory was specified, find the real data dir.
2049 adjust_data_dir(void)
2051 char cmd[MAXPGPATH],
2052 filename[MAXPGPATH],
2056 /* do nothing if we're working without knowledge of data dir */
2057 if (pg_config == NULL)
2060 /* If there is no postgresql.conf, it can't be a config-only dir */
2061 snprintf(filename, sizeof(filename), "%s/postgresql.conf", pg_config);
2062 if ((fd = fopen(filename, "r")) == NULL)
2066 /* If PG_VERSION exists, it can't be a config-only dir */
2067 snprintf(filename, sizeof(filename), "%s/PG_VERSION", pg_config);
2068 if ((fd = fopen(filename, "r")) != NULL)
2074 /* Must be a configuration directory, so find the data directory */
2076 /* we use a private my_exec_path to avoid interfering with later uses */
2077 if (exec_path == NULL)
2078 my_exec_path = find_other_exec_or_die(argv0, "postgres", PG_BACKEND_VERSIONSTR);
2080 my_exec_path = pg_strdup(exec_path);
2082 /* it's important for -C to be the first option, see main.c */
2083 snprintf(cmd, MAXPGPATH, "\"%s\" -C data_directory %s%s",
2085 pgdata_opt ? pgdata_opt : "",
2086 post_opts ? post_opts : "");
2088 fd = popen(cmd, "r");
2089 if (fd == NULL || fgets(filename, sizeof(filename), fd) == NULL)
2091 write_stderr(_("%s: could not determine the data directory using command \"%s\"\n"), progname, cmd);
2097 /* Remove trailing newline */
2098 if (strchr(filename, '\n') != NULL)
2099 *strchr(filename, '\n') = '\0';
2102 pg_data = pg_strdup(filename);
2103 canonicalize_path(pg_data);
2108 main(int argc, char **argv)
2110 static struct option long_options[] = {
2111 {"help", no_argument, NULL, '?'},
2112 {"version", no_argument, NULL, 'V'},
2113 {"log", required_argument, NULL, 'l'},
2114 {"mode", required_argument, NULL, 'm'},
2115 {"pgdata", required_argument, NULL, 'D'},
2116 {"silent", no_argument, NULL, 's'},
2117 {"timeout", required_argument, NULL, 't'},
2118 {"core-files", no_argument, NULL, 'c'},
2124 pgpid_t killproc = 0;
2126 #if defined(WIN32) || defined(__CYGWIN__)
2127 setvbuf(stderr, NULL, _IONBF, 0);
2130 progname = get_progname(argv[0]);
2131 set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_ctl"));
2132 start_time = time(NULL);
2135 * save argv[0] so do_start() can look for the postmaster if necessary. we
2136 * don't look for postmaster here because in many cases we won't need it.
2140 umask(S_IRWXG | S_IRWXO);
2142 /* support --help and --version even if invoked as root */
2145 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
2150 else if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
2152 puts("pg_ctl (PostgreSQL) " PG_VERSION);
2158 * Disallow running as root, to forestall any possible security holes.
2163 write_stderr(_("%s: cannot be run as root\n"
2164 "Please log in (using, e.g., \"su\") as the "
2165 "(unprivileged) user that will\n"
2166 "own the server process.\n"),
2173 * 'Action' can be before or after args so loop over both. Some
2174 * getopt_long() implementations will reorder argv[] to place all flags
2175 * first (GNU?), but we don't rely on it. Our /port version doesn't do
2180 /* process command-line options */
2181 while (optind < argc)
2183 while ((c = getopt_long(argc, argv, "cD:e:l:m:N:o:p:P:sS:t:U:wW", long_options, &option_index)) != -1)
2192 pgdata_D = pg_strdup(optarg);
2193 canonicalize_path(pgdata_D);
2194 env_var = psprintf("PGDATA=%s", pgdata_D);
2198 * We could pass PGDATA just in an environment
2199 * variable but we do -D too for clearer postmaster
2202 pgdata_opt = psprintf("-D \"%s\" ", pgdata_D);
2206 event_source = pg_strdup(optarg);
2209 log_file = pg_strdup(optarg);
2215 register_servicename = pg_strdup(optarg);
2218 /* append option? */
2220 post_opts = pg_strdup(optarg);
2223 char *old_post_opts = post_opts;
2225 post_opts = psprintf("%s %s", old_post_opts, optarg);
2226 free(old_post_opts);
2230 exec_path = pg_strdup(optarg);
2233 register_password = pg_strdup(optarg);
2239 #if defined(WIN32) || defined(__CYGWIN__)
2240 set_starttype(optarg);
2242 write_stderr(_("%s: -S option not supported on this platform\n"),
2248 wait_seconds = atoi(optarg);
2251 if (strchr(optarg, '\\'))
2252 register_username = pg_strdup(optarg);
2254 /* Prepend .\ for local accounts */
2255 register_username = psprintf(".\\%s", optarg);
2266 allow_core_files = true;
2269 /* getopt_long already issued a suitable error message */
2275 /* Process an action */
2278 if (ctl_command != NO_COMMAND)
2280 write_stderr(_("%s: too many command-line arguments (first is \"%s\")\n"), progname, argv[optind]);
2285 if (strcmp(argv[optind], "init") == 0
2286 || strcmp(argv[optind], "initdb") == 0)
2287 ctl_command = INIT_COMMAND;
2288 else if (strcmp(argv[optind], "start") == 0)
2289 ctl_command = START_COMMAND;
2290 else if (strcmp(argv[optind], "stop") == 0)
2291 ctl_command = STOP_COMMAND;
2292 else if (strcmp(argv[optind], "restart") == 0)
2293 ctl_command = RESTART_COMMAND;
2294 else if (strcmp(argv[optind], "reload") == 0)
2295 ctl_command = RELOAD_COMMAND;
2296 else if (strcmp(argv[optind], "status") == 0)
2297 ctl_command = STATUS_COMMAND;
2298 else if (strcmp(argv[optind], "promote") == 0)
2299 ctl_command = PROMOTE_COMMAND;
2300 else if (strcmp(argv[optind], "kill") == 0)
2302 if (argc - optind < 3)
2304 write_stderr(_("%s: missing arguments for kill mode\n"), progname);
2308 ctl_command = KILL_COMMAND;
2309 set_sig(argv[++optind]);
2310 killproc = atol(argv[++optind]);
2312 #if defined(WIN32) || defined(__CYGWIN__)
2313 else if (strcmp(argv[optind], "register") == 0)
2314 ctl_command = REGISTER_COMMAND;
2315 else if (strcmp(argv[optind], "unregister") == 0)
2316 ctl_command = UNREGISTER_COMMAND;
2317 else if (strcmp(argv[optind], "runservice") == 0)
2318 ctl_command = RUN_AS_SERVICE_COMMAND;
2322 write_stderr(_("%s: unrecognized operation mode \"%s\"\n"), progname, argv[optind]);
2330 if (ctl_command == NO_COMMAND)
2332 write_stderr(_("%s: no operation specified\n"), progname);
2337 /* Note we put any -D switch into the env var above */
2338 pg_config = getenv("PGDATA");
2341 pg_config = pg_strdup(pg_config);
2342 canonicalize_path(pg_config);
2343 pg_data = pg_strdup(pg_config);
2346 /* -D might point at config-only directory; if so find the real PGDATA */
2349 /* Complain if -D needed and not provided */
2350 if (pg_config == NULL &&
2351 ctl_command != KILL_COMMAND && ctl_command != UNREGISTER_COMMAND)
2353 write_stderr(_("%s: no database directory specified and environment variable PGDATA unset\n"),
2361 switch (ctl_command)
2363 case RESTART_COMMAND:
2375 if (ctl_command == RELOAD_COMMAND)
2383 snprintf(postopts_file, MAXPGPATH, "%s/postmaster.opts", pg_data);
2384 snprintf(version_file, MAXPGPATH, "%s/PG_VERSION", pg_data);
2385 snprintf(pid_file, MAXPGPATH, "%s/postmaster.pid", pg_data);
2386 snprintf(backup_file, MAXPGPATH, "%s/backup_label", pg_data);
2387 snprintf(recovery_file, MAXPGPATH, "%s/recovery.conf", pg_data);
2390 switch (ctl_command)
2395 case STATUS_COMMAND:
2404 case RESTART_COMMAND:
2407 case RELOAD_COMMAND:
2410 case PROMOTE_COMMAND:
2416 #if defined(WIN32) || defined(__CYGWIN__)
2417 case REGISTER_COMMAND:
2418 pgwin32_doRegister();
2420 case UNREGISTER_COMMAND:
2421 pgwin32_doUnregister();
2423 case RUN_AS_SERVICE_COMMAND:
2424 pgwin32_doRunAsService();