1 /*-------------------------------------------------------------------------
3 * pg_ctl --- start/stops/restarts the PostgreSQL server
5 * Portions Copyright (c) 1996-2013, 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"
27 #include <sys/types.h>
31 #ifdef HAVE_SYS_RESOURCE_H
33 #include <sys/resource.h>
36 #include "getopt_long.h"
37 #include "miscadmin.h"
39 #if defined(__CYGWIN__)
40 #include <sys/cygwin.h>
42 /* Cygwin defines WIN32 in windows.h, but we don't want it. */
46 /* PID can be negative for standalone backend */
71 RUN_AS_SERVICE_COMMAND
74 #define DEFAULT_WAIT 60
76 static bool do_wait = false;
77 static bool wait_set = false;
78 static int wait_seconds = DEFAULT_WAIT;
79 static bool silent_mode = false;
80 static ShutdownMode shutdown_mode = SMART_MODE;
81 static int sig = SIGTERM; /* default */
82 static CtlCommand ctl_command = NO_COMMAND;
83 static char *pg_data = NULL;
84 static char *pg_config = NULL;
85 static char *pgdata_opt = NULL;
86 static char *post_opts = NULL;
87 static const char *progname;
88 static char *log_file = NULL;
89 static char *exec_path = NULL;
90 static char *register_servicename = "PostgreSQL"; /* FIXME: + version ID? */
91 static char *register_username = NULL;
92 static char *register_password = NULL;
93 static char *argv0 = NULL;
94 static bool allow_core_files = false;
95 static time_t start_time;
97 static char postopts_file[MAXPGPATH];
98 static char pid_file[MAXPGPATH];
99 static char backup_file[MAXPGPATH];
100 static char recovery_file[MAXPGPATH];
101 static char promote_file[MAXPGPATH];
103 #if defined(WIN32) || defined(__CYGWIN__)
104 static DWORD pgctl_start_type = SERVICE_AUTO_START;
105 static SERVICE_STATUS status;
106 static SERVICE_STATUS_HANDLE hStatus = (SERVICE_STATUS_HANDLE) 0;
107 static HANDLE shutdownHandles[2];
108 static pid_t postmasterPID = -1;
110 #define shutdownEvent shutdownHandles[0]
111 #define postmasterProcess shutdownHandles[1]
116 write_stderr(const char *fmt,...)
117 /* This extension allows gcc to check the format string for consistency with
118 the supplied arguments. */
119 __attribute__((format(PG_PRINTF_ATTRIBUTE, 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 static bool pgwin32_IsInstalled(SC_HANDLE);
137 static char *pgwin32_CommandLine(bool);
138 static void pgwin32_doRegister(void);
139 static void pgwin32_doUnregister(void);
140 static void pgwin32_SetServiceStatus(DWORD);
141 static void WINAPI pgwin32_ServiceHandler(DWORD);
142 static void WINAPI pgwin32_ServiceMain(DWORD, LPTSTR *);
143 static void pgwin32_doRunAsService(void);
144 static int CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, bool as_service);
147 static pgpid_t get_pgpid(void);
148 static char **readfile(const char *path);
149 static int start_postmaster(void);
150 static void read_post_opts(void);
152 static PGPing test_postmaster_connection(bool);
153 static bool postmaster_is_alive(pid_t pid);
155 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_CORE)
156 static void unlimit_core_size(void);
160 #if defined(WIN32) || defined(__CYGWIN__)
162 write_eventlog(int level, const char *line)
164 static HANDLE evtHandle = INVALID_HANDLE_VALUE;
166 if (silent_mode && level == EVENTLOG_INFORMATION_TYPE)
169 if (evtHandle == INVALID_HANDLE_VALUE)
171 evtHandle = RegisterEventSource(NULL, "PostgreSQL");
172 if (evtHandle == NULL)
174 evtHandle = INVALID_HANDLE_VALUE;
179 ReportEvent(evtHandle,
182 0, /* All events are Id 0 */
192 * Write errors to stderr (or by equal means when stderr is
196 write_stderr(const char *fmt,...)
201 #if !defined(WIN32) && !defined(__CYGWIN__)
202 /* On Unix, we just fprintf to stderr */
203 vfprintf(stderr, fmt, ap);
207 * On Win32, we print to stderr if running on a console, or write to
208 * eventlog if running as a service
210 if (!isatty(fileno(stderr))) /* Running as a service */
212 char errbuf[2048]; /* Arbitrary size? */
214 vsnprintf(errbuf, sizeof(errbuf), fmt, ap);
216 write_eventlog(EVENTLOG_ERROR_TYPE, errbuf);
219 /* Not running as service, write to stderr */
220 vfprintf(stderr, fmt, ap);
226 * Given an already-localized string, print it to stdout unless the
227 * user has specified that no messages should be printed.
230 print_msg(const char *msg)
245 pidf = fopen(pid_file, "r");
248 /* No pid file, not an error on startup */
253 write_stderr(_("%s: could not open PID file \"%s\": %s\n"),
254 progname, pid_file, strerror(errno));
258 if (fscanf(pidf, "%ld", &pid) != 1)
260 /* Is the file empty? */
261 if (ftell(pidf) == 0 && feof(pidf))
262 write_stderr(_("%s: the PID file \"%s\" is empty\n"),
265 write_stderr(_("%s: invalid data in PID file \"%s\"\n"),
270 return (pgpid_t) pid;
275 * get the lines from a text file - return NULL if file can't be opened
278 readfile(const char *path)
291 * Slurp the file into memory.
293 * The file can change concurrently, so we read the whole file into memory
294 * with a single read() call. That's not guaranteed to get an atomic
295 * snapshot, but in practice, for a small file, it's close enough for the
298 fd = open(path, O_RDONLY | PG_BINARY, 0);
301 if (fstat(fd, &statbuf) < 0)
306 if (statbuf.st_size == 0)
310 result = (char **) pg_malloc(sizeof(char *));
314 buffer = pg_malloc(statbuf.st_size + 1);
316 len = read(fd, buffer, statbuf.st_size + 1);
318 if (len != statbuf.st_size)
320 /* oops, the file size changed between fstat and read */
326 * Count newlines. We expect there to be a newline after each full line,
327 * including one at the end of file. If there isn't a newline at the end,
328 * any characters after the last newline will be ignored.
331 for (i = 0; i < len; i++)
333 if (buffer[i] == '\n')
337 /* set up the result buffer */
338 result = (char **) pg_malloc((nlines + 1) * sizeof(char *));
340 /* now split the buffer into lines */
343 for (i = 0; i < len; i++)
345 if (buffer[i] == '\n')
347 int slen = &buffer[i] - linebegin + 1;
348 char *linebuf = pg_malloc(slen + 1);
350 memcpy(linebuf, linebegin, slen);
351 linebuf[slen] = '\0';
352 result[n++] = linebuf;
353 linebegin = &buffer[i + 1];
366 * start/test/stop routines
370 start_postmaster(void)
377 * Since there might be quotes to handle here, it is easier simply to pass
378 * everything to a shell to process them.
380 * XXX it would be better to fork and exec so that we would know the child
381 * postmaster's PID directly; then test_postmaster_connection could use
382 * the PID without having to rely on reading it back from the pidfile.
384 if (log_file != NULL)
385 snprintf(cmd, MAXPGPATH, SYSTEMQUOTE "\"%s\" %s%s < \"%s\" >> \"%s\" 2>&1 &" SYSTEMQUOTE,
386 exec_path, pgdata_opt, post_opts,
389 snprintf(cmd, MAXPGPATH, SYSTEMQUOTE "\"%s\" %s%s < \"%s\" 2>&1 &" SYSTEMQUOTE,
390 exec_path, pgdata_opt, post_opts, DEVNULL);
396 * On win32 we don't use system(). So we don't need to use & (which would
397 * be START /B on win32). However, we still call the shell (CMD.EXE) with
398 * it to handle redirection etc.
400 PROCESS_INFORMATION pi;
402 if (log_file != NULL)
403 snprintf(cmd, MAXPGPATH, "CMD /C " SYSTEMQUOTE "\"%s\" %s%s < \"%s\" >> \"%s\" 2>&1" SYSTEMQUOTE,
404 exec_path, pgdata_opt, post_opts, DEVNULL, log_file);
406 snprintf(cmd, MAXPGPATH, "CMD /C " SYSTEMQUOTE "\"%s\" %s%s < \"%s\" 2>&1" SYSTEMQUOTE,
407 exec_path, pgdata_opt, post_opts, DEVNULL);
409 if (!CreateRestrictedProcess(cmd, &pi, false))
410 return GetLastError();
411 CloseHandle(pi.hProcess);
412 CloseHandle(pi.hThread);
420 * Find the pgport and try a connection
422 * Note that the checkpoint parameter enables a Windows service control
423 * manager checkpoint, it's got nothing to do with database checkpoints!!
426 test_postmaster_connection(bool do_checkpoint)
428 PGPing ret = PQPING_NO_RESPONSE;
429 bool found_stale_pidfile = false;
431 char connstr[MAXPGPATH * 2 + 256];
434 /* if requested wait time is zero, return "still starting up" code */
435 if (wait_seconds <= 0)
436 return PQPING_REJECT;
440 for (i = 0; i < wait_seconds; i++)
442 /* Do we need a connection string? */
443 if (connstr[0] == '\0')
446 * The number of lines in postmaster.pid tells us several things:
449 * 0 lock file created but status not written
450 * 2 pre-9.1 server, shared memory not created
451 * 3 pre-9.1 server, shared memory created
452 * 5 9.1+ server, ports not opened
453 * 6 9.1+ server, shared memory not created
454 * 7 9.1+ server, shared memory created
456 * This code does not support pre-9.1 servers. On Unix machines
457 * we could consider extracting the port number from the shmem
458 * key, but that (a) is not robust, and (b) doesn't help with
459 * finding out the socket directory. And it wouldn't work anyway
462 * If we see less than 6 lines in postmaster.pid, just keep
468 /* Try to read the postmaster.pid file */
469 if ((optlines = readfile(pid_file)) != NULL &&
470 optlines[0] != NULL &&
471 optlines[1] != NULL &&
474 if (optlines[3] == NULL)
476 /* File is exactly three lines, must be pre-9.1 */
477 write_stderr(_("\n%s: -w option is not supported when starting a pre-9.1 server\n"),
479 return PQPING_NO_ATTEMPT;
481 else if (optlines[4] != NULL &&
484 /* File is complete enough for us, parse it */
489 * Make sanity checks. If it's for a standalone backend
490 * (negative PID), or the recorded start time is before
491 * pg_ctl started, then either we are looking at the wrong
492 * data directory, or this is a pre-existing pidfile that
493 * hasn't (yet?) been overwritten by our child postmaster.
494 * Allow 2 seconds slop for possible cross-process clock
497 pmpid = atol(optlines[LOCK_FILE_LINE_PID - 1]);
498 pmstart = atol(optlines[LOCK_FILE_LINE_START_TIME - 1]);
499 if (pmpid <= 0 || pmstart < start_time - 2)
502 * Set flag to report stale pidfile if it doesn't get
503 * overwritten before we give up waiting.
505 found_stale_pidfile = true;
510 * OK, seems to be a valid pidfile from our child.
515 char host_str[MAXPGPATH];
517 found_stale_pidfile = false;
518 pm_pid = (pgpid_t) pmpid;
521 * Extract port number and host string to use. Prefer
522 * using Unix socket if available.
524 portnum = atoi(optlines[LOCK_FILE_LINE_PORT - 1]);
525 sockdir = optlines[LOCK_FILE_LINE_SOCKET_DIR - 1];
526 hostaddr = optlines[LOCK_FILE_LINE_LISTEN_ADDR - 1];
529 * While unix_socket_directories can accept relative
530 * directories, libpq's host parameter must have a
531 * leading slash to indicate a socket directory. So,
532 * ignore sockdir if it's relative, and try to use TCP
535 if (sockdir[0] == '/')
536 strlcpy(host_str, sockdir, sizeof(host_str));
538 strlcpy(host_str, hostaddr, sizeof(host_str));
540 /* remove trailing newline */
541 if (strchr(host_str, '\n') != NULL)
542 *strchr(host_str, '\n') = '\0';
544 /* Fail if couldn't get either sockdir or host addr */
545 if (host_str[0] == '\0')
547 write_stderr(_("\n%s: -w option cannot use a relative socket directory specification\n"),
549 return PQPING_NO_ATTEMPT;
552 /* If postmaster is listening on "*", use localhost */
553 if (strcmp(host_str, "*") == 0)
554 strcpy(host_str, "localhost");
557 * We need to set connect_timeout otherwise on Windows
558 * the Service Control Manager (SCM) will probably
561 snprintf(connstr, sizeof(connstr),
562 "dbname=postgres port=%d host='%s' connect_timeout=5",
569 /* If we have a connection string, ping the server */
570 if (connstr[0] != '\0')
572 ret = PQping(connstr);
573 if (ret == PQPING_OK || ret == PQPING_NO_ATTEMPT)
578 * The postmaster should create postmaster.pid very soon after being
579 * started. If it's not there after we've waited 5 or more seconds,
580 * assume startup failed and give up waiting. (Note this covers both
581 * cases where the pidfile was never created, and where it was created
582 * and then removed during postmaster exit.) Also, if there *is* a
583 * file there but it appears stale, issue a suitable warning and give
590 if (stat(pid_file, &statbuf) != 0)
591 return PQPING_NO_RESPONSE;
593 if (found_stale_pidfile)
595 write_stderr(_("\n%s: this data directory appears to be running a pre-existing postmaster\n"),
597 return PQPING_NO_RESPONSE;
602 * If we've been able to identify the child postmaster's PID, check
603 * the process is still alive. This covers cases where the postmaster
604 * successfully created the pidfile but then crashed without removing
607 if (pm_pid > 0 && !postmaster_is_alive((pid_t) pm_pid))
608 return PQPING_NO_RESPONSE;
610 /* No response, or startup still in process; wait */
615 * Increment the wait hint by 6 secs (connection timeout + sleep)
616 * We must do this to indicate to the SCM that our startup time is
617 * changing, otherwise it'll usually send a stop signal after 20
618 * seconds, despite incrementing the checkpoint counter.
620 status.dwWaitHint += 6000;
621 status.dwCheckPoint++;
622 SetServiceStatus(hStatus, (LPSERVICE_STATUS) &status);
628 pg_usleep(1000000); /* 1 sec */
631 /* return result of last call to PQping */
636 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_CORE)
638 unlimit_core_size(void)
642 getrlimit(RLIMIT_CORE, &lim);
643 if (lim.rlim_max == 0)
645 write_stderr(_("%s: cannot set core file size limit; disallowed by hard limit\n"),
649 else if (lim.rlim_max == RLIM_INFINITY || lim.rlim_cur < lim.rlim_max)
651 lim.rlim_cur = lim.rlim_max;
652 setrlimit(RLIMIT_CORE, &lim);
660 if (post_opts == NULL)
662 post_opts = ""; /* default */
663 if (ctl_command == RESTART_COMMAND)
667 optlines = readfile(postopts_file);
668 if (optlines == NULL)
670 write_stderr(_("%s: could not read file \"%s\"\n"), progname, postopts_file);
673 else if (optlines[0] == NULL || optlines[1] != NULL)
675 write_stderr(_("%s: option file \"%s\" must have exactly one line\n"),
676 progname, postopts_file);
685 optline = optlines[0];
686 /* trim off line endings */
687 len = strcspn(optline, "\r\n");
691 * Are we at the first option, as defined by space and
694 if ((arg1 = strstr(optline, " \"")) != NULL)
696 *arg1 = '\0'; /* terminate so we get only program
698 post_opts = arg1 + 1; /* point past whitespace */
700 if (exec_path == NULL)
708 find_other_exec_or_die(const char *argv0, const char *target, const char *versionstr)
713 found_path = pg_malloc(MAXPGPATH);
715 if ((ret = find_other_exec(argv0, target, versionstr, found_path)) < 0)
717 char full_path[MAXPGPATH];
719 if (find_my_exec(argv0, full_path) < 0)
720 strlcpy(full_path, progname, sizeof(full_path));
723 write_stderr(_("The program \"%s\" is needed by %s "
724 "but was not found in the\n"
725 "same directory as \"%s\".\n"
726 "Check your installation.\n"),
727 target, progname, full_path);
729 write_stderr(_("The program \"%s\" was found by \"%s\"\n"
730 "but was not the same version as %s.\n"
731 "Check your installation.\n"),
732 target, full_path, progname);
744 if (exec_path == NULL)
745 exec_path = find_other_exec_or_die(argv0, "initdb", "initdb (PostgreSQL) " PG_VERSION "\n");
747 if (pgdata_opt == NULL)
750 if (post_opts == NULL)
754 snprintf(cmd, MAXPGPATH, SYSTEMQUOTE "\"%s\" %s%s" SYSTEMQUOTE,
755 exec_path, pgdata_opt, post_opts);
757 snprintf(cmd, MAXPGPATH, SYSTEMQUOTE "\"%s\" %s%s > \"%s\"" SYSTEMQUOTE,
758 exec_path, pgdata_opt, post_opts, DEVNULL);
760 if (system(cmd) != 0)
762 write_stderr(_("%s: database system initialization failed\n"), progname);
773 if (ctl_command != RESTART_COMMAND)
775 old_pid = get_pgpid();
777 write_stderr(_("%s: another server might be running; "
778 "trying to start server anyway\n"),
784 /* No -D or -D already added during server start */
785 if (ctl_command == RESTART_COMMAND || pgdata_opt == NULL)
788 if (exec_path == NULL)
789 exec_path = find_other_exec_or_die(argv0, "postgres", PG_BACKEND_VERSIONSTR);
791 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_CORE)
792 if (allow_core_files)
797 * If possible, tell the postmaster our parent shell's PID (see the
798 * comments in CreateLockFile() for motivation). Windows hasn't got
799 * getppid() unfortunately.
803 static char env_var[32];
805 snprintf(env_var, sizeof(env_var), "PG_GRANDPARENT_PID=%d",
811 exitcode = start_postmaster();
814 write_stderr(_("%s: could not start server: exit code was %d\n"),
821 print_msg(_("waiting for server to start..."));
823 switch (test_postmaster_connection(false))
826 print_msg(_(" done\n"));
827 print_msg(_("server started\n"));
830 print_msg(_(" stopped waiting\n"));
831 print_msg(_("server is still starting up\n"));
833 case PQPING_NO_RESPONSE:
834 print_msg(_(" stopped waiting\n"));
835 write_stderr(_("%s: could not start server\n"
836 "Examine the log output.\n"),
840 case PQPING_NO_ATTEMPT:
841 print_msg(_(" failed\n"));
842 write_stderr(_("%s: could not wait for server because of misconfiguration\n"),
848 print_msg(_("server starting\n"));
861 if (pid == 0) /* no pid file */
863 write_stderr(_("%s: PID file \"%s\" does not exist\n"), progname, pid_file);
864 write_stderr(_("Is server running?\n"));
867 else if (pid < 0) /* standalone backend, not postmaster */
870 write_stderr(_("%s: cannot stop server; "
871 "single-user server is running (PID: %ld)\n"),
876 if (kill((pid_t) pid, sig) != 0)
878 write_stderr(_("%s: could not send stop signal (PID: %ld): %s\n"), progname, pid,
885 print_msg(_("server shutting down\n"));
891 * If backup_label exists, an online backup is running. Warn the user
892 * that smart shutdown will wait for it to finish. However, if
893 * recovery.conf is also present, we're recovering from an online
894 * backup instead of performing one.
896 if (shutdown_mode == SMART_MODE &&
897 stat(backup_file, &statbuf) == 0 &&
898 stat(recovery_file, &statbuf) != 0)
900 print_msg(_("WARNING: online backup mode is active\n"
901 "Shutdown will not complete until pg_stop_backup() is called.\n\n"));
904 print_msg(_("waiting for server to shut down..."));
906 for (cnt = 0; cnt < wait_seconds; cnt++)
908 if ((pid = get_pgpid()) != 0)
911 pg_usleep(1000000); /* 1 sec */
917 if (pid != 0) /* pid file still exists */
919 print_msg(_(" failed\n"));
921 write_stderr(_("%s: server does not shut down\n"), progname);
922 if (shutdown_mode == SMART_MODE)
923 write_stderr(_("HINT: The \"-m fast\" option immediately disconnects sessions rather than\n"
924 "waiting for session-initiated disconnection.\n"));
927 print_msg(_(" done\n"));
929 print_msg(_("server stopped\n"));
935 * restart/reload routines
947 if (pid == 0) /* no pid file */
949 write_stderr(_("%s: PID file \"%s\" does not exist\n"),
951 write_stderr(_("Is server running?\n"));
952 write_stderr(_("starting server anyway\n"));
956 else if (pid < 0) /* standalone backend, not postmaster */
959 if (postmaster_is_alive((pid_t) pid))
961 write_stderr(_("%s: cannot restart server; "
962 "single-user server is running (PID: %ld)\n"),
964 write_stderr(_("Please terminate the single-user server and try again.\n"));
969 if (postmaster_is_alive((pid_t) pid))
971 if (kill((pid_t) pid, sig) != 0)
973 write_stderr(_("%s: could not send stop signal (PID: %ld): %s\n"), progname, pid,
979 * If backup_label exists, an online backup is running. Warn the user
980 * that smart shutdown will wait for it to finish. However, if
981 * recovery.conf is also present, we're recovering from an online
982 * backup instead of performing one.
984 if (shutdown_mode == SMART_MODE &&
985 stat(backup_file, &statbuf) == 0 &&
986 stat(recovery_file, &statbuf) != 0)
988 print_msg(_("WARNING: online backup mode is active\n"
989 "Shutdown will not complete until pg_stop_backup() is called.\n\n"));
992 print_msg(_("waiting for server to shut down..."));
994 /* always wait for restart */
996 for (cnt = 0; cnt < wait_seconds; cnt++)
998 if ((pid = get_pgpid()) != 0)
1001 pg_usleep(1000000); /* 1 sec */
1007 if (pid != 0) /* pid file still exists */
1009 print_msg(_(" failed\n"));
1011 write_stderr(_("%s: server does not shut down\n"), progname);
1012 if (shutdown_mode == SMART_MODE)
1013 write_stderr(_("HINT: The \"-m fast\" option immediately disconnects sessions rather than\n"
1014 "waiting for session-initiated disconnection.\n"));
1018 print_msg(_(" done\n"));
1019 print_msg(_("server stopped\n"));
1023 write_stderr(_("%s: old server process (PID: %ld) seems to be gone\n"),
1025 write_stderr(_("starting server anyway\n"));
1037 if (pid == 0) /* no pid file */
1039 write_stderr(_("%s: PID file \"%s\" does not exist\n"), progname, pid_file);
1040 write_stderr(_("Is server running?\n"));
1043 else if (pid < 0) /* standalone backend, not postmaster */
1046 write_stderr(_("%s: cannot reload server; "
1047 "single-user server is running (PID: %ld)\n"),
1049 write_stderr(_("Please terminate the single-user server and try again.\n"));
1053 if (kill((pid_t) pid, sig) != 0)
1055 write_stderr(_("%s: could not send reload signal (PID: %ld): %s\n"),
1056 progname, pid, strerror(errno));
1060 print_msg(_("server signaled\n"));
1073 struct stat statbuf;
1077 if (pid == 0) /* no pid file */
1079 write_stderr(_("%s: PID file \"%s\" does not exist\n"), progname, pid_file);
1080 write_stderr(_("Is server running?\n"));
1083 else if (pid < 0) /* standalone backend, not postmaster */
1086 write_stderr(_("%s: cannot promote server; "
1087 "single-user server is running (PID: %ld)\n"),
1092 /* If recovery.conf doesn't exist, the server is not in standby mode */
1093 if (stat(recovery_file, &statbuf) != 0)
1095 write_stderr(_("%s: cannot promote server; "
1096 "server is not in standby mode\n"),
1102 * For 9.3 onwards, "fast" promotion is performed. Promotion
1103 * with a full checkpoint is still possible by writing a file called
1104 * "fallback_promote" instead of "promote"
1106 snprintf(promote_file, MAXPGPATH, "%s/promote", pg_data);
1108 if ((prmfile = fopen(promote_file, "w")) == NULL)
1110 write_stderr(_("%s: could not create promote signal file \"%s\": %s\n"),
1111 progname, promote_file, strerror(errno));
1114 if (fclose(prmfile))
1116 write_stderr(_("%s: could not write promote signal file \"%s\": %s\n"),
1117 progname, promote_file, strerror(errno));
1122 if (kill((pid_t) pid, sig) != 0)
1124 write_stderr(_("%s: could not send promote signal (PID: %ld): %s\n"),
1125 progname, pid, strerror(errno));
1126 if (unlink(promote_file) != 0)
1127 write_stderr(_("%s: could not remove promote signal file \"%s\": %s\n"),
1128 progname, promote_file, strerror(errno));
1132 print_msg(_("server promoting\n"));
1141 postmaster_is_alive(pid_t pid)
1144 * Test to see if the process is still there. Note that we do not
1145 * consider an EPERM failure to mean that the process is still there;
1146 * EPERM must mean that the given PID belongs to some other userid, and
1147 * considering the permissions on $PGDATA, that means it's not the
1148 * postmaster we are after.
1150 * Don't believe that our own PID or parent shell's PID is the postmaster,
1151 * either. (Windows hasn't got getppid(), though.)
1153 if (pid == getpid())
1156 if (pid == getppid())
1159 if (kill(pid, 0) == 0)
1170 /* Is there a pid file? */
1173 /* standalone backend? */
1177 if (postmaster_is_alive((pid_t) pid))
1179 printf(_("%s: single-user server is running (PID: %ld)\n"),
1185 /* must be a postmaster */
1187 if (postmaster_is_alive((pid_t) pid))
1191 printf(_("%s: server is running (PID: %ld)\n"),
1194 optlines = readfile(postopts_file);
1195 if (optlines != NULL)
1196 for (; *optlines != NULL; optlines++)
1197 fputs(*optlines, stdout);
1202 printf(_("%s: no server running\n"), progname);
1205 * The Linux Standard Base Core Specification 3.1 says this should return
1207 * https://refspecs.linuxbase.org/LSB_3.1.0/LSB-Core-generic/LSB-Core-generic/iniscrptact.html
1215 do_kill(pgpid_t pid)
1217 if (kill((pid_t) pid, sig) != 0)
1219 write_stderr(_("%s: could not send signal %d (PID: %ld): %s\n"),
1220 progname, sig, pid, strerror(errno));
1225 #if defined(WIN32) || defined(__CYGWIN__)
1228 pgwin32_IsInstalled(SC_HANDLE hSCM)
1230 SC_HANDLE hService = OpenService(hSCM, register_servicename, SERVICE_QUERY_CONFIG);
1231 bool bResult = (hService != NULL);
1234 CloseServiceHandle(hService);
1239 pgwin32_CommandLine(bool registration)
1241 static char cmdLine[MAXPGPATH];
1245 char buf[MAXPGPATH];
1250 ret = find_my_exec(argv0, cmdLine);
1253 write_stderr(_("%s: could not find own program executable\n"), progname);
1259 ret = find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
1263 write_stderr(_("%s: could not find postgres program executable\n"), progname);
1269 /* need to convert to windows path */
1270 #if CYGWIN_VERSION_DLL_MAJOR >= 1007
1271 cygwin_conv_path(CCP_POSIX_TO_WIN_A, cmdLine, buf, sizeof(buf));
1273 cygwin_conv_to_full_win32_path(cmdLine, buf);
1275 strcpy(cmdLine, buf);
1280 if (pg_strcasecmp(cmdLine + strlen(cmdLine) - 4, ".exe") != 0)
1282 /* If commandline does not end in .exe, append it */
1283 strcat(cmdLine, ".exe");
1285 strcat(cmdLine, " runservice -N \"");
1286 strcat(cmdLine, register_servicename);
1287 strcat(cmdLine, "\"");
1292 strcat(cmdLine, " -D \"");
1293 strcat(cmdLine, pg_config);
1294 strcat(cmdLine, "\"");
1297 if (registration && do_wait)
1298 strcat(cmdLine, " -w");
1300 if (registration && wait_seconds != DEFAULT_WAIT)
1302 sprintf(cmdLine + strlen(cmdLine), " -t %d", wait_seconds);
1304 if (registration && silent_mode)
1305 strcat(cmdLine, " -s");
1309 strcat(cmdLine, " ");
1311 strcat(cmdLine, " -o \"");
1312 strcat(cmdLine, post_opts);
1314 strcat(cmdLine, "\"");
1321 pgwin32_doRegister(void)
1324 SC_HANDLE hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
1328 write_stderr(_("%s: could not open service manager\n"), progname);
1331 if (pgwin32_IsInstalled(hSCM))
1333 CloseServiceHandle(hSCM);
1334 write_stderr(_("%s: service \"%s\" already registered\n"), progname, register_servicename);
1338 if ((hService = CreateService(hSCM, register_servicename, register_servicename,
1339 SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
1340 pgctl_start_type, SERVICE_ERROR_NORMAL,
1341 pgwin32_CommandLine(true),
1342 NULL, NULL, "RPCSS\0", register_username, register_password)) == NULL)
1344 CloseServiceHandle(hSCM);
1345 write_stderr(_("%s: could not register service \"%s\": error code %lu\n"), progname, register_servicename, GetLastError());
1348 CloseServiceHandle(hService);
1349 CloseServiceHandle(hSCM);
1353 pgwin32_doUnregister(void)
1356 SC_HANDLE hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
1360 write_stderr(_("%s: could not open service manager\n"), progname);
1363 if (!pgwin32_IsInstalled(hSCM))
1365 CloseServiceHandle(hSCM);
1366 write_stderr(_("%s: service \"%s\" not registered\n"), progname, register_servicename);
1370 if ((hService = OpenService(hSCM, register_servicename, DELETE)) == NULL)
1372 CloseServiceHandle(hSCM);
1373 write_stderr(_("%s: could not open service \"%s\": error code %lu\n"), progname, register_servicename, GetLastError());
1376 if (!DeleteService(hService))
1378 CloseServiceHandle(hService);
1379 CloseServiceHandle(hSCM);
1380 write_stderr(_("%s: could not unregister service \"%s\": error code %lu\n"), progname, register_servicename, GetLastError());
1383 CloseServiceHandle(hService);
1384 CloseServiceHandle(hSCM);
1388 pgwin32_SetServiceStatus(DWORD currentState)
1390 status.dwCurrentState = currentState;
1391 SetServiceStatus(hStatus, (LPSERVICE_STATUS) &status);
1395 pgwin32_ServiceHandler(DWORD request)
1399 case SERVICE_CONTROL_STOP:
1400 case SERVICE_CONTROL_SHUTDOWN:
1403 * We only need a short wait hint here as it just needs to wait
1404 * for the next checkpoint. They occur every 5 seconds during
1407 status.dwWaitHint = 10000;
1408 pgwin32_SetServiceStatus(SERVICE_STOP_PENDING);
1409 SetEvent(shutdownEvent);
1412 case SERVICE_CONTROL_PAUSE:
1413 /* Win32 config reloading */
1414 status.dwWaitHint = 5000;
1415 kill(postmasterPID, SIGHUP);
1418 /* FIXME: These could be used to replace other signals etc */
1419 case SERVICE_CONTROL_CONTINUE:
1420 case SERVICE_CONTROL_INTERROGATE:
1427 pgwin32_ServiceMain(DWORD argc, LPTSTR *argv)
1429 PROCESS_INFORMATION pi;
1432 /* Initialize variables */
1433 status.dwWin32ExitCode = S_OK;
1434 status.dwCheckPoint = 0;
1435 status.dwWaitHint = 60000;
1436 status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
1437 status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_PAUSE_CONTINUE;
1438 status.dwServiceSpecificExitCode = 0;
1439 status.dwCurrentState = SERVICE_START_PENDING;
1441 memset(&pi, 0, sizeof(pi));
1445 /* Register the control request handler */
1446 if ((hStatus = RegisterServiceCtrlHandler(register_servicename, pgwin32_ServiceHandler)) == (SERVICE_STATUS_HANDLE) 0)
1449 if ((shutdownEvent = CreateEvent(NULL, true, false, NULL)) == NULL)
1452 /* Start the postmaster */
1453 pgwin32_SetServiceStatus(SERVICE_START_PENDING);
1454 if (!CreateRestrictedProcess(pgwin32_CommandLine(false), &pi, true))
1456 pgwin32_SetServiceStatus(SERVICE_STOPPED);
1459 postmasterPID = pi.dwProcessId;
1460 postmasterProcess = pi.hProcess;
1461 CloseHandle(pi.hThread);
1465 write_eventlog(EVENTLOG_INFORMATION_TYPE, _("Waiting for server startup...\n"));
1466 if (test_postmaster_connection(true) != PQPING_OK)
1468 write_eventlog(EVENTLOG_ERROR_TYPE, _("Timed out waiting for server startup\n"));
1469 pgwin32_SetServiceStatus(SERVICE_STOPPED);
1472 write_eventlog(EVENTLOG_INFORMATION_TYPE, _("Server started and accepting connections\n"));
1475 pgwin32_SetServiceStatus(SERVICE_RUNNING);
1477 /* Wait for quit... */
1478 ret = WaitForMultipleObjects(2, shutdownHandles, FALSE, INFINITE);
1480 pgwin32_SetServiceStatus(SERVICE_STOP_PENDING);
1483 case WAIT_OBJECT_0: /* shutdown event */
1484 kill(postmasterPID, SIGINT);
1487 * Increment the checkpoint and try again Abort after 12
1488 * checkpoints as the postmaster has probably hung
1490 while (WaitForSingleObject(postmasterProcess, 5000) == WAIT_TIMEOUT && status.dwCheckPoint < 12)
1491 status.dwCheckPoint++;
1494 case (WAIT_OBJECT_0 + 1): /* postmaster went down */
1498 /* shouldn't get here? */
1502 CloseHandle(shutdownEvent);
1503 CloseHandle(postmasterProcess);
1505 pgwin32_SetServiceStatus(SERVICE_STOPPED);
1509 pgwin32_doRunAsService(void)
1511 SERVICE_TABLE_ENTRY st[] = {{register_servicename, pgwin32_ServiceMain},
1514 if (StartServiceCtrlDispatcher(st) == 0)
1516 write_stderr(_("%s: could not start service \"%s\": error code %lu\n"), progname, register_servicename, GetLastError());
1523 * Mingw headers are incomplete, and so are the libraries. So we have to load
1524 * a whole lot of API functions dynamically. Since we have to do this anyway,
1525 * also load the couple of functions that *do* exist in minwg headers but not
1526 * on NT4. That way, we don't break on NT4.
1528 typedef BOOL (WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE);
1529 typedef BOOL (WINAPI * __IsProcessInJob) (HANDLE, HANDLE, PBOOL);
1530 typedef HANDLE (WINAPI * __CreateJobObject) (LPSECURITY_ATTRIBUTES, LPCTSTR);
1531 typedef BOOL (WINAPI * __SetInformationJobObject) (HANDLE, JOBOBJECTINFOCLASS, LPVOID, DWORD);
1532 typedef BOOL (WINAPI * __AssignProcessToJobObject) (HANDLE, HANDLE);
1533 typedef BOOL (WINAPI * __QueryInformationJobObject) (HANDLE, JOBOBJECTINFOCLASS, LPVOID, DWORD, LPDWORD);
1535 /* Windows API define missing from some versions of MingW headers */
1536 #ifndef DISABLE_MAX_PRIVILEGE
1537 #define DISABLE_MAX_PRIVILEGE 0x1
1541 * Create a restricted token, a job object sandbox, and execute the specified
1544 * Returns 0 on success, non-zero on failure, same as CreateProcess().
1546 * On NT4, or any other system not containing the required functions, will
1547 * launch the process under the current token without doing any modifications.
1549 * NOTE! Job object will only work when running as a service, because it's
1550 * automatically destroyed when pg_ctl exits.
1553 CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, bool as_service)
1559 HANDLE restrictedToken;
1560 SID_IDENTIFIER_AUTHORITY NtAuthority = {SECURITY_NT_AUTHORITY};
1561 SID_AND_ATTRIBUTES dropSids[2];
1563 /* Functions loaded dynamically */
1564 __CreateRestrictedToken _CreateRestrictedToken = NULL;
1565 __IsProcessInJob _IsProcessInJob = NULL;
1566 __CreateJobObject _CreateJobObject = NULL;
1567 __SetInformationJobObject _SetInformationJobObject = NULL;
1568 __AssignProcessToJobObject _AssignProcessToJobObject = NULL;
1569 __QueryInformationJobObject _QueryInformationJobObject = NULL;
1570 HANDLE Kernel32Handle;
1571 HANDLE Advapi32Handle;
1573 ZeroMemory(&si, sizeof(si));
1576 Advapi32Handle = LoadLibrary("ADVAPI32.DLL");
1577 if (Advapi32Handle != NULL)
1579 _CreateRestrictedToken = (__CreateRestrictedToken) GetProcAddress(Advapi32Handle, "CreateRestrictedToken");
1582 if (_CreateRestrictedToken == NULL)
1585 * NT4 doesn't have CreateRestrictedToken, so just call ordinary
1588 write_stderr(_("%s: WARNING: cannot create restricted tokens on this platform\n"), progname);
1589 if (Advapi32Handle != NULL)
1590 FreeLibrary(Advapi32Handle);
1591 return CreateProcess(NULL, cmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, processInfo);
1594 /* Open the current token to use as a base for the restricted one */
1595 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken))
1597 write_stderr(_("%s: could not open process token: error code %lu\n"), progname, GetLastError());
1601 /* Allocate list of SIDs to remove */
1602 ZeroMemory(&dropSids, sizeof(dropSids));
1603 if (!AllocateAndInitializeSid(&NtAuthority, 2,
1604 SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0,
1605 0, &dropSids[0].Sid) ||
1606 !AllocateAndInitializeSid(&NtAuthority, 2,
1607 SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0,
1608 0, &dropSids[1].Sid))
1610 write_stderr(_("%s: could not allocate SIDs: error code %lu\n"), progname, GetLastError());
1614 b = _CreateRestrictedToken(origToken,
1615 DISABLE_MAX_PRIVILEGE,
1616 sizeof(dropSids) / sizeof(dropSids[0]),
1622 FreeSid(dropSids[1].Sid);
1623 FreeSid(dropSids[0].Sid);
1624 CloseHandle(origToken);
1625 FreeLibrary(Advapi32Handle);
1629 write_stderr(_("%s: could not create restricted token: error code %lu\n"), progname, GetLastError());
1634 AddUserToTokenDacl(restrictedToken);
1637 r = CreateProcessAsUser(restrictedToken, NULL, cmd, NULL, NULL, TRUE, CREATE_SUSPENDED, NULL, NULL, &si, processInfo);
1639 Kernel32Handle = LoadLibrary("KERNEL32.DLL");
1640 if (Kernel32Handle != NULL)
1642 _IsProcessInJob = (__IsProcessInJob) GetProcAddress(Kernel32Handle, "IsProcessInJob");
1643 _CreateJobObject = (__CreateJobObject) GetProcAddress(Kernel32Handle, "CreateJobObjectA");
1644 _SetInformationJobObject = (__SetInformationJobObject) GetProcAddress(Kernel32Handle, "SetInformationJobObject");
1645 _AssignProcessToJobObject = (__AssignProcessToJobObject) GetProcAddress(Kernel32Handle, "AssignProcessToJobObject");
1646 _QueryInformationJobObject = (__QueryInformationJobObject) GetProcAddress(Kernel32Handle, "QueryInformationJobObject");
1649 /* Verify that we found all functions */
1650 if (_IsProcessInJob == NULL || _CreateJobObject == NULL || _SetInformationJobObject == NULL || _AssignProcessToJobObject == NULL || _QueryInformationJobObject == NULL)
1653 * IsProcessInJob() is not available on < WinXP, so there is no need
1654 * to log the error every time in that case
1658 osv.dwOSVersionInfoSize = sizeof(osv);
1659 if (!GetVersionEx(&osv) || /* could not get version */
1660 (osv.dwMajorVersion == 5 && osv.dwMinorVersion > 0) || /* 5.1=xp, 5.2=2003, etc */
1661 osv.dwMajorVersion > 5) /* anything newer should have the API */
1664 * Log error if we can't get version, or if we're on WinXP/2003 or
1667 write_stderr(_("%s: WARNING: could not locate all job object functions in system API\n"), progname);
1673 if (_IsProcessInJob(processInfo->hProcess, NULL, &inJob))
1678 * Job objects are working, and the new process isn't in one,
1679 * so we can create one safely. If any problems show up when
1680 * setting it, we're going to ignore them.
1685 sprintf(jobname, "PostgreSQL_%lu", processInfo->dwProcessId);
1687 job = _CreateJobObject(NULL, jobname);
1690 JOBOBJECT_BASIC_LIMIT_INFORMATION basicLimit;
1691 JOBOBJECT_BASIC_UI_RESTRICTIONS uiRestrictions;
1692 JOBOBJECT_SECURITY_LIMIT_INFORMATION securityLimit;
1695 ZeroMemory(&basicLimit, sizeof(basicLimit));
1696 ZeroMemory(&uiRestrictions, sizeof(uiRestrictions));
1697 ZeroMemory(&securityLimit, sizeof(securityLimit));
1699 basicLimit.LimitFlags = JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION | JOB_OBJECT_LIMIT_PRIORITY_CLASS;
1700 basicLimit.PriorityClass = NORMAL_PRIORITY_CLASS;
1701 _SetInformationJobObject(job, JobObjectBasicLimitInformation, &basicLimit, sizeof(basicLimit));
1703 uiRestrictions.UIRestrictionsClass = JOB_OBJECT_UILIMIT_DESKTOP | JOB_OBJECT_UILIMIT_DISPLAYSETTINGS |
1704 JOB_OBJECT_UILIMIT_EXITWINDOWS | JOB_OBJECT_UILIMIT_READCLIPBOARD |
1705 JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS | JOB_OBJECT_UILIMIT_WRITECLIPBOARD;
1709 osv.dwOSVersionInfoSize = sizeof(osv);
1710 if (!GetVersionEx(&osv) ||
1711 osv.dwMajorVersion < 6 ||
1712 (osv.dwMajorVersion == 6 && osv.dwMinorVersion == 0))
1715 * On Windows 7 (and presumably later),
1716 * JOB_OBJECT_UILIMIT_HANDLES prevents us from
1717 * starting as a service. So we only enable it on
1718 * Vista and earlier (version <= 6.0)
1720 uiRestrictions.UIRestrictionsClass |= JOB_OBJECT_UILIMIT_HANDLES;
1723 _SetInformationJobObject(job, JobObjectBasicUIRestrictions, &uiRestrictions, sizeof(uiRestrictions));
1725 securityLimit.SecurityLimitFlags = JOB_OBJECT_SECURITY_NO_ADMIN | JOB_OBJECT_SECURITY_ONLY_TOKEN;
1726 securityLimit.JobToken = restrictedToken;
1727 _SetInformationJobObject(job, JobObjectSecurityLimitInformation, &securityLimit, sizeof(securityLimit));
1729 _AssignProcessToJobObject(job, processInfo->hProcess);
1736 CloseHandle(restrictedToken);
1738 ResumeThread(processInfo->hThread);
1740 FreeLibrary(Kernel32Handle);
1743 * We intentionally don't close the job object handle, because we want the
1744 * object to live on until pg_ctl shuts down.
1753 write_stderr(_("Try \"%s --help\" for more information.\n"), progname);
1761 printf(_("%s is a utility to initialize, start, stop, or control a PostgreSQL server.\n\n"), progname);
1762 printf(_("Usage:\n"));
1763 printf(_(" %s init[db] [-D DATADIR] [-s] [-o \"OPTIONS\"]\n"), progname);
1764 printf(_(" %s start [-w] [-t SECS] [-D DATADIR] [-s] [-l FILENAME] [-o \"OPTIONS\"]\n"), progname);
1765 printf(_(" %s stop [-W] [-t SECS] [-D DATADIR] [-s] [-m SHUTDOWN-MODE]\n"), progname);
1766 printf(_(" %s restart [-w] [-t SECS] [-D DATADIR] [-s] [-m SHUTDOWN-MODE]\n"
1767 " [-o \"OPTIONS\"]\n"), progname);
1768 printf(_(" %s reload [-D DATADIR] [-s]\n"), progname);
1769 printf(_(" %s status [-D DATADIR]\n"), progname);
1770 printf(_(" %s promote [-D DATADIR] [-s]\n"), progname);
1771 printf(_(" %s kill SIGNALNAME PID\n"), progname);
1772 #if defined(WIN32) || defined(__CYGWIN__)
1773 printf(_(" %s register [-N SERVICENAME] [-U USERNAME] [-P PASSWORD] [-D DATADIR]\n"
1774 " [-S START-TYPE] [-w] [-t SECS] [-o \"OPTIONS\"]\n"), progname);
1775 printf(_(" %s unregister [-N SERVICENAME]\n"), progname);
1778 printf(_("\nCommon options:\n"));
1779 printf(_(" -D, --pgdata=DATADIR location of the database storage area\n"));
1780 printf(_(" -s, --silent only print errors, no informational messages\n"));
1781 printf(_(" -t, --timeout=SECS seconds to wait when using -w option\n"));
1782 printf(_(" -V, --version output version information, then exit\n"));
1783 printf(_(" -w wait until operation completes\n"));
1784 printf(_(" -W do not wait until operation completes\n"));
1785 printf(_(" -?, --help show this help, then exit\n"));
1786 printf(_("(The default is to wait for shutdown, but not for start or restart.)\n\n"));
1787 printf(_("If the -D option is omitted, the environment variable PGDATA is used.\n"));
1789 printf(_("\nOptions for start or restart:\n"));
1790 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_CORE)
1791 printf(_(" -c, --core-files allow postgres to produce core files\n"));
1793 printf(_(" -c, --core-files not applicable on this platform\n"));
1795 printf(_(" -l, --log=FILENAME write (or append) server log to FILENAME\n"));
1796 printf(_(" -o OPTIONS command line options to pass to postgres\n"
1797 " (PostgreSQL server executable) or initdb\n"));
1798 printf(_(" -p PATH-TO-POSTGRES normally not necessary\n"));
1799 printf(_("\nOptions for stop, restart, or promote:\n"));
1800 printf(_(" -m, --mode=MODE MODE can be \"smart\", \"fast\", or \"immediate\"\n"));
1802 printf(_("\nShutdown modes are:\n"));
1803 printf(_(" smart quit after all clients have disconnected\n"));
1804 printf(_(" fast quit directly, with proper shutdown\n"));
1805 printf(_(" immediate quit without complete shutdown; will lead to recovery on restart\n"));
1807 printf(_("\nAllowed signal names for kill:\n"));
1808 printf(" ABRT HUP INT QUIT TERM USR1 USR2\n");
1810 #if defined(WIN32) || defined(__CYGWIN__)
1811 printf(_("\nOptions for register and unregister:\n"));
1812 printf(_(" -N SERVICENAME service name with which to register PostgreSQL server\n"));
1813 printf(_(" -P PASSWORD password of account to register PostgreSQL server\n"));
1814 printf(_(" -U USERNAME user name of account to register PostgreSQL server\n"));
1815 printf(_(" -S START-TYPE service start type to register PostgreSQL server\n"));
1817 printf(_("\nStart types are:\n"));
1818 printf(_(" auto start service automatically during system startup (default)\n"));
1819 printf(_(" demand start service on demand\n"));
1822 printf(_("\nReport bugs to <pgsql-bugs@postgresql.org>.\n"));
1828 set_mode(char *modeopt)
1830 if (strcmp(modeopt, "s") == 0 || strcmp(modeopt, "smart") == 0)
1832 shutdown_mode = SMART_MODE;
1835 else if (strcmp(modeopt, "f") == 0 || strcmp(modeopt, "fast") == 0)
1837 shutdown_mode = FAST_MODE;
1840 else if (strcmp(modeopt, "i") == 0 || strcmp(modeopt, "immediate") == 0)
1842 shutdown_mode = IMMEDIATE_MODE;
1847 write_stderr(_("%s: unrecognized shutdown mode \"%s\"\n"), progname, modeopt);
1856 set_sig(char *signame)
1858 if (strcmp(signame, "HUP") == 0)
1860 else if (strcmp(signame, "INT") == 0)
1862 else if (strcmp(signame, "QUIT") == 0)
1864 else if (strcmp(signame, "ABRT") == 0)
1867 /* probably should NOT provide SIGKILL */
1868 else if (strcmp(signame, "KILL") == 0)
1871 else if (strcmp(signame, "TERM") == 0)
1873 else if (strcmp(signame, "USR1") == 0)
1875 else if (strcmp(signame, "USR2") == 0)
1879 write_stderr(_("%s: unrecognized signal name \"%s\"\n"), progname, signame);
1886 #if defined(WIN32) || defined(__CYGWIN__)
1888 set_starttype(char *starttypeopt)
1890 if (strcmp(starttypeopt, "a") == 0 || strcmp(starttypeopt, "auto") == 0)
1891 pgctl_start_type = SERVICE_AUTO_START;
1892 else if (strcmp(starttypeopt, "d") == 0 || strcmp(starttypeopt, "demand") == 0)
1893 pgctl_start_type = SERVICE_DEMAND_START;
1896 write_stderr(_("%s: unrecognized start type \"%s\"\n"), progname, starttypeopt);
1906 * If a configuration-only directory was specified, find the real data dir.
1909 adjust_data_dir(void)
1911 char cmd[MAXPGPATH],
1912 filename[MAXPGPATH],
1916 /* do nothing if we're working without knowledge of data dir */
1917 if (pg_config == NULL)
1920 /* If there is no postgresql.conf, it can't be a config-only dir */
1921 snprintf(filename, sizeof(filename), "%s/postgresql.conf", pg_config);
1922 if ((fd = fopen(filename, "r")) == NULL)
1926 /* If PG_VERSION exists, it can't be a config-only dir */
1927 snprintf(filename, sizeof(filename), "%s/PG_VERSION", pg_config);
1928 if ((fd = fopen(filename, "r")) != NULL)
1934 /* Must be a configuration directory, so find the data directory */
1936 /* we use a private my_exec_path to avoid interfering with later uses */
1937 if (exec_path == NULL)
1938 my_exec_path = find_other_exec_or_die(argv0, "postgres", PG_BACKEND_VERSIONSTR);
1940 my_exec_path = pg_strdup(exec_path);
1942 snprintf(cmd, MAXPGPATH, SYSTEMQUOTE "\"%s\" %s%s -C data_directory" SYSTEMQUOTE,
1943 my_exec_path, pgdata_opt ? pgdata_opt : "", post_opts ?
1946 fd = popen(cmd, "r");
1947 if (fd == NULL || fgets(filename, sizeof(filename), fd) == NULL)
1949 write_stderr(_("%s: could not determine the data directory using command \"%s\"\n"), progname, cmd);
1955 /* Remove trailing newline */
1956 if (strchr(filename, '\n') != NULL)
1957 *strchr(filename, '\n') = '\0';
1960 pg_data = pg_strdup(filename);
1961 canonicalize_path(pg_data);
1966 main(int argc, char **argv)
1968 static struct option long_options[] = {
1969 {"help", no_argument, NULL, '?'},
1970 {"version", no_argument, NULL, 'V'},
1971 {"log", required_argument, NULL, 'l'},
1972 {"mode", required_argument, NULL, 'm'},
1973 {"pgdata", required_argument, NULL, 'D'},
1974 {"silent", no_argument, NULL, 's'},
1975 {"timeout", required_argument, NULL, 't'},
1976 {"core-files", no_argument, NULL, 'c'},
1982 pgpid_t killproc = 0;
1984 #if defined(WIN32) || defined(__CYGWIN__)
1985 setvbuf(stderr, NULL, _IONBF, 0);
1988 progname = get_progname(argv[0]);
1989 set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_ctl"));
1990 start_time = time(NULL);
1993 * save argv[0] so do_start() can look for the postmaster if necessary. we
1994 * don't look for postmaster here because in many cases we won't need it.
1998 umask(S_IRWXG | S_IRWXO);
2000 /* support --help and --version even if invoked as root */
2003 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
2008 else if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
2010 puts("pg_ctl (PostgreSQL) " PG_VERSION);
2016 * Disallow running as root, to forestall any possible security holes.
2021 write_stderr(_("%s: cannot be run as root\n"
2022 "Please log in (using, e.g., \"su\") as the "
2023 "(unprivileged) user that will\n"
2024 "own the server process.\n"),
2031 * 'Action' can be before or after args so loop over both. Some
2032 * getopt_long() implementations will reorder argv[] to place all flags
2033 * first (GNU?), but we don't rely on it. Our /port version doesn't do
2038 /* process command-line options */
2039 while (optind < argc)
2041 while ((c = getopt_long(argc, argv, "cD:l:m:N:o:p:P:sS:t:U:wW", long_options, &option_index)) != -1)
2050 pgdata_D = pg_strdup(optarg);
2051 canonicalize_path(pgdata_D);
2052 env_var = psprintf("PGDATA=%s", pgdata_D);
2056 * We could pass PGDATA just in an environment
2057 * variable but we do -D too for clearer postmaster
2060 pgdata_opt = psprintf("-D \"%s\" ", pgdata_D);
2064 log_file = pg_strdup(optarg);
2070 register_servicename = pg_strdup(optarg);
2073 post_opts = pg_strdup(optarg);
2076 exec_path = pg_strdup(optarg);
2079 register_password = pg_strdup(optarg);
2085 #if defined(WIN32) || defined(__CYGWIN__)
2086 set_starttype(optarg);
2088 write_stderr(_("%s: -S option not supported on this platform\n"),
2094 wait_seconds = atoi(optarg);
2097 if (strchr(optarg, '\\'))
2098 register_username = pg_strdup(optarg);
2100 /* Prepend .\ for local accounts */
2101 register_username = psprintf(".\\%s", optarg);
2112 allow_core_files = true;
2115 /* getopt_long already issued a suitable error message */
2121 /* Process an action */
2124 if (ctl_command != NO_COMMAND)
2126 write_stderr(_("%s: too many command-line arguments (first is \"%s\")\n"), progname, argv[optind]);
2131 if (strcmp(argv[optind], "init") == 0
2132 || strcmp(argv[optind], "initdb") == 0)
2133 ctl_command = INIT_COMMAND;
2134 else if (strcmp(argv[optind], "start") == 0)
2135 ctl_command = START_COMMAND;
2136 else if (strcmp(argv[optind], "stop") == 0)
2137 ctl_command = STOP_COMMAND;
2138 else if (strcmp(argv[optind], "restart") == 0)
2139 ctl_command = RESTART_COMMAND;
2140 else if (strcmp(argv[optind], "reload") == 0)
2141 ctl_command = RELOAD_COMMAND;
2142 else if (strcmp(argv[optind], "status") == 0)
2143 ctl_command = STATUS_COMMAND;
2144 else if (strcmp(argv[optind], "promote") == 0)
2145 ctl_command = PROMOTE_COMMAND;
2146 else if (strcmp(argv[optind], "kill") == 0)
2148 if (argc - optind < 3)
2150 write_stderr(_("%s: missing arguments for kill mode\n"), progname);
2154 ctl_command = KILL_COMMAND;
2155 set_sig(argv[++optind]);
2156 killproc = atol(argv[++optind]);
2158 #if defined(WIN32) || defined(__CYGWIN__)
2159 else if (strcmp(argv[optind], "register") == 0)
2160 ctl_command = REGISTER_COMMAND;
2161 else if (strcmp(argv[optind], "unregister") == 0)
2162 ctl_command = UNREGISTER_COMMAND;
2163 else if (strcmp(argv[optind], "runservice") == 0)
2164 ctl_command = RUN_AS_SERVICE_COMMAND;
2168 write_stderr(_("%s: unrecognized operation mode \"%s\"\n"), progname, argv[optind]);
2176 if (ctl_command == NO_COMMAND)
2178 write_stderr(_("%s: no operation specified\n"), progname);
2183 /* Note we put any -D switch into the env var above */
2184 pg_config = getenv("PGDATA");
2187 pg_config = pg_strdup(pg_config);
2188 canonicalize_path(pg_config);
2189 pg_data = pg_strdup(pg_config);
2192 /* -D might point at config-only directory; if so find the real PGDATA */
2195 /* Complain if -D needed and not provided */
2196 if (pg_config == NULL &&
2197 ctl_command != KILL_COMMAND && ctl_command != UNREGISTER_COMMAND)
2199 write_stderr(_("%s: no database directory specified and environment variable PGDATA unset\n"),
2207 switch (ctl_command)
2209 case RESTART_COMMAND:
2221 if (ctl_command == RELOAD_COMMAND)
2229 snprintf(postopts_file, MAXPGPATH, "%s/postmaster.opts", pg_data);
2230 snprintf(pid_file, MAXPGPATH, "%s/postmaster.pid", pg_data);
2231 snprintf(backup_file, MAXPGPATH, "%s/backup_label", pg_data);
2232 snprintf(recovery_file, MAXPGPATH, "%s/recovery.conf", pg_data);
2235 switch (ctl_command)
2240 case STATUS_COMMAND:
2249 case RESTART_COMMAND:
2252 case RELOAD_COMMAND:
2255 case PROMOTE_COMMAND:
2261 #if defined(WIN32) || defined(__CYGWIN__)
2262 case REGISTER_COMMAND:
2263 pgwin32_doRegister();
2265 case UNREGISTER_COMMAND:
2266 pgwin32_doUnregister();
2268 case RUN_AS_SERVICE_COMMAND:
2269 pgwin32_doRunAsService();