1 /*-------------------------------------------------------------------------
3 * pg_ctl --- start/stops/restarts the PostgreSQL server
5 * Portions Copyright (c) 1996-2012, 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"
26 #include <sys/types.h>
30 #ifdef HAVE_SYS_RESOURCE_H
32 #include <sys/resource.h>
35 #include "libpq/pqsignal.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 *pg_malloc(size_t size);
121 static char *xstrdup(const char *s);
122 static void do_advice(void);
123 static void do_help(void);
124 static void set_mode(char *modeopt);
125 static void set_sig(char *signame);
126 static void do_init(void);
127 static void do_start(void);
128 static void do_stop(void);
129 static void do_restart(void);
130 static void do_reload(void);
131 static void do_status(void);
132 static void do_promote(void);
133 static void do_kill(pgpid_t pid);
134 static void print_msg(const char *msg);
135 static void adjust_data_dir(void);
137 #if defined(WIN32) || defined(__CYGWIN__)
138 static bool pgwin32_IsInstalled(SC_HANDLE);
139 static char *pgwin32_CommandLine(bool);
140 static void pgwin32_doRegister(void);
141 static void pgwin32_doUnregister(void);
142 static void pgwin32_SetServiceStatus(DWORD);
143 static void WINAPI pgwin32_ServiceHandler(DWORD);
144 static void WINAPI pgwin32_ServiceMain(DWORD, LPTSTR *);
145 static void pgwin32_doRunAsService(void);
146 static int CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, bool as_service);
149 static pgpid_t get_pgpid(void);
150 static char **readfile(const char *path);
151 static int start_postmaster(void);
152 static void read_post_opts(void);
154 static PGPing test_postmaster_connection(bool);
155 static bool postmaster_is_alive(pid_t pid);
157 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_CORE)
158 static void unlimit_core_size(void);
162 #if defined(WIN32) || defined(__CYGWIN__)
164 write_eventlog(int level, const char *line)
166 static HANDLE evtHandle = INVALID_HANDLE_VALUE;
168 if (silent_mode && level == EVENTLOG_INFORMATION_TYPE)
171 if (evtHandle == INVALID_HANDLE_VALUE)
173 evtHandle = RegisterEventSource(NULL, "PostgreSQL");
174 if (evtHandle == NULL)
176 evtHandle = INVALID_HANDLE_VALUE;
181 ReportEvent(evtHandle,
184 0, /* All events are Id 0 */
194 * Write errors to stderr (or by equal means when stderr is
198 write_stderr(const char *fmt,...)
203 #if !defined(WIN32) && !defined(__CYGWIN__)
204 /* On Unix, we just fprintf to stderr */
205 vfprintf(stderr, fmt, ap);
209 * On Win32, we print to stderr if running on a console, or write to
210 * eventlog if running as a service
212 if (!isatty(fileno(stderr))) /* Running as a service */
214 char errbuf[2048]; /* Arbitrary size? */
216 vsnprintf(errbuf, sizeof(errbuf), fmt, ap);
218 write_eventlog(EVENTLOG_ERROR_TYPE, errbuf);
221 /* Not running as service, write to stderr */
222 vfprintf(stderr, fmt, ap);
228 * routines to check memory allocations and fail noisily.
232 pg_malloc(size_t size)
236 result = malloc(size);
239 write_stderr(_("%s: out of memory\n"), progname);
247 xstrdup(const char *s)
254 write_stderr(_("%s: out of memory\n"), progname);
261 * Given an already-localized string, print it to stdout unless the
262 * user has specified that no messages should be printed.
265 print_msg(const char *msg)
280 pidf = fopen(pid_file, "r");
283 /* No pid file, not an error on startup */
288 write_stderr(_("%s: could not open PID file \"%s\": %s\n"),
289 progname, pid_file, strerror(errno));
293 if (fscanf(pidf, "%ld", &pid) != 1)
295 write_stderr(_("%s: invalid data in PID file \"%s\"\n"),
300 return (pgpid_t) pid;
305 * get the lines from a text file - return NULL if file can't be opened
308 readfile(const char *path)
318 if ((infile = fopen(path, "r")) == NULL)
321 /* pass over the file twice - the first time to size the result */
323 while ((c = fgetc(infile)) != EOF)
329 if (linelen > maxlength)
335 /* handle last line without a terminating newline (yuck) */
338 if (linelen > maxlength)
341 /* set up the result and the line buffer */
342 result = (char **) pg_malloc((nlines + 1) * sizeof(char *));
343 buffer = (char *) pg_malloc(maxlength + 1);
345 /* now reprocess the file and store the lines */
348 while (fgets(buffer, maxlength + 1, infile) != NULL)
349 result[nlines++] = xstrdup(buffer);
353 result[nlines] = NULL;
361 * start/test/stop routines
365 start_postmaster(void)
372 * Since there might be quotes to handle here, it is easier simply to pass
373 * everything to a shell to process them.
375 * XXX it would be better to fork and exec so that we would know the child
376 * postmaster's PID directly; then test_postmaster_connection could use
377 * the PID without having to rely on reading it back from the pidfile.
379 if (log_file != NULL)
380 snprintf(cmd, MAXPGPATH, SYSTEMQUOTE "\"%s\" %s%s < \"%s\" >> \"%s\" 2>&1 &" SYSTEMQUOTE,
381 exec_path, pgdata_opt, post_opts,
384 snprintf(cmd, MAXPGPATH, SYSTEMQUOTE "\"%s\" %s%s < \"%s\" 2>&1 &" SYSTEMQUOTE,
385 exec_path, pgdata_opt, post_opts, DEVNULL);
391 * On win32 we don't use system(). So we don't need to use & (which would
392 * be START /B on win32). However, we still call the shell (CMD.EXE) with
393 * it to handle redirection etc.
395 PROCESS_INFORMATION pi;
397 if (log_file != NULL)
398 snprintf(cmd, MAXPGPATH, "CMD /C " SYSTEMQUOTE "\"%s\" %s%s < \"%s\" >> \"%s\" 2>&1" SYSTEMQUOTE,
399 exec_path, pgdata_opt, post_opts, DEVNULL, log_file);
401 snprintf(cmd, MAXPGPATH, "CMD /C " SYSTEMQUOTE "\"%s\" %s%s < \"%s\" 2>&1" SYSTEMQUOTE,
402 exec_path, pgdata_opt, post_opts, DEVNULL);
404 if (!CreateRestrictedProcess(cmd, &pi, false))
405 return GetLastError();
406 CloseHandle(pi.hProcess);
407 CloseHandle(pi.hThread);
415 * Find the pgport and try a connection
417 * Note that the checkpoint parameter enables a Windows service control
418 * manager checkpoint, it's got nothing to do with database checkpoints!!
421 test_postmaster_connection(bool do_checkpoint)
423 PGPing ret = PQPING_NO_RESPONSE;
424 bool found_stale_pidfile = false;
426 char connstr[MAXPGPATH * 2 + 256];
429 /* if requested wait time is zero, return "still starting up" code */
430 if (wait_seconds <= 0)
431 return PQPING_REJECT;
435 for (i = 0; i < wait_seconds; i++)
437 /* Do we need a connection string? */
438 if (connstr[0] == '\0')
441 * The number of lines in postmaster.pid tells us several things:
444 * 0 lock file created but status not written
445 * 2 pre-9.1 server, shared memory not created
446 * 3 pre-9.1 server, shared memory created
447 * 5 9.1+ server, ports not opened
448 * 6 9.1+ server, shared memory not created
449 * 7 9.1+ server, shared memory created
451 * This code does not support pre-9.1 servers. On Unix machines
452 * we could consider extracting the port number from the shmem
453 * key, but that (a) is not robust, and (b) doesn't help with
454 * finding out the socket directory. And it wouldn't work anyway
457 * If we see less than 6 lines in postmaster.pid, just keep
463 /* Try to read the postmaster.pid file */
464 if ((optlines = readfile(pid_file)) != NULL &&
465 optlines[0] != NULL &&
466 optlines[1] != NULL &&
469 if (optlines[3] == NULL)
471 /* File is exactly three lines, must be pre-9.1 */
472 write_stderr(_("\n%s: -w option is not supported when starting a pre-9.1 server\n"),
474 return PQPING_NO_ATTEMPT;
476 else if (optlines[4] != NULL &&
479 /* File is complete enough for us, parse it */
484 * Make sanity checks. If it's for a standalone backend
485 * (negative PID), or the recorded start time is before
486 * pg_ctl started, then either we are looking at the wrong
487 * data directory, or this is a pre-existing pidfile that
488 * hasn't (yet?) been overwritten by our child postmaster.
489 * Allow 2 seconds slop for possible cross-process clock
492 pmpid = atol(optlines[LOCK_FILE_LINE_PID - 1]);
493 pmstart = atol(optlines[LOCK_FILE_LINE_START_TIME - 1]);
494 if (pmpid <= 0 || pmstart < start_time - 2)
497 * Set flag to report stale pidfile if it doesn't get
498 * overwritten before we give up waiting.
500 found_stale_pidfile = true;
505 * OK, seems to be a valid pidfile from our child.
510 char host_str[MAXPGPATH];
512 found_stale_pidfile = false;
513 pm_pid = (pgpid_t) pmpid;
516 * Extract port number and host string to use. Prefer
517 * using Unix socket if available.
519 portnum = atoi(optlines[LOCK_FILE_LINE_PORT - 1]);
520 sockdir = optlines[LOCK_FILE_LINE_SOCKET_DIR - 1];
521 hostaddr = optlines[LOCK_FILE_LINE_LISTEN_ADDR - 1];
524 * While unix_socket_directory can accept relative
525 * directories, libpq's host parameter must have a
526 * leading slash to indicate a socket directory. So,
527 * ignore sockdir if it's relative, and try to use TCP
530 if (sockdir[0] == '/')
531 strlcpy(host_str, sockdir, sizeof(host_str));
533 strlcpy(host_str, hostaddr, sizeof(host_str));
535 /* remove trailing newline */
536 if (strchr(host_str, '\n') != NULL)
537 *strchr(host_str, '\n') = '\0';
539 /* Fail if couldn't get either sockdir or host addr */
540 if (host_str[0] == '\0')
542 write_stderr(_("\n%s: -w option cannot use a relative socket directory specification\n"),
544 return PQPING_NO_ATTEMPT;
547 /* If postmaster is listening on "*", use localhost */
548 if (strcmp(host_str, "*") == 0)
549 strcpy(host_str, "localhost");
552 * We need to set connect_timeout otherwise on Windows
553 * the Service Control Manager (SCM) will probably
556 snprintf(connstr, sizeof(connstr),
557 "dbname=postgres port=%d host='%s' connect_timeout=5",
564 /* If we have a connection string, ping the server */
565 if (connstr[0] != '\0')
567 ret = PQping(connstr);
568 if (ret == PQPING_OK || ret == PQPING_NO_ATTEMPT)
573 * The postmaster should create postmaster.pid very soon after being
574 * started. If it's not there after we've waited 5 or more seconds,
575 * assume startup failed and give up waiting. (Note this covers both
576 * cases where the pidfile was never created, and where it was created
577 * and then removed during postmaster exit.) Also, if there *is* a
578 * file there but it appears stale, issue a suitable warning and give
585 if (stat(pid_file, &statbuf) != 0)
586 return PQPING_NO_RESPONSE;
588 if (found_stale_pidfile)
590 write_stderr(_("\n%s: this data directory appears to be running a pre-existing postmaster\n"),
592 return PQPING_NO_RESPONSE;
597 * If we've been able to identify the child postmaster's PID, check
598 * the process is still alive. This covers cases where the postmaster
599 * successfully created the pidfile but then crashed without removing
602 if (pm_pid > 0 && !postmaster_is_alive((pid_t) pm_pid))
603 return PQPING_NO_RESPONSE;
605 /* No response, or startup still in process; wait */
610 * Increment the wait hint by 6 secs (connection timeout + sleep)
611 * We must do this to indicate to the SCM that our startup time is
612 * changing, otherwise it'll usually send a stop signal after 20
613 * seconds, despite incrementing the checkpoint counter.
615 status.dwWaitHint += 6000;
616 status.dwCheckPoint++;
617 SetServiceStatus(hStatus, (LPSERVICE_STATUS) &status);
623 pg_usleep(1000000); /* 1 sec */
626 /* return result of last call to PQping */
631 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_CORE)
633 unlimit_core_size(void)
637 getrlimit(RLIMIT_CORE, &lim);
638 if (lim.rlim_max == 0)
640 write_stderr(_("%s: cannot set core file size limit; disallowed by hard limit\n"),
644 else if (lim.rlim_max == RLIM_INFINITY || lim.rlim_cur < lim.rlim_max)
646 lim.rlim_cur = lim.rlim_max;
647 setrlimit(RLIMIT_CORE, &lim);
655 if (post_opts == NULL)
657 post_opts = ""; /* default */
658 if (ctl_command == RESTART_COMMAND)
662 optlines = readfile(postopts_file);
663 if (optlines == NULL)
665 write_stderr(_("%s: could not read file \"%s\"\n"), progname, postopts_file);
668 else if (optlines[0] == NULL || optlines[1] != NULL)
670 write_stderr(_("%s: option file \"%s\" must have exactly one line\n"),
671 progname, postopts_file);
680 optline = optlines[0];
681 /* trim off line endings */
682 len = strcspn(optline, "\r\n");
686 * Are we at the first option, as defined by space and
689 if ((arg1 = strstr(optline, " \"")) != NULL)
691 *arg1 = '\0'; /* terminate so we get only program
693 post_opts = arg1 + 1; /* point past whitespace */
695 if (exec_path == NULL)
703 find_other_exec_or_die(const char *argv0, const char *target, const char *versionstr)
708 found_path = pg_malloc(MAXPGPATH);
710 if ((ret = find_other_exec(argv0, target, versionstr, found_path)) < 0)
712 char full_path[MAXPGPATH];
714 if (find_my_exec(argv0, full_path) < 0)
715 strlcpy(full_path, progname, sizeof(full_path));
718 write_stderr(_("The program \"%s\" is needed by %s "
719 "but was not found in the\n"
720 "same directory as \"%s\".\n"
721 "Check your installation.\n"),
722 target, progname, full_path);
724 write_stderr(_("The program \"%s\" was found by \"%s\"\n"
725 "but was not the same version as %s.\n"
726 "Check your installation.\n"),
727 target, full_path, progname);
739 if (exec_path == NULL)
740 exec_path = find_other_exec_or_die(argv0, "initdb", "initdb (PostgreSQL) " PG_VERSION "\n");
742 if (pgdata_opt == NULL)
745 if (post_opts == NULL)
749 snprintf(cmd, MAXPGPATH, SYSTEMQUOTE "\"%s\" %s%s" SYSTEMQUOTE,
750 exec_path, pgdata_opt, post_opts);
752 snprintf(cmd, MAXPGPATH, SYSTEMQUOTE "\"%s\" %s%s > \"%s\"" SYSTEMQUOTE,
753 exec_path, pgdata_opt, post_opts, DEVNULL);
755 if (system(cmd) != 0)
757 write_stderr(_("%s: database system initialization failed\n"), progname);
768 if (ctl_command != RESTART_COMMAND)
770 old_pid = get_pgpid();
772 write_stderr(_("%s: another server might be running; "
773 "trying to start server anyway\n"),
779 /* No -D or -D already added during server start */
780 if (ctl_command == RESTART_COMMAND || pgdata_opt == NULL)
783 if (exec_path == NULL)
784 exec_path = find_other_exec_or_die(argv0, "postgres", PG_BACKEND_VERSIONSTR);
786 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_CORE)
787 if (allow_core_files)
792 * If possible, tell the postmaster our parent shell's PID (see the
793 * comments in CreateLockFile() for motivation). Windows hasn't got
794 * getppid() unfortunately.
798 static char env_var[32];
800 snprintf(env_var, sizeof(env_var), "PG_GRANDPARENT_PID=%d",
806 exitcode = start_postmaster();
809 write_stderr(_("%s: could not start server: exit code was %d\n"),
816 print_msg(_("waiting for server to start..."));
818 switch (test_postmaster_connection(false))
821 print_msg(_(" done\n"));
822 print_msg(_("server started\n"));
825 print_msg(_(" stopped waiting\n"));
826 print_msg(_("server is still starting up\n"));
828 case PQPING_NO_RESPONSE:
829 print_msg(_(" stopped waiting\n"));
830 write_stderr(_("%s: could not start server\n"
831 "Examine the log output.\n"),
835 case PQPING_NO_ATTEMPT:
836 print_msg(_(" failed\n"));
837 write_stderr(_("%s: could not wait for server because of misconfiguration\n"),
843 print_msg(_("server starting\n"));
856 if (pid == 0) /* no pid file */
858 write_stderr(_("%s: PID file \"%s\" does not exist\n"), progname, pid_file);
859 write_stderr(_("Is server running?\n"));
862 else if (pid < 0) /* standalone backend, not postmaster */
865 write_stderr(_("%s: cannot stop server; "
866 "single-user server is running (PID: %ld)\n"),
871 if (kill((pid_t) pid, sig) != 0)
873 write_stderr(_("%s: could not send stop signal (PID: %ld): %s\n"), progname, pid,
880 print_msg(_("server shutting down\n"));
886 * If backup_label exists, an online backup is running. Warn the user
887 * that smart shutdown will wait for it to finish. However, if
888 * recovery.conf is also present, we're recovering from an online
889 * backup instead of performing one.
891 if (shutdown_mode == SMART_MODE &&
892 stat(backup_file, &statbuf) == 0 &&
893 stat(recovery_file, &statbuf) != 0)
895 print_msg(_("WARNING: online backup mode is active\n"
896 "Shutdown will not complete until pg_stop_backup() is called.\n\n"));
899 print_msg(_("waiting for server to shut down..."));
901 for (cnt = 0; cnt < wait_seconds; cnt++)
903 if ((pid = get_pgpid()) != 0)
906 pg_usleep(1000000); /* 1 sec */
912 if (pid != 0) /* pid file still exists */
914 print_msg(_(" failed\n"));
916 write_stderr(_("%s: server does not shut down\n"), progname);
917 if (shutdown_mode == SMART_MODE)
918 write_stderr(_("HINT: The \"-m fast\" option immediately disconnects sessions rather than\n"
919 "waiting for session-initiated disconnection.\n"));
922 print_msg(_(" done\n"));
924 print_msg(_("server stopped\n"));
930 * restart/reload routines
942 if (pid == 0) /* no pid file */
944 write_stderr(_("%s: PID file \"%s\" does not exist\n"),
946 write_stderr(_("Is server running?\n"));
947 write_stderr(_("starting server anyway\n"));
951 else if (pid < 0) /* standalone backend, not postmaster */
954 if (postmaster_is_alive((pid_t) pid))
956 write_stderr(_("%s: cannot restart server; "
957 "single-user server is running (PID: %ld)\n"),
959 write_stderr(_("Please terminate the single-user server and try again.\n"));
964 if (postmaster_is_alive((pid_t) pid))
966 if (kill((pid_t) pid, sig) != 0)
968 write_stderr(_("%s: could not send stop signal (PID: %ld): %s\n"), progname, pid,
974 * If backup_label exists, an online backup is running. Warn the user
975 * that smart shutdown will wait for it to finish. However, if
976 * recovery.conf is also present, we're recovering from an online
977 * backup instead of performing one.
979 if (shutdown_mode == SMART_MODE &&
980 stat(backup_file, &statbuf) == 0 &&
981 stat(recovery_file, &statbuf) != 0)
983 print_msg(_("WARNING: online backup mode is active\n"
984 "Shutdown will not complete until pg_stop_backup() is called.\n\n"));
987 print_msg(_("waiting for server to shut down..."));
989 /* always wait for restart */
991 for (cnt = 0; cnt < wait_seconds; cnt++)
993 if ((pid = get_pgpid()) != 0)
996 pg_usleep(1000000); /* 1 sec */
1002 if (pid != 0) /* pid file still exists */
1004 print_msg(_(" failed\n"));
1006 write_stderr(_("%s: server does not shut down\n"), progname);
1007 if (shutdown_mode == SMART_MODE)
1008 write_stderr(_("HINT: The \"-m fast\" option immediately disconnects sessions rather than\n"
1009 "waiting for session-initiated disconnection.\n"));
1013 print_msg(_(" done\n"));
1014 print_msg(_("server stopped\n"));
1018 write_stderr(_("%s: old server process (PID: %ld) seems to be gone\n"),
1020 write_stderr(_("starting server anyway\n"));
1032 if (pid == 0) /* no pid file */
1034 write_stderr(_("%s: PID file \"%s\" does not exist\n"), progname, pid_file);
1035 write_stderr(_("Is server running?\n"));
1038 else if (pid < 0) /* standalone backend, not postmaster */
1041 write_stderr(_("%s: cannot reload server; "
1042 "single-user server is running (PID: %ld)\n"),
1044 write_stderr(_("Please terminate the single-user server and try again.\n"));
1048 if (kill((pid_t) pid, sig) != 0)
1050 write_stderr(_("%s: could not send reload signal (PID: %ld): %s\n"),
1051 progname, pid, strerror(errno));
1055 print_msg(_("server signaled\n"));
1068 struct stat statbuf;
1072 if (pid == 0) /* no pid file */
1074 write_stderr(_("%s: PID file \"%s\" does not exist\n"), progname, pid_file);
1075 write_stderr(_("Is server running?\n"));
1078 else if (pid < 0) /* standalone backend, not postmaster */
1081 write_stderr(_("%s: cannot promote server; "
1082 "single-user server is running (PID: %ld)\n"),
1087 /* If recovery.conf doesn't exist, the server is not in standby mode */
1088 if (stat(recovery_file, &statbuf) != 0)
1090 write_stderr(_("%s: cannot promote server; "
1091 "server is not in standby mode\n"),
1096 if ((prmfile = fopen(promote_file, "w")) == NULL)
1098 write_stderr(_("%s: could not create promote signal file \"%s\": %s\n"),
1099 progname, promote_file, strerror(errno));
1102 if (fclose(prmfile))
1104 write_stderr(_("%s: could not write promote signal file \"%s\": %s\n"),
1105 progname, promote_file, strerror(errno));
1110 if (kill((pid_t) pid, sig) != 0)
1112 write_stderr(_("%s: could not send promote signal (PID: %ld): %s\n"),
1113 progname, pid, strerror(errno));
1114 if (unlink(promote_file) != 0)
1115 write_stderr(_("%s: could not remove promote signal file \"%s\": %s\n"),
1116 progname, promote_file, strerror(errno));
1120 print_msg(_("server promoting\n"));
1129 postmaster_is_alive(pid_t pid)
1132 * Test to see if the process is still there. Note that we do not
1133 * consider an EPERM failure to mean that the process is still there;
1134 * EPERM must mean that the given PID belongs to some other userid, and
1135 * considering the permissions on $PGDATA, that means it's not the
1136 * postmaster we are after.
1138 * Don't believe that our own PID or parent shell's PID is the postmaster,
1139 * either. (Windows hasn't got getppid(), though.)
1141 if (pid == getpid())
1144 if (pid == getppid())
1147 if (kill(pid, 0) == 0)
1158 /* Is there a pid file? */
1161 /* standalone backend? */
1165 if (postmaster_is_alive((pid_t) pid))
1167 printf(_("%s: single-user server is running (PID: %ld)\n"),
1173 /* must be a postmaster */
1175 if (postmaster_is_alive((pid_t) pid))
1179 printf(_("%s: server is running (PID: %ld)\n"),
1182 optlines = readfile(postopts_file);
1183 if (optlines != NULL)
1184 for (; *optlines != NULL; optlines++)
1185 fputs(*optlines, stdout);
1190 printf(_("%s: no server running\n"), progname);
1193 * The Linux Standard Base Core Specification 3.1 says this should return
1195 * http://refspecs.freestandards.org/LSB_3.1.1/LSB-Core-generic/LSB-Core-ge
1196 * neric/iniscrptact.html
1204 do_kill(pgpid_t pid)
1206 if (kill((pid_t) pid, sig) != 0)
1208 write_stderr(_("%s: could not send signal %d (PID: %ld): %s\n"),
1209 progname, sig, pid, strerror(errno));
1214 #if defined(WIN32) || defined(__CYGWIN__)
1217 pgwin32_IsInstalled(SC_HANDLE hSCM)
1219 SC_HANDLE hService = OpenService(hSCM, register_servicename, SERVICE_QUERY_CONFIG);
1220 bool bResult = (hService != NULL);
1223 CloseServiceHandle(hService);
1228 pgwin32_CommandLine(bool registration)
1230 static char cmdLine[MAXPGPATH];
1234 char buf[MAXPGPATH];
1239 ret = find_my_exec(argv0, cmdLine);
1242 write_stderr(_("%s: could not find own program executable\n"), progname);
1248 ret = find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
1252 write_stderr(_("%s: could not find postgres program executable\n"), progname);
1258 /* need to convert to windows path */
1259 #if CYGWIN_VERSION_DLL_MAJOR >= 1007
1260 cygwin_conv_path(CCP_POSIX_TO_WIN_A, cmdLine, buf, sizeof(buf));
1262 cygwin_conv_to_full_win32_path(cmdLine, buf);
1264 strcpy(cmdLine, buf);
1269 if (pg_strcasecmp(cmdLine + strlen(cmdLine) - 4, ".exe") != 0)
1271 /* If commandline does not end in .exe, append it */
1272 strcat(cmdLine, ".exe");
1274 strcat(cmdLine, " runservice -N \"");
1275 strcat(cmdLine, register_servicename);
1276 strcat(cmdLine, "\"");
1281 strcat(cmdLine, " -D \"");
1282 strcat(cmdLine, pg_config);
1283 strcat(cmdLine, "\"");
1286 if (registration && do_wait)
1287 strcat(cmdLine, " -w");
1289 if (registration && wait_seconds != DEFAULT_WAIT)
1291 sprintf(cmdLine + strlen(cmdLine), " -t %d", wait_seconds);
1293 if (registration && silent_mode)
1294 strcat(cmdLine, " -s");
1298 strcat(cmdLine, " ");
1300 strcat(cmdLine, " -o \"");
1301 strcat(cmdLine, post_opts);
1303 strcat(cmdLine, "\"");
1310 pgwin32_doRegister(void)
1313 SC_HANDLE hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
1317 write_stderr(_("%s: could not open service manager\n"), progname);
1320 if (pgwin32_IsInstalled(hSCM))
1322 CloseServiceHandle(hSCM);
1323 write_stderr(_("%s: service \"%s\" already registered\n"), progname, register_servicename);
1327 if ((hService = CreateService(hSCM, register_servicename, register_servicename,
1328 SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
1329 pgctl_start_type, SERVICE_ERROR_NORMAL,
1330 pgwin32_CommandLine(true),
1331 NULL, NULL, "RPCSS\0", register_username, register_password)) == NULL)
1333 CloseServiceHandle(hSCM);
1334 write_stderr(_("%s: could not register service \"%s\": error code %lu\n"), progname, register_servicename, GetLastError());
1337 CloseServiceHandle(hService);
1338 CloseServiceHandle(hSCM);
1342 pgwin32_doUnregister(void)
1345 SC_HANDLE hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
1349 write_stderr(_("%s: could not open service manager\n"), progname);
1352 if (!pgwin32_IsInstalled(hSCM))
1354 CloseServiceHandle(hSCM);
1355 write_stderr(_("%s: service \"%s\" not registered\n"), progname, register_servicename);
1359 if ((hService = OpenService(hSCM, register_servicename, DELETE)) == NULL)
1361 CloseServiceHandle(hSCM);
1362 write_stderr(_("%s: could not open service \"%s\": error code %lu\n"), progname, register_servicename, GetLastError());
1365 if (!DeleteService(hService))
1367 CloseServiceHandle(hService);
1368 CloseServiceHandle(hSCM);
1369 write_stderr(_("%s: could not unregister service \"%s\": error code %lu\n"), progname, register_servicename, GetLastError());
1372 CloseServiceHandle(hService);
1373 CloseServiceHandle(hSCM);
1377 pgwin32_SetServiceStatus(DWORD currentState)
1379 status.dwCurrentState = currentState;
1380 SetServiceStatus(hStatus, (LPSERVICE_STATUS) &status);
1384 pgwin32_ServiceHandler(DWORD request)
1388 case SERVICE_CONTROL_STOP:
1389 case SERVICE_CONTROL_SHUTDOWN:
1392 * We only need a short wait hint here as it just needs to wait
1393 * for the next checkpoint. They occur every 5 seconds during
1396 status.dwWaitHint = 10000;
1397 pgwin32_SetServiceStatus(SERVICE_STOP_PENDING);
1398 SetEvent(shutdownEvent);
1401 case SERVICE_CONTROL_PAUSE:
1402 /* Win32 config reloading */
1403 status.dwWaitHint = 5000;
1404 kill(postmasterPID, SIGHUP);
1407 /* FIXME: These could be used to replace other signals etc */
1408 case SERVICE_CONTROL_CONTINUE:
1409 case SERVICE_CONTROL_INTERROGATE:
1416 pgwin32_ServiceMain(DWORD argc, LPTSTR *argv)
1418 PROCESS_INFORMATION pi;
1421 /* Initialize variables */
1422 status.dwWin32ExitCode = S_OK;
1423 status.dwCheckPoint = 0;
1424 status.dwWaitHint = 60000;
1425 status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
1426 status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_PAUSE_CONTINUE;
1427 status.dwServiceSpecificExitCode = 0;
1428 status.dwCurrentState = SERVICE_START_PENDING;
1430 memset(&pi, 0, sizeof(pi));
1434 /* Register the control request handler */
1435 if ((hStatus = RegisterServiceCtrlHandler(register_servicename, pgwin32_ServiceHandler)) == (SERVICE_STATUS_HANDLE) 0)
1438 if ((shutdownEvent = CreateEvent(NULL, true, false, NULL)) == NULL)
1441 /* Start the postmaster */
1442 pgwin32_SetServiceStatus(SERVICE_START_PENDING);
1443 if (!CreateRestrictedProcess(pgwin32_CommandLine(false), &pi, true))
1445 pgwin32_SetServiceStatus(SERVICE_STOPPED);
1448 postmasterPID = pi.dwProcessId;
1449 postmasterProcess = pi.hProcess;
1450 CloseHandle(pi.hThread);
1454 write_eventlog(EVENTLOG_INFORMATION_TYPE, _("Waiting for server startup...\n"));
1455 if (test_postmaster_connection(true) != PQPING_OK)
1457 write_eventlog(EVENTLOG_ERROR_TYPE, _("Timed out waiting for server startup\n"));
1458 pgwin32_SetServiceStatus(SERVICE_STOPPED);
1461 write_eventlog(EVENTLOG_INFORMATION_TYPE, _("Server started and accepting connections\n"));
1464 pgwin32_SetServiceStatus(SERVICE_RUNNING);
1466 /* Wait for quit... */
1467 ret = WaitForMultipleObjects(2, shutdownHandles, FALSE, INFINITE);
1469 pgwin32_SetServiceStatus(SERVICE_STOP_PENDING);
1472 case WAIT_OBJECT_0: /* shutdown event */
1473 kill(postmasterPID, SIGINT);
1476 * Increment the checkpoint and try again Abort after 12
1477 * checkpoints as the postmaster has probably hung
1479 while (WaitForSingleObject(postmasterProcess, 5000) == WAIT_TIMEOUT && status.dwCheckPoint < 12)
1480 status.dwCheckPoint++;
1483 case (WAIT_OBJECT_0 + 1): /* postmaster went down */
1487 /* shouldn't get here? */
1491 CloseHandle(shutdownEvent);
1492 CloseHandle(postmasterProcess);
1494 pgwin32_SetServiceStatus(SERVICE_STOPPED);
1498 pgwin32_doRunAsService(void)
1500 SERVICE_TABLE_ENTRY st[] = {{register_servicename, pgwin32_ServiceMain},
1503 if (StartServiceCtrlDispatcher(st) == 0)
1505 write_stderr(_("%s: could not start service \"%s\": error code %lu\n"), progname, register_servicename, GetLastError());
1512 * Mingw headers are incomplete, and so are the libraries. So we have to load
1513 * a whole lot of API functions dynamically. Since we have to do this anyway,
1514 * also load the couple of functions that *do* exist in minwg headers but not
1515 * on NT4. That way, we don't break on NT4.
1517 typedef BOOL (WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE);
1518 typedef BOOL (WINAPI * __IsProcessInJob) (HANDLE, HANDLE, PBOOL);
1519 typedef HANDLE (WINAPI * __CreateJobObject) (LPSECURITY_ATTRIBUTES, LPCTSTR);
1520 typedef BOOL (WINAPI * __SetInformationJobObject) (HANDLE, JOBOBJECTINFOCLASS, LPVOID, DWORD);
1521 typedef BOOL (WINAPI * __AssignProcessToJobObject) (HANDLE, HANDLE);
1522 typedef BOOL (WINAPI * __QueryInformationJobObject) (HANDLE, JOBOBJECTINFOCLASS, LPVOID, DWORD, LPDWORD);
1524 /* Windows API define missing from some versions of MingW headers */
1525 #ifndef DISABLE_MAX_PRIVILEGE
1526 #define DISABLE_MAX_PRIVILEGE 0x1
1530 * Create a restricted token, a job object sandbox, and execute the specified
1533 * Returns 0 on success, non-zero on failure, same as CreateProcess().
1535 * On NT4, or any other system not containing the required functions, will
1536 * launch the process under the current token without doing any modifications.
1538 * NOTE! Job object will only work when running as a service, because it's
1539 * automatically destroyed when pg_ctl exits.
1542 CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, bool as_service)
1548 HANDLE restrictedToken;
1549 SID_IDENTIFIER_AUTHORITY NtAuthority = {SECURITY_NT_AUTHORITY};
1550 SID_AND_ATTRIBUTES dropSids[2];
1552 /* Functions loaded dynamically */
1553 __CreateRestrictedToken _CreateRestrictedToken = NULL;
1554 __IsProcessInJob _IsProcessInJob = NULL;
1555 __CreateJobObject _CreateJobObject = NULL;
1556 __SetInformationJobObject _SetInformationJobObject = NULL;
1557 __AssignProcessToJobObject _AssignProcessToJobObject = NULL;
1558 __QueryInformationJobObject _QueryInformationJobObject = NULL;
1559 HANDLE Kernel32Handle;
1560 HANDLE Advapi32Handle;
1562 ZeroMemory(&si, sizeof(si));
1565 Advapi32Handle = LoadLibrary("ADVAPI32.DLL");
1566 if (Advapi32Handle != NULL)
1568 _CreateRestrictedToken = (__CreateRestrictedToken) GetProcAddress(Advapi32Handle, "CreateRestrictedToken");
1571 if (_CreateRestrictedToken == NULL)
1574 * NT4 doesn't have CreateRestrictedToken, so just call ordinary
1577 write_stderr(_("%s: WARNING: cannot create restricted tokens on this platform\n"), progname);
1578 if (Advapi32Handle != NULL)
1579 FreeLibrary(Advapi32Handle);
1580 return CreateProcess(NULL, cmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, processInfo);
1583 /* Open the current token to use as a base for the restricted one */
1584 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken))
1586 write_stderr(_("%s: could not open process token: error code %lu\n"), progname, GetLastError());
1590 /* Allocate list of SIDs to remove */
1591 ZeroMemory(&dropSids, sizeof(dropSids));
1592 if (!AllocateAndInitializeSid(&NtAuthority, 2,
1593 SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0,
1594 0, &dropSids[0].Sid) ||
1595 !AllocateAndInitializeSid(&NtAuthority, 2,
1596 SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0,
1597 0, &dropSids[1].Sid))
1599 write_stderr(_("%s: could not allocate SIDs: error code %lu\n"), progname, GetLastError());
1603 b = _CreateRestrictedToken(origToken,
1604 DISABLE_MAX_PRIVILEGE,
1605 sizeof(dropSids) / sizeof(dropSids[0]),
1611 FreeSid(dropSids[1].Sid);
1612 FreeSid(dropSids[0].Sid);
1613 CloseHandle(origToken);
1614 FreeLibrary(Advapi32Handle);
1618 write_stderr(_("%s: could not create restricted token: error code %lu\n"), progname, GetLastError());
1623 AddUserToTokenDacl(restrictedToken);
1626 r = CreateProcessAsUser(restrictedToken, NULL, cmd, NULL, NULL, TRUE, CREATE_SUSPENDED, NULL, NULL, &si, processInfo);
1628 Kernel32Handle = LoadLibrary("KERNEL32.DLL");
1629 if (Kernel32Handle != NULL)
1631 _IsProcessInJob = (__IsProcessInJob) GetProcAddress(Kernel32Handle, "IsProcessInJob");
1632 _CreateJobObject = (__CreateJobObject) GetProcAddress(Kernel32Handle, "CreateJobObjectA");
1633 _SetInformationJobObject = (__SetInformationJobObject) GetProcAddress(Kernel32Handle, "SetInformationJobObject");
1634 _AssignProcessToJobObject = (__AssignProcessToJobObject) GetProcAddress(Kernel32Handle, "AssignProcessToJobObject");
1635 _QueryInformationJobObject = (__QueryInformationJobObject) GetProcAddress(Kernel32Handle, "QueryInformationJobObject");
1638 /* Verify that we found all functions */
1639 if (_IsProcessInJob == NULL || _CreateJobObject == NULL || _SetInformationJobObject == NULL || _AssignProcessToJobObject == NULL || _QueryInformationJobObject == NULL)
1642 * IsProcessInJob() is not available on < WinXP, so there is no need
1643 * to log the error every time in that case
1647 osv.dwOSVersionInfoSize = sizeof(osv);
1648 if (!GetVersionEx(&osv) || /* could not get version */
1649 (osv.dwMajorVersion == 5 && osv.dwMinorVersion > 0) || /* 5.1=xp, 5.2=2003, etc */
1650 osv.dwMajorVersion > 5) /* anything newer should have the API */
1653 * Log error if we can't get version, or if we're on WinXP/2003 or
1656 write_stderr(_("%s: WARNING: could not locate all job object functions in system API\n"), progname);
1662 if (_IsProcessInJob(processInfo->hProcess, NULL, &inJob))
1667 * Job objects are working, and the new process isn't in one,
1668 * so we can create one safely. If any problems show up when
1669 * setting it, we're going to ignore them.
1674 sprintf(jobname, "PostgreSQL_%lu", processInfo->dwProcessId);
1676 job = _CreateJobObject(NULL, jobname);
1679 JOBOBJECT_BASIC_LIMIT_INFORMATION basicLimit;
1680 JOBOBJECT_BASIC_UI_RESTRICTIONS uiRestrictions;
1681 JOBOBJECT_SECURITY_LIMIT_INFORMATION securityLimit;
1684 ZeroMemory(&basicLimit, sizeof(basicLimit));
1685 ZeroMemory(&uiRestrictions, sizeof(uiRestrictions));
1686 ZeroMemory(&securityLimit, sizeof(securityLimit));
1688 basicLimit.LimitFlags = JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION | JOB_OBJECT_LIMIT_PRIORITY_CLASS;
1689 basicLimit.PriorityClass = NORMAL_PRIORITY_CLASS;
1690 _SetInformationJobObject(job, JobObjectBasicLimitInformation, &basicLimit, sizeof(basicLimit));
1692 uiRestrictions.UIRestrictionsClass = JOB_OBJECT_UILIMIT_DESKTOP | JOB_OBJECT_UILIMIT_DISPLAYSETTINGS |
1693 JOB_OBJECT_UILIMIT_EXITWINDOWS | JOB_OBJECT_UILIMIT_READCLIPBOARD |
1694 JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS | JOB_OBJECT_UILIMIT_WRITECLIPBOARD;
1698 osv.dwOSVersionInfoSize = sizeof(osv);
1699 if (!GetVersionEx(&osv) ||
1700 osv.dwMajorVersion < 6 ||
1701 (osv.dwMajorVersion == 6 && osv.dwMinorVersion == 0))
1704 * On Windows 7 (and presumably later),
1705 * JOB_OBJECT_UILIMIT_HANDLES prevents us from
1706 * starting as a service. So we only enable it on
1707 * Vista and earlier (version <= 6.0)
1709 uiRestrictions.UIRestrictionsClass |= JOB_OBJECT_UILIMIT_HANDLES;
1712 _SetInformationJobObject(job, JobObjectBasicUIRestrictions, &uiRestrictions, sizeof(uiRestrictions));
1714 securityLimit.SecurityLimitFlags = JOB_OBJECT_SECURITY_NO_ADMIN | JOB_OBJECT_SECURITY_ONLY_TOKEN;
1715 securityLimit.JobToken = restrictedToken;
1716 _SetInformationJobObject(job, JobObjectSecurityLimitInformation, &securityLimit, sizeof(securityLimit));
1718 _AssignProcessToJobObject(job, processInfo->hProcess);
1725 CloseHandle(restrictedToken);
1727 ResumeThread(processInfo->hThread);
1729 FreeLibrary(Kernel32Handle);
1732 * We intentionally don't close the job object handle, because we want the
1733 * object to live on until pg_ctl shuts down.
1742 write_stderr(_("Try \"%s --help\" for more information.\n"), progname);
1750 printf(_("%s is a utility to initialize, start, stop, or control a PostgreSQL server.\n\n"), progname);
1751 printf(_("Usage:\n"));
1752 printf(_(" %s init[db] [-D DATADIR] [-s] [-o \"OPTIONS\"]\n"), progname);
1753 printf(_(" %s start [-w] [-t SECS] [-D DATADIR] [-s] [-l FILENAME] [-o \"OPTIONS\"]\n"), progname);
1754 printf(_(" %s stop [-W] [-t SECS] [-D DATADIR] [-s] [-m SHUTDOWN-MODE]\n"), progname);
1755 printf(_(" %s restart [-w] [-t SECS] [-D DATADIR] [-s] [-m SHUTDOWN-MODE]\n"
1756 " [-o \"OPTIONS\"]\n"), progname);
1757 printf(_(" %s reload [-D DATADIR] [-s]\n"), progname);
1758 printf(_(" %s status [-D DATADIR]\n"), progname);
1759 printf(_(" %s promote [-D DATADIR] [-s]\n"), progname);
1760 printf(_(" %s kill SIGNALNAME PID\n"), progname);
1761 #if defined(WIN32) || defined(__CYGWIN__)
1762 printf(_(" %s register [-N SERVICENAME] [-U USERNAME] [-P PASSWORD] [-D DATADIR]\n"
1763 " [-S START-TYPE] [-w] [-t SECS] [-o \"OPTIONS\"]\n"), progname);
1764 printf(_(" %s unregister [-N SERVICENAME]\n"), progname);
1767 printf(_("\nCommon options:\n"));
1768 printf(_(" -D, --pgdata=DATADIR location of the database storage area\n"));
1769 printf(_(" -s, --silent only print errors, no informational messages\n"));
1770 printf(_(" -t, --timeout=SECS seconds to wait when using -w option\n"));
1771 printf(_(" -V, --version output version information, then exit\n"));
1772 printf(_(" -w wait until operation completes\n"));
1773 printf(_(" -W do not wait until operation completes\n"));
1774 printf(_(" -?, --help show this help, then exit\n"));
1775 printf(_("(The default is to wait for shutdown, but not for start or restart.)\n\n"));
1776 printf(_("If the -D option is omitted, the environment variable PGDATA is used.\n"));
1778 printf(_("\nOptions for start or restart:\n"));
1779 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_CORE)
1780 printf(_(" -c, --core-files allow postgres to produce core files\n"));
1782 printf(_(" -c, --core-files not applicable on this platform\n"));
1784 printf(_(" -l, --log=FILENAME write (or append) server log to FILENAME\n"));
1785 printf(_(" -o OPTIONS command line options to pass to postgres\n"
1786 " (PostgreSQL server executable) or initdb\n"));
1787 printf(_(" -p PATH-TO-POSTGRES normally not necessary\n"));
1788 printf(_("\nOptions for stop or restart:\n"));
1789 printf(_(" -m, --mode=MODE MODE can be \"smart\", \"fast\", or \"immediate\"\n"));
1791 printf(_("\nShutdown modes are:\n"));
1792 printf(_(" smart quit after all clients have disconnected\n"));
1793 printf(_(" fast quit directly, with proper shutdown\n"));
1794 printf(_(" immediate quit without complete shutdown; will lead to recovery on restart\n"));
1796 printf(_("\nAllowed signal names for kill:\n"));
1797 printf(" ABRT HUP INT QUIT TERM USR1 USR2\n");
1799 #if defined(WIN32) || defined(__CYGWIN__)
1800 printf(_("\nOptions for register and unregister:\n"));
1801 printf(_(" -N SERVICENAME service name with which to register PostgreSQL server\n"));
1802 printf(_(" -P PASSWORD password of account to register PostgreSQL server\n"));
1803 printf(_(" -U USERNAME user name of account to register PostgreSQL server\n"));
1804 printf(_(" -S START-TYPE service start type to register PostgreSQL server\n"));
1806 printf(_("\nStart types are:\n"));
1807 printf(_(" auto start service automatically during system startup (default)\n"));
1808 printf(_(" demand start service on demand\n"));
1811 printf(_("\nReport bugs to <pgsql-bugs@postgresql.org>.\n"));
1817 set_mode(char *modeopt)
1819 if (strcmp(modeopt, "s") == 0 || strcmp(modeopt, "smart") == 0)
1821 shutdown_mode = SMART_MODE;
1824 else if (strcmp(modeopt, "f") == 0 || strcmp(modeopt, "fast") == 0)
1826 shutdown_mode = FAST_MODE;
1829 else if (strcmp(modeopt, "i") == 0 || strcmp(modeopt, "immediate") == 0)
1831 shutdown_mode = IMMEDIATE_MODE;
1836 write_stderr(_("%s: unrecognized shutdown mode \"%s\"\n"), progname, modeopt);
1845 set_sig(char *signame)
1847 if (strcmp(signame, "HUP") == 0)
1849 else if (strcmp(signame, "INT") == 0)
1851 else if (strcmp(signame, "QUIT") == 0)
1853 else if (strcmp(signame, "ABRT") == 0)
1856 /* probably should NOT provide SIGKILL */
1857 else if (strcmp(signame, "KILL") == 0)
1860 else if (strcmp(signame, "TERM") == 0)
1862 else if (strcmp(signame, "USR1") == 0)
1864 else if (strcmp(signame, "USR2") == 0)
1868 write_stderr(_("%s: unrecognized signal name \"%s\"\n"), progname, signame);
1875 #if defined(WIN32) || defined(__CYGWIN__)
1877 set_starttype(char *starttypeopt)
1879 if (strcmp(starttypeopt, "a") == 0 || strcmp(starttypeopt, "auto") == 0)
1880 pgctl_start_type = SERVICE_AUTO_START;
1881 else if (strcmp(starttypeopt, "d") == 0 || strcmp(starttypeopt, "demand") == 0)
1882 pgctl_start_type = SERVICE_DEMAND_START;
1885 write_stderr(_("%s: unrecognized start type \"%s\"\n"), progname, starttypeopt);
1895 * If a configuration-only directory was specified, find the real data dir.
1898 adjust_data_dir(void)
1900 char cmd[MAXPGPATH],
1901 filename[MAXPGPATH],
1905 /* do nothing if we're working without knowledge of data dir */
1906 if (pg_config == NULL)
1909 /* If there is no postgresql.conf, it can't be a config-only dir */
1910 snprintf(filename, sizeof(filename), "%s/postgresql.conf", pg_config);
1911 if ((fd = fopen(filename, "r")) == NULL)
1915 /* If PG_VERSION exists, it can't be a config-only dir */
1916 snprintf(filename, sizeof(filename), "%s/PG_VERSION", pg_config);
1917 if ((fd = fopen(filename, "r")) != NULL)
1923 /* Must be a configuration directory, so find the data directory */
1925 /* we use a private my_exec_path to avoid interfering with later uses */
1926 if (exec_path == NULL)
1927 my_exec_path = find_other_exec_or_die(argv0, "postgres", PG_BACKEND_VERSIONSTR);
1929 my_exec_path = xstrdup(exec_path);
1931 snprintf(cmd, MAXPGPATH, SYSTEMQUOTE "\"%s\" %s%s -C data_directory" SYSTEMQUOTE,
1932 my_exec_path, pgdata_opt ? pgdata_opt : "", post_opts ?
1935 fd = popen(cmd, "r");
1936 if (fd == NULL || fgets(filename, sizeof(filename), fd) == NULL)
1938 write_stderr(_("%s: could not determine the data directory using command \"%s\"\n"), progname, cmd);
1944 /* Remove trailing newline */
1945 if (strchr(filename, '\n') != NULL)
1946 *strchr(filename, '\n') = '\0';
1949 pg_data = xstrdup(filename);
1950 canonicalize_path(pg_data);
1955 main(int argc, char **argv)
1957 static struct option long_options[] = {
1958 {"help", no_argument, NULL, '?'},
1959 {"version", no_argument, NULL, 'V'},
1960 {"log", required_argument, NULL, 'l'},
1961 {"mode", required_argument, NULL, 'm'},
1962 {"pgdata", required_argument, NULL, 'D'},
1963 {"silent", no_argument, NULL, 's'},
1964 {"timeout", required_argument, NULL, 't'},
1965 {"core-files", no_argument, NULL, 'c'},
1971 pgpid_t killproc = 0;
1973 #if defined(WIN32) || defined(__CYGWIN__)
1974 setvbuf(stderr, NULL, _IONBF, 0);
1977 progname = get_progname(argv[0]);
1978 set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_ctl"));
1979 start_time = time(NULL);
1982 * save argv[0] so do_start() can look for the postmaster if necessary. we
1983 * don't look for postmaster here because in many cases we won't need it.
1987 umask(S_IRWXG | S_IRWXO);
1989 /* support --help and --version even if invoked as root */
1992 if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0 ||
1993 strcmp(argv[1], "-?") == 0)
1998 else if (strcmp(argv[1], "-V") == 0 || strcmp(argv[1], "--version") == 0)
2000 puts("pg_ctl (PostgreSQL) " PG_VERSION);
2006 * Disallow running as root, to forestall any possible security holes.
2011 write_stderr(_("%s: cannot be run as root\n"
2012 "Please log in (using, e.g., \"su\") as the "
2013 "(unprivileged) user that will\n"
2014 "own the server process.\n"),
2021 * 'Action' can be before or after args so loop over both. Some
2022 * getopt_long() implementations will reorder argv[] to place all flags
2023 * first (GNU?), but we don't rely on it. Our /port version doesn't do
2028 /* process command-line options */
2029 while (optind < argc)
2031 while ((c = getopt_long(argc, argv, "cD:l:m:N:o:p:P:sS:t:U:wW", long_options, &option_index)) != -1)
2038 char *env_var = pg_malloc(strlen(optarg) + 8);
2040 pgdata_D = xstrdup(optarg);
2041 canonicalize_path(pgdata_D);
2042 snprintf(env_var, strlen(optarg) + 8, "PGDATA=%s",
2047 * We could pass PGDATA just in an environment
2048 * variable but we do -D too for clearer postmaster
2051 pgdata_opt = pg_malloc(strlen(pgdata_D) + 7);
2052 snprintf(pgdata_opt, strlen(pgdata_D) + 7,
2058 log_file = xstrdup(optarg);
2064 register_servicename = xstrdup(optarg);
2067 post_opts = xstrdup(optarg);
2070 exec_path = xstrdup(optarg);
2073 register_password = xstrdup(optarg);
2079 #if defined(WIN32) || defined(__CYGWIN__)
2080 set_starttype(optarg);
2082 write_stderr(_("%s: -S option not supported on this platform\n"),
2088 wait_seconds = atoi(optarg);
2091 if (strchr(optarg, '\\'))
2092 register_username = xstrdup(optarg);
2094 /* Prepend .\ for local accounts */
2096 register_username = malloc(strlen(optarg) + 3);
2097 if (!register_username)
2099 write_stderr(_("%s: out of memory\n"), progname);
2102 strcpy(register_username, ".\\");
2103 strcat(register_username, optarg);
2115 allow_core_files = true;
2118 /* getopt_long already issued a suitable error message */
2124 /* Process an action */
2127 if (ctl_command != NO_COMMAND)
2129 write_stderr(_("%s: too many command-line arguments (first is \"%s\")\n"), progname, argv[optind]);
2134 if (strcmp(argv[optind], "init") == 0
2135 || strcmp(argv[optind], "initdb") == 0)
2136 ctl_command = INIT_COMMAND;
2137 else if (strcmp(argv[optind], "start") == 0)
2138 ctl_command = START_COMMAND;
2139 else if (strcmp(argv[optind], "stop") == 0)
2140 ctl_command = STOP_COMMAND;
2141 else if (strcmp(argv[optind], "restart") == 0)
2142 ctl_command = RESTART_COMMAND;
2143 else if (strcmp(argv[optind], "reload") == 0)
2144 ctl_command = RELOAD_COMMAND;
2145 else if (strcmp(argv[optind], "status") == 0)
2146 ctl_command = STATUS_COMMAND;
2147 else if (strcmp(argv[optind], "promote") == 0)
2148 ctl_command = PROMOTE_COMMAND;
2149 else if (strcmp(argv[optind], "kill") == 0)
2151 if (argc - optind < 3)
2153 write_stderr(_("%s: missing arguments for kill mode\n"), progname);
2157 ctl_command = KILL_COMMAND;
2158 set_sig(argv[++optind]);
2159 killproc = atol(argv[++optind]);
2161 #if defined(WIN32) || defined(__CYGWIN__)
2162 else if (strcmp(argv[optind], "register") == 0)
2163 ctl_command = REGISTER_COMMAND;
2164 else if (strcmp(argv[optind], "unregister") == 0)
2165 ctl_command = UNREGISTER_COMMAND;
2166 else if (strcmp(argv[optind], "runservice") == 0)
2167 ctl_command = RUN_AS_SERVICE_COMMAND;
2171 write_stderr(_("%s: unrecognized operation mode \"%s\"\n"), progname, argv[optind]);
2179 if (ctl_command == NO_COMMAND)
2181 write_stderr(_("%s: no operation specified\n"), progname);
2186 /* Note we put any -D switch into the env var above */
2187 pg_config = getenv("PGDATA");
2190 pg_config = xstrdup(pg_config);
2191 canonicalize_path(pg_config);
2192 pg_data = xstrdup(pg_config);
2195 /* -D might point at config-only directory; if so find the real PGDATA */
2198 /* Complain if -D needed and not provided */
2199 if (pg_config == NULL &&
2200 ctl_command != KILL_COMMAND && ctl_command != UNREGISTER_COMMAND)
2202 write_stderr(_("%s: no database directory specified and environment variable PGDATA unset\n"),
2210 switch (ctl_command)
2212 case RESTART_COMMAND:
2224 if (ctl_command == RELOAD_COMMAND)
2232 snprintf(postopts_file, MAXPGPATH, "%s/postmaster.opts", pg_data);
2233 snprintf(pid_file, MAXPGPATH, "%s/postmaster.pid", pg_data);
2234 snprintf(backup_file, MAXPGPATH, "%s/backup_label", pg_data);
2235 snprintf(recovery_file, MAXPGPATH, "%s/recovery.conf", pg_data);
2236 snprintf(promote_file, MAXPGPATH, "%s/promote", pg_data);
2239 switch (ctl_command)
2244 case STATUS_COMMAND:
2253 case RESTART_COMMAND:
2256 case RELOAD_COMMAND:
2259 case PROMOTE_COMMAND:
2265 #if defined(WIN32) || defined(__CYGWIN__)
2266 case REGISTER_COMMAND:
2267 pgwin32_doRegister();
2269 case UNREGISTER_COMMAND:
2270 pgwin32_doUnregister();
2272 case RUN_AS_SERVICE_COMMAND:
2273 pgwin32_doRunAsService();