1 /*-------------------------------------------------------------------------
3 * pg_ctl --- start/stops/restarts the PostgreSQL server
5 * Portions Copyright (c) 1996-2011, 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 *pgdata_opt = NULL;
85 static char *post_opts = NULL;
86 static const char *progname;
87 static char *log_file = NULL;
88 static char *exec_path = NULL;
89 static char *register_servicename = "PostgreSQL"; /* FIXME: + version ID? */
90 static char *register_username = NULL;
91 static char *register_password = NULL;
92 static char *argv0 = NULL;
93 static bool allow_core_files = false;
94 static time_t start_time;
96 static char postopts_file[MAXPGPATH];
97 static char pid_file[MAXPGPATH];
98 static char backup_file[MAXPGPATH];
99 static char recovery_file[MAXPGPATH];
100 static char promote_file[MAXPGPATH];
102 #if defined(WIN32) || defined(__CYGWIN__)
103 static DWORD pgctl_start_type = SERVICE_AUTO_START;
104 static SERVICE_STATUS status;
105 static SERVICE_STATUS_HANDLE hStatus = (SERVICE_STATUS_HANDLE) 0;
106 static HANDLE shutdownHandles[2];
107 static pid_t postmasterPID = -1;
109 #define shutdownEvent shutdownHandles[0]
110 #define postmasterProcess shutdownHandles[1]
115 write_stderr(const char *fmt,...)
116 /* This extension allows gcc to check the format string for consistency with
117 the supplied arguments. */
118 __attribute__((format(PG_PRINTF_ATTRIBUTE, 1, 2)));
119 static void *pg_malloc(size_t size);
120 static char *xstrdup(const char *s);
121 static void do_advice(void);
122 static void do_help(void);
123 static void set_mode(char *modeopt);
124 static void set_sig(char *signame);
125 static void do_init(void);
126 static void do_start(void);
127 static void do_stop(void);
128 static void do_restart(void);
129 static void do_reload(void);
130 static void do_status(void);
131 static void do_promote(void);
132 static void do_kill(pgpid_t pid);
133 static void print_msg(const char *msg);
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 * routines to check memory allocations and fail noisily.
230 pg_malloc(size_t size)
234 result = malloc(size);
237 write_stderr(_("%s: out of memory\n"), progname);
245 xstrdup(const char *s)
252 write_stderr(_("%s: out of memory\n"), progname);
259 * Given an already-localized string, print it to stdout unless the
260 * user has specified that no messages should be printed.
263 print_msg(const char *msg)
278 pidf = fopen(pid_file, "r");
281 /* No pid file, not an error on startup */
286 write_stderr(_("%s: could not open PID file \"%s\": %s\n"),
287 progname, pid_file, strerror(errno));
291 if (fscanf(pidf, "%ld", &pid) != 1)
293 write_stderr(_("%s: invalid data in PID file \"%s\"\n"),
298 return (pgpid_t) pid;
303 * get the lines from a text file - return NULL if file can't be opened
306 readfile(const char *path)
316 if ((infile = fopen(path, "r")) == NULL)
319 /* pass over the file twice - the first time to size the result */
321 while ((c = fgetc(infile)) != EOF)
327 if (linelen > maxlength)
333 /* handle last line without a terminating newline (yuck) */
336 if (linelen > maxlength)
339 /* set up the result and the line buffer */
340 result = (char **) pg_malloc((nlines + 1) * sizeof(char *));
341 buffer = (char *) pg_malloc(maxlength + 1);
343 /* now reprocess the file and store the lines */
346 while (fgets(buffer, maxlength + 1, infile) != NULL)
347 result[nlines++] = xstrdup(buffer);
351 result[nlines] = NULL;
359 * start/test/stop routines
363 start_postmaster(void)
370 * Since there might be quotes to handle here, it is easier simply to pass
371 * everything to a shell to process them.
373 * XXX it would be better to fork and exec so that we would know the child
374 * postmaster's PID directly; then test_postmaster_connection could use
375 * the PID without having to rely on reading it back from the pidfile.
377 if (log_file != NULL)
378 snprintf(cmd, MAXPGPATH, SYSTEMQUOTE "\"%s\" %s%s < \"%s\" >> \"%s\" 2>&1 &" SYSTEMQUOTE,
379 exec_path, pgdata_opt, post_opts,
382 snprintf(cmd, MAXPGPATH, SYSTEMQUOTE "\"%s\" %s%s < \"%s\" 2>&1 &" SYSTEMQUOTE,
383 exec_path, pgdata_opt, post_opts, DEVNULL);
389 * On win32 we don't use system(). So we don't need to use & (which would
390 * be START /B on win32). However, we still call the shell (CMD.EXE) with
391 * it to handle redirection etc.
393 PROCESS_INFORMATION pi;
395 if (log_file != NULL)
396 snprintf(cmd, MAXPGPATH, "CMD /C " SYSTEMQUOTE "\"%s\" %s%s < \"%s\" >> \"%s\" 2>&1" SYSTEMQUOTE,
397 exec_path, pgdata_opt, post_opts, DEVNULL, log_file);
399 snprintf(cmd, MAXPGPATH, "CMD /C " SYSTEMQUOTE "\"%s\" %s%s < \"%s\" 2>&1" SYSTEMQUOTE,
400 exec_path, pgdata_opt, post_opts, DEVNULL);
402 if (!CreateRestrictedProcess(cmd, &pi, false))
403 return GetLastError();
404 CloseHandle(pi.hProcess);
405 CloseHandle(pi.hThread);
413 * Find the pgport and try a connection
415 * Note that the checkpoint parameter enables a Windows service control
416 * manager checkpoint, it's got nothing to do with database checkpoints!!
419 test_postmaster_connection(bool do_checkpoint)
421 PGPing ret = PQPING_NO_RESPONSE;
422 bool found_stale_pidfile = false;
424 char connstr[MAXPGPATH * 2 + 256];
427 /* if requested wait time is zero, return "still starting up" code */
428 if (wait_seconds <= 0)
429 return PQPING_REJECT;
433 for (i = 0; i < wait_seconds; i++)
435 /* Do we need a connection string? */
436 if (connstr[0] == '\0')
439 * The number of lines in postmaster.pid tells us several things:
442 * 0 lock file created but status not written
443 * 2 pre-9.1 server, shared memory not created
444 * 3 pre-9.1 server, shared memory created
445 * 5 9.1+ server, ports not opened
446 * 6 9.1+ server, shared memory not created
447 * 7 9.1+ server, shared memory created
449 * This code does not support pre-9.1 servers. On Unix machines
450 * we could consider extracting the port number from the shmem
451 * key, but that (a) is not robust, and (b) doesn't help with
452 * finding out the socket directory. And it wouldn't work anyway
455 * If we see less than 6 lines in postmaster.pid, just keep
461 /* Try to read the postmaster.pid file */
462 if ((optlines = readfile(pid_file)) != NULL &&
463 optlines[0] != NULL &&
464 optlines[1] != NULL &&
467 if (optlines[3] == NULL)
469 /* File is exactly three lines, must be pre-9.1 */
470 write_stderr(_("\n%s: -w option is not supported when starting a pre-9.1 server\n"),
472 return PQPING_NO_ATTEMPT;
474 else if (optlines[4] != NULL &&
477 /* File is complete enough for us, parse it */
482 * Make sanity checks. If it's for a standalone backend
483 * (negative PID), or the recorded start time is before
484 * pg_ctl started, then either we are looking at the wrong
485 * data directory, or this is a pre-existing pidfile that
486 * hasn't (yet?) been overwritten by our child postmaster.
487 * Allow 2 seconds slop for possible cross-process clock
490 pmpid = atol(optlines[LOCK_FILE_LINE_PID - 1]);
491 pmstart = atol(optlines[LOCK_FILE_LINE_START_TIME - 1]);
492 if (pmpid <= 0 || pmstart < start_time - 2)
495 * Set flag to report stale pidfile if it doesn't get
496 * overwritten before we give up waiting.
498 found_stale_pidfile = true;
503 * OK, seems to be a valid pidfile from our child.
508 char host_str[MAXPGPATH];
510 found_stale_pidfile = false;
511 pm_pid = (pgpid_t) pmpid;
514 * Extract port number and host string to use. Prefer
515 * using Unix socket if available.
517 portnum = atoi(optlines[LOCK_FILE_LINE_PORT - 1]);
518 sockdir = optlines[LOCK_FILE_LINE_SOCKET_DIR - 1];
519 hostaddr = optlines[LOCK_FILE_LINE_LISTEN_ADDR - 1];
522 * While unix_socket_directory can accept relative
523 * directories, libpq's host parameter must have a
524 * leading slash to indicate a socket directory. So,
525 * ignore sockdir if it's relative, and try to use TCP
528 if (sockdir[0] == '/')
529 strlcpy(host_str, sockdir, sizeof(host_str));
531 strlcpy(host_str, hostaddr, sizeof(host_str));
533 /* remove trailing newline */
534 if (strchr(host_str, '\n') != NULL)
535 *strchr(host_str, '\n') = '\0';
537 /* Fail if couldn't get either sockdir or host addr */
538 if (host_str[0] == '\0')
540 write_stderr(_("\n%s: -w option cannot use a relative socket directory specification\n"),
542 return PQPING_NO_ATTEMPT;
545 /* If postmaster is listening on "*", use localhost */
546 if (strcmp(host_str, "*") == 0)
547 strcpy(host_str, "localhost");
550 * We need to set connect_timeout otherwise on Windows
551 * the Service Control Manager (SCM) will probably
554 snprintf(connstr, sizeof(connstr),
555 "dbname=postgres port=%d host='%s' connect_timeout=5",
562 /* If we have a connection string, ping the server */
563 if (connstr[0] != '\0')
565 ret = PQping(connstr);
566 if (ret == PQPING_OK || ret == PQPING_NO_ATTEMPT)
571 * The postmaster should create postmaster.pid very soon after being
572 * started. If it's not there after we've waited 5 or more seconds,
573 * assume startup failed and give up waiting. (Note this covers both
574 * cases where the pidfile was never created, and where it was created
575 * and then removed during postmaster exit.) Also, if there *is* a
576 * file there but it appears stale, issue a suitable warning and give
583 if (stat(pid_file, &statbuf) != 0)
584 return PQPING_NO_RESPONSE;
586 if (found_stale_pidfile)
588 write_stderr(_("\n%s: this data directory appears to be running a pre-existing postmaster\n"),
590 return PQPING_NO_RESPONSE;
595 * If we've been able to identify the child postmaster's PID, check
596 * the process is still alive. This covers cases where the postmaster
597 * successfully created the pidfile but then crashed without removing
600 if (pm_pid > 0 && !postmaster_is_alive((pid_t) pm_pid))
601 return PQPING_NO_RESPONSE;
603 /* No response, or startup still in process; wait */
608 * Increment the wait hint by 6 secs (connection timeout + sleep)
609 * We must do this to indicate to the SCM that our startup time is
610 * changing, otherwise it'll usually send a stop signal after 20
611 * seconds, despite incrementing the checkpoint counter.
613 status.dwWaitHint += 6000;
614 status.dwCheckPoint++;
615 SetServiceStatus(hStatus, (LPSERVICE_STATUS) &status);
621 pg_usleep(1000000); /* 1 sec */
624 /* return result of last call to PQping */
629 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_CORE)
631 unlimit_core_size(void)
635 getrlimit(RLIMIT_CORE, &lim);
636 if (lim.rlim_max == 0)
638 write_stderr(_("%s: cannot set core file size limit; disallowed by hard limit\n"),
642 else if (lim.rlim_max == RLIM_INFINITY || lim.rlim_cur < lim.rlim_max)
644 lim.rlim_cur = lim.rlim_max;
645 setrlimit(RLIMIT_CORE, &lim);
653 if (post_opts == NULL)
655 post_opts = ""; /* default */
656 if (ctl_command == RESTART_COMMAND)
660 optlines = readfile(postopts_file);
661 if (optlines == NULL)
663 write_stderr(_("%s: could not read file \"%s\"\n"), progname, postopts_file);
666 else if (optlines[0] == NULL || optlines[1] != NULL)
668 write_stderr(_("%s: option file \"%s\" must have exactly one line\n"),
669 progname, postopts_file);
678 optline = optlines[0];
679 /* trim off line endings */
680 len = strcspn(optline, "\r\n");
684 * Are we at the first option, as defined by space and
687 if ((arg1 = strstr(optline, " \"")) != NULL)
689 *arg1 = '\0'; /* terminate so we get only program
691 post_opts = arg1 + 1; /* point past whitespace */
693 if (exec_path == NULL)
701 find_other_exec_or_die(const char *argv0, const char *target, const char *versionstr)
706 found_path = pg_malloc(MAXPGPATH);
708 if ((ret = find_other_exec(argv0, target, versionstr, found_path)) < 0)
710 char full_path[MAXPGPATH];
712 if (find_my_exec(argv0, full_path) < 0)
713 strlcpy(full_path, progname, sizeof(full_path));
716 write_stderr(_("The program \"%s\" is needed by %s "
717 "but was not found in the\n"
718 "same directory as \"%s\".\n"
719 "Check your installation.\n"),
720 target, progname, full_path);
722 write_stderr(_("The program \"%s\" was found by \"%s\"\n"
723 "but was not the same version as %s.\n"
724 "Check your installation.\n"),
725 target, full_path, progname);
737 if (exec_path == NULL)
738 exec_path = find_other_exec_or_die(argv0, "initdb", "initdb (PostgreSQL) " PG_VERSION "\n");
740 if (pgdata_opt == NULL)
743 if (post_opts == NULL)
747 snprintf(cmd, MAXPGPATH, SYSTEMQUOTE "\"%s\" %s%s" SYSTEMQUOTE,
748 exec_path, pgdata_opt, post_opts);
750 snprintf(cmd, MAXPGPATH, SYSTEMQUOTE "\"%s\" %s%s > \"%s\"" SYSTEMQUOTE,
751 exec_path, pgdata_opt, post_opts, DEVNULL);
753 if (system(cmd) != 0)
755 write_stderr(_("%s: database system initialization failed\n"), progname);
766 if (ctl_command != RESTART_COMMAND)
768 old_pid = get_pgpid();
770 write_stderr(_("%s: another server might be running; "
771 "trying to start server anyway\n"),
777 /* No -D or -D already added during server start */
778 if (ctl_command == RESTART_COMMAND || pgdata_opt == NULL)
781 if (exec_path == NULL)
782 exec_path = find_other_exec_or_die(argv0, "postgres", PG_BACKEND_VERSIONSTR);
784 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_CORE)
785 if (allow_core_files)
790 * If possible, tell the postmaster our parent shell's PID (see the
791 * comments in CreateLockFile() for motivation). Windows hasn't got
792 * getppid() unfortunately.
796 static char env_var[32];
798 snprintf(env_var, sizeof(env_var), "PG_GRANDPARENT_PID=%d",
804 exitcode = start_postmaster();
807 write_stderr(_("%s: could not start server: exit code was %d\n"),
814 print_msg(_("waiting for server to start..."));
816 switch (test_postmaster_connection(false))
819 print_msg(_(" done\n"));
820 print_msg(_("server started\n"));
823 print_msg(_(" stopped waiting\n"));
824 print_msg(_("server is still starting up\n"));
826 case PQPING_NO_RESPONSE:
827 print_msg(_(" stopped waiting\n"));
828 write_stderr(_("%s: could not start server\n"
829 "Examine the log output.\n"),
833 case PQPING_NO_ATTEMPT:
834 print_msg(_(" failed\n"));
835 write_stderr(_("%s: could not wait for server because of misconfiguration\n"),
841 print_msg(_("server starting\n"));
854 if (pid == 0) /* no pid file */
856 write_stderr(_("%s: PID file \"%s\" does not exist\n"), progname, pid_file);
857 write_stderr(_("Is server running?\n"));
860 else if (pid < 0) /* standalone backend, not postmaster */
863 write_stderr(_("%s: cannot stop server; "
864 "single-user server is running (PID: %ld)\n"),
869 if (kill((pid_t) pid, sig) != 0)
871 write_stderr(_("%s: could not send stop signal (PID: %ld): %s\n"), progname, pid,
878 print_msg(_("server shutting down\n"));
884 * If backup_label exists, an online backup is running. Warn the user
885 * that smart shutdown will wait for it to finish. However, if
886 * recovery.conf is also present, we're recovering from an online
887 * backup instead of performing one.
889 if (shutdown_mode == SMART_MODE &&
890 stat(backup_file, &statbuf) == 0 &&
891 stat(recovery_file, &statbuf) != 0)
893 print_msg(_("WARNING: online backup mode is active\n"
894 "Shutdown will not complete until pg_stop_backup() is called.\n\n"));
897 print_msg(_("waiting for server to shut down..."));
899 for (cnt = 0; cnt < wait_seconds; cnt++)
901 if ((pid = get_pgpid()) != 0)
904 pg_usleep(1000000); /* 1 sec */
910 if (pid != 0) /* pid file still exists */
912 print_msg(_(" failed\n"));
914 write_stderr(_("%s: server does not shut down\n"), progname);
915 if (shutdown_mode == SMART_MODE)
916 write_stderr(_("HINT: The \"-m fast\" option immediately disconnects sessions rather than\n"
917 "waiting for session-initiated disconnection.\n"));
920 print_msg(_(" done\n"));
922 print_msg(_("server stopped\n"));
928 * restart/reload routines
940 if (pid == 0) /* no pid file */
942 write_stderr(_("%s: PID file \"%s\" does not exist\n"),
944 write_stderr(_("Is server running?\n"));
945 write_stderr(_("starting server anyway\n"));
949 else if (pid < 0) /* standalone backend, not postmaster */
952 if (postmaster_is_alive((pid_t) pid))
954 write_stderr(_("%s: cannot restart server; "
955 "single-user server is running (PID: %ld)\n"),
957 write_stderr(_("Please terminate the single-user server and try again.\n"));
962 if (postmaster_is_alive((pid_t) pid))
964 if (kill((pid_t) pid, sig) != 0)
966 write_stderr(_("%s: could not send stop signal (PID: %ld): %s\n"), progname, pid,
972 * If backup_label exists, an online backup is running. Warn the user
973 * that smart shutdown will wait for it to finish. However, if
974 * recovery.conf is also present, we're recovering from an online
975 * backup instead of performing one.
977 if (shutdown_mode == SMART_MODE &&
978 stat(backup_file, &statbuf) == 0 &&
979 stat(recovery_file, &statbuf) != 0)
981 print_msg(_("WARNING: online backup mode is active\n"
982 "Shutdown will not complete until pg_stop_backup() is called.\n\n"));
985 print_msg(_("waiting for server to shut down..."));
987 /* always wait for restart */
989 for (cnt = 0; cnt < wait_seconds; cnt++)
991 if ((pid = get_pgpid()) != 0)
994 pg_usleep(1000000); /* 1 sec */
1000 if (pid != 0) /* pid file still exists */
1002 print_msg(_(" failed\n"));
1004 write_stderr(_("%s: server does not shut down\n"), progname);
1005 if (shutdown_mode == SMART_MODE)
1006 write_stderr(_("HINT: The \"-m fast\" option immediately disconnects sessions rather than\n"
1007 "waiting for session-initiated disconnection.\n"));
1011 print_msg(_(" done\n"));
1012 print_msg(_("server stopped\n"));
1016 write_stderr(_("%s: old server process (PID: %ld) seems to be gone\n"),
1018 write_stderr(_("starting server anyway\n"));
1030 if (pid == 0) /* no pid file */
1032 write_stderr(_("%s: PID file \"%s\" does not exist\n"), progname, pid_file);
1033 write_stderr(_("Is server running?\n"));
1036 else if (pid < 0) /* standalone backend, not postmaster */
1039 write_stderr(_("%s: cannot reload server; "
1040 "single-user server is running (PID: %ld)\n"),
1042 write_stderr(_("Please terminate the single-user server and try again.\n"));
1046 if (kill((pid_t) pid, sig) != 0)
1048 write_stderr(_("%s: could not send reload signal (PID: %ld): %s\n"),
1049 progname, pid, strerror(errno));
1053 print_msg(_("server signaled\n"));
1066 struct stat statbuf;
1070 if (pid == 0) /* no pid file */
1072 write_stderr(_("%s: PID file \"%s\" does not exist\n"), progname, pid_file);
1073 write_stderr(_("Is server running?\n"));
1076 else if (pid < 0) /* standalone backend, not postmaster */
1079 write_stderr(_("%s: cannot promote server; "
1080 "single-user server is running (PID: %ld)\n"),
1085 /* If recovery.conf doesn't exist, the server is not in standby mode */
1086 if (stat(recovery_file, &statbuf) != 0)
1088 write_stderr(_("%s: cannot promote server; "
1089 "server is not in standby mode\n"),
1094 if ((prmfile = fopen(promote_file, "w")) == NULL)
1096 write_stderr(_("%s: could not create promote signal file \"%s\": %s\n"),
1097 progname, promote_file, strerror(errno));
1100 if (fclose(prmfile))
1102 write_stderr(_("%s: could not write promote signal file \"%s\": %s\n"),
1103 progname, promote_file, strerror(errno));
1108 if (kill((pid_t) pid, sig) != 0)
1110 write_stderr(_("%s: could not send promote signal (PID: %ld): %s\n"),
1111 progname, pid, strerror(errno));
1112 if (unlink(promote_file) != 0)
1113 write_stderr(_("%s: could not remove promote signal file \"%s\": %s\n"),
1114 progname, promote_file, strerror(errno));
1118 print_msg(_("server promoting\n"));
1127 postmaster_is_alive(pid_t pid)
1130 * Test to see if the process is still there. Note that we do not
1131 * consider an EPERM failure to mean that the process is still there;
1132 * EPERM must mean that the given PID belongs to some other userid, and
1133 * considering the permissions on $PGDATA, that means it's not the
1134 * postmaster we are after.
1136 * Don't believe that our own PID or parent shell's PID is the postmaster,
1137 * either. (Windows hasn't got getppid(), though.)
1139 if (pid == getpid())
1142 if (pid == getppid())
1145 if (kill(pid, 0) == 0)
1156 if (pid != 0) /* 0 means no pid file */
1158 if (pid < 0) /* standalone backend */
1161 if (postmaster_is_alive((pid_t) pid))
1163 printf(_("%s: single-user server is running (PID: %ld)\n"),
1171 if (postmaster_is_alive((pid_t) pid))
1175 printf(_("%s: server is running (PID: %ld)\n"),
1178 optlines = readfile(postopts_file);
1179 if (optlines != NULL)
1180 for (; *optlines != NULL; optlines++)
1181 fputs(*optlines, stdout);
1186 printf(_("%s: no server running\n"), progname);
1193 do_kill(pgpid_t pid)
1195 if (kill((pid_t) pid, sig) != 0)
1197 write_stderr(_("%s: could not send signal %d (PID: %ld): %s\n"),
1198 progname, sig, pid, strerror(errno));
1203 #if defined(WIN32) || defined(__CYGWIN__)
1206 pgwin32_IsInstalled(SC_HANDLE hSCM)
1208 SC_HANDLE hService = OpenService(hSCM, register_servicename, SERVICE_QUERY_CONFIG);
1209 bool bResult = (hService != NULL);
1212 CloseServiceHandle(hService);
1217 pgwin32_CommandLine(bool registration)
1219 static char cmdLine[MAXPGPATH];
1223 char buf[MAXPGPATH];
1228 ret = find_my_exec(argv0, cmdLine);
1231 write_stderr(_("%s: could not find own program executable\n"), progname);
1237 ret = find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
1241 write_stderr(_("%s: could not find postgres program executable\n"), progname);
1247 /* need to convert to windows path */
1248 #if CYGWIN_VERSION_DLL_MAJOR >= 1007
1249 cygwin_conv_path(CCP_POSIX_TO_WIN_A, cmdLine, buf, sizeof(buf));
1251 cygwin_conv_to_full_win32_path(cmdLine, buf);
1253 strcpy(cmdLine, buf);
1258 if (pg_strcasecmp(cmdLine + strlen(cmdLine) - 4, ".exe"))
1260 /* If commandline does not end in .exe, append it */
1261 strcat(cmdLine, ".exe");
1263 strcat(cmdLine, " runservice -N \"");
1264 strcat(cmdLine, register_servicename);
1265 strcat(cmdLine, "\"");
1270 strcat(cmdLine, " -D \"");
1271 strcat(cmdLine, pg_data);
1272 strcat(cmdLine, "\"");
1275 if (registration && do_wait)
1276 strcat(cmdLine, " -w");
1278 if (registration && wait_seconds != DEFAULT_WAIT)
1280 sprintf(cmdLine + strlen(cmdLine), " -t %d", wait_seconds);
1282 if (registration && silent_mode)
1283 strcat(cmdLine, " -s");
1287 strcat(cmdLine, " ");
1289 strcat(cmdLine, " -o \"");
1290 strcat(cmdLine, post_opts);
1292 strcat(cmdLine, "\"");
1299 pgwin32_doRegister(void)
1302 SC_HANDLE hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
1306 write_stderr(_("%s: could not open service manager\n"), progname);
1309 if (pgwin32_IsInstalled(hSCM))
1311 CloseServiceHandle(hSCM);
1312 write_stderr(_("%s: service \"%s\" already registered\n"), progname, register_servicename);
1316 if ((hService = CreateService(hSCM, register_servicename, register_servicename,
1317 SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
1318 pgctl_start_type, SERVICE_ERROR_NORMAL,
1319 pgwin32_CommandLine(true),
1320 NULL, NULL, "RPCSS\0", register_username, register_password)) == NULL)
1322 CloseServiceHandle(hSCM);
1323 write_stderr(_("%s: could not register service \"%s\": error code %d\n"), progname, register_servicename, (int) GetLastError());
1326 CloseServiceHandle(hService);
1327 CloseServiceHandle(hSCM);
1331 pgwin32_doUnregister(void)
1334 SC_HANDLE hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
1338 write_stderr(_("%s: could not open service manager\n"), progname);
1341 if (!pgwin32_IsInstalled(hSCM))
1343 CloseServiceHandle(hSCM);
1344 write_stderr(_("%s: service \"%s\" not registered\n"), progname, register_servicename);
1348 if ((hService = OpenService(hSCM, register_servicename, DELETE)) == NULL)
1350 CloseServiceHandle(hSCM);
1351 write_stderr(_("%s: could not open service \"%s\": error code %d\n"), progname, register_servicename, (int) GetLastError());
1354 if (!DeleteService(hService))
1356 CloseServiceHandle(hService);
1357 CloseServiceHandle(hSCM);
1358 write_stderr(_("%s: could not unregister service \"%s\": error code %d\n"), progname, register_servicename, (int) GetLastError());
1361 CloseServiceHandle(hService);
1362 CloseServiceHandle(hSCM);
1366 pgwin32_SetServiceStatus(DWORD currentState)
1368 status.dwCurrentState = currentState;
1369 SetServiceStatus(hStatus, (LPSERVICE_STATUS) &status);
1373 pgwin32_ServiceHandler(DWORD request)
1377 case SERVICE_CONTROL_STOP:
1378 case SERVICE_CONTROL_SHUTDOWN:
1381 * We only need a short wait hint here as it just needs to wait
1382 * for the next checkpoint. They occur every 5 seconds during
1385 status.dwWaitHint = 10000;
1386 pgwin32_SetServiceStatus(SERVICE_STOP_PENDING);
1387 SetEvent(shutdownEvent);
1390 case SERVICE_CONTROL_PAUSE:
1391 /* Win32 config reloading */
1392 status.dwWaitHint = 5000;
1393 kill(postmasterPID, SIGHUP);
1396 /* FIXME: These could be used to replace other signals etc */
1397 case SERVICE_CONTROL_CONTINUE:
1398 case SERVICE_CONTROL_INTERROGATE:
1405 pgwin32_ServiceMain(DWORD argc, LPTSTR *argv)
1407 PROCESS_INFORMATION pi;
1409 DWORD check_point_start;
1411 /* Initialize variables */
1412 status.dwWin32ExitCode = S_OK;
1413 status.dwCheckPoint = 0;
1414 status.dwWaitHint = 60000;
1415 status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
1416 status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_PAUSE_CONTINUE;
1417 status.dwServiceSpecificExitCode = 0;
1418 status.dwCurrentState = SERVICE_START_PENDING;
1420 memset(&pi, 0, sizeof(pi));
1424 /* Register the control request handler */
1425 if ((hStatus = RegisterServiceCtrlHandler(register_servicename, pgwin32_ServiceHandler)) == (SERVICE_STATUS_HANDLE) 0)
1428 if ((shutdownEvent = CreateEvent(NULL, true, false, NULL)) == NULL)
1431 /* Start the postmaster */
1432 pgwin32_SetServiceStatus(SERVICE_START_PENDING);
1433 if (!CreateRestrictedProcess(pgwin32_CommandLine(false), &pi, true))
1435 pgwin32_SetServiceStatus(SERVICE_STOPPED);
1438 postmasterPID = pi.dwProcessId;
1439 postmasterProcess = pi.hProcess;
1440 CloseHandle(pi.hThread);
1444 write_eventlog(EVENTLOG_INFORMATION_TYPE, _("Waiting for server startup...\n"));
1445 if (test_postmaster_connection(true) != PQPING_OK)
1447 write_eventlog(EVENTLOG_ERROR_TYPE, _("Timed out waiting for server startup\n"));
1448 pgwin32_SetServiceStatus(SERVICE_STOPPED);
1451 write_eventlog(EVENTLOG_INFORMATION_TYPE, _("Server started and accepting connections\n"));
1455 * Save the checkpoint value as it might have been incremented in
1456 * test_postmaster_connection
1458 check_point_start = status.dwCheckPoint;
1460 pgwin32_SetServiceStatus(SERVICE_RUNNING);
1462 /* Wait for quit... */
1463 ret = WaitForMultipleObjects(2, shutdownHandles, FALSE, INFINITE);
1465 pgwin32_SetServiceStatus(SERVICE_STOP_PENDING);
1468 case WAIT_OBJECT_0: /* shutdown event */
1469 kill(postmasterPID, SIGINT);
1472 * Increment the checkpoint and try again Abort after 12
1473 * checkpoints as the postmaster has probably hung
1475 while (WaitForSingleObject(postmasterProcess, 5000) == WAIT_TIMEOUT && status.dwCheckPoint < 12)
1476 status.dwCheckPoint++;
1479 case (WAIT_OBJECT_0 + 1): /* postmaster went down */
1483 /* shouldn't get here? */
1487 CloseHandle(shutdownEvent);
1488 CloseHandle(postmasterProcess);
1490 pgwin32_SetServiceStatus(SERVICE_STOPPED);
1494 pgwin32_doRunAsService(void)
1496 SERVICE_TABLE_ENTRY st[] = {{register_servicename, pgwin32_ServiceMain},
1499 if (StartServiceCtrlDispatcher(st) == 0)
1501 write_stderr(_("%s: could not start service \"%s\": error code %d\n"), progname, register_servicename, (int) GetLastError());
1508 * Mingw headers are incomplete, and so are the libraries. So we have to load
1509 * a whole lot of API functions dynamically. Since we have to do this anyway,
1510 * also load the couple of functions that *do* exist in minwg headers but not
1511 * on NT4. That way, we don't break on NT4.
1513 typedef BOOL (WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE);
1514 typedef BOOL (WINAPI * __IsProcessInJob) (HANDLE, HANDLE, PBOOL);
1515 typedef HANDLE (WINAPI * __CreateJobObject) (LPSECURITY_ATTRIBUTES, LPCTSTR);
1516 typedef BOOL (WINAPI * __SetInformationJobObject) (HANDLE, JOBOBJECTINFOCLASS, LPVOID, DWORD);
1517 typedef BOOL (WINAPI * __AssignProcessToJobObject) (HANDLE, HANDLE);
1518 typedef BOOL (WINAPI * __QueryInformationJobObject) (HANDLE, JOBOBJECTINFOCLASS, LPVOID, DWORD, LPDWORD);
1520 /* Windows API define missing from some versions of MingW headers */
1521 #ifndef DISABLE_MAX_PRIVILEGE
1522 #define DISABLE_MAX_PRIVILEGE 0x1
1526 * Create a restricted token, a job object sandbox, and execute the specified
1529 * Returns 0 on success, non-zero on failure, same as CreateProcess().
1531 * On NT4, or any other system not containing the required functions, will
1532 * launch the process under the current token without doing any modifications.
1534 * NOTE! Job object will only work when running as a service, because it's
1535 * automatically destroyed when pg_ctl exits.
1538 CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, bool as_service)
1544 HANDLE restrictedToken;
1545 SID_IDENTIFIER_AUTHORITY NtAuthority = {SECURITY_NT_AUTHORITY};
1546 SID_AND_ATTRIBUTES dropSids[2];
1548 /* Functions loaded dynamically */
1549 __CreateRestrictedToken _CreateRestrictedToken = NULL;
1550 __IsProcessInJob _IsProcessInJob = NULL;
1551 __CreateJobObject _CreateJobObject = NULL;
1552 __SetInformationJobObject _SetInformationJobObject = NULL;
1553 __AssignProcessToJobObject _AssignProcessToJobObject = NULL;
1554 __QueryInformationJobObject _QueryInformationJobObject = NULL;
1555 HANDLE Kernel32Handle;
1556 HANDLE Advapi32Handle;
1558 ZeroMemory(&si, sizeof(si));
1561 Advapi32Handle = LoadLibrary("ADVAPI32.DLL");
1562 if (Advapi32Handle != NULL)
1564 _CreateRestrictedToken = (__CreateRestrictedToken) GetProcAddress(Advapi32Handle, "CreateRestrictedToken");
1567 if (_CreateRestrictedToken == NULL)
1570 * NT4 doesn't have CreateRestrictedToken, so just call ordinary
1573 write_stderr("WARNING: cannot create restricted tokens on this platform\n");
1574 if (Advapi32Handle != NULL)
1575 FreeLibrary(Advapi32Handle);
1576 return CreateProcess(NULL, cmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, processInfo);
1579 /* Open the current token to use as a base for the restricted one */
1580 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken))
1582 write_stderr("Failed to open process token: %lu\n", GetLastError());
1586 /* Allocate list of SIDs to remove */
1587 ZeroMemory(&dropSids, sizeof(dropSids));
1588 if (!AllocateAndInitializeSid(&NtAuthority, 2,
1589 SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0,
1590 0, &dropSids[0].Sid) ||
1591 !AllocateAndInitializeSid(&NtAuthority, 2,
1592 SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0,
1593 0, &dropSids[1].Sid))
1595 write_stderr("Failed to allocate SIDs: %lu\n", GetLastError());
1599 b = _CreateRestrictedToken(origToken,
1600 DISABLE_MAX_PRIVILEGE,
1601 sizeof(dropSids) / sizeof(dropSids[0]),
1607 FreeSid(dropSids[1].Sid);
1608 FreeSid(dropSids[0].Sid);
1609 CloseHandle(origToken);
1610 FreeLibrary(Advapi32Handle);
1614 write_stderr("Failed to create restricted token: %lu\n", GetLastError());
1619 AddUserToTokenDacl(restrictedToken);
1622 r = CreateProcessAsUser(restrictedToken, NULL, cmd, NULL, NULL, TRUE, CREATE_SUSPENDED, NULL, NULL, &si, processInfo);
1624 Kernel32Handle = LoadLibrary("KERNEL32.DLL");
1625 if (Kernel32Handle != NULL)
1627 _IsProcessInJob = (__IsProcessInJob) GetProcAddress(Kernel32Handle, "IsProcessInJob");
1628 _CreateJobObject = (__CreateJobObject) GetProcAddress(Kernel32Handle, "CreateJobObjectA");
1629 _SetInformationJobObject = (__SetInformationJobObject) GetProcAddress(Kernel32Handle, "SetInformationJobObject");
1630 _AssignProcessToJobObject = (__AssignProcessToJobObject) GetProcAddress(Kernel32Handle, "AssignProcessToJobObject");
1631 _QueryInformationJobObject = (__QueryInformationJobObject) GetProcAddress(Kernel32Handle, "QueryInformationJobObject");
1634 /* Verify that we found all functions */
1635 if (_IsProcessInJob == NULL || _CreateJobObject == NULL || _SetInformationJobObject == NULL || _AssignProcessToJobObject == NULL || _QueryInformationJobObject == NULL)
1638 * IsProcessInJob() is not available on < WinXP, so there is no need
1639 * to log the error every time in that case
1643 osv.dwOSVersionInfoSize = sizeof(osv);
1644 if (!GetVersionEx(&osv) || /* could not get version */
1645 (osv.dwMajorVersion == 5 && osv.dwMinorVersion > 0) || /* 5.1=xp, 5.2=2003, etc */
1646 osv.dwMajorVersion > 5) /* anything newer should have the API */
1649 * Log error if we can't get version, or if we're on WinXP/2003 or
1652 write_stderr("WARNING: could not locate all job object functions in system API\n");
1658 if (_IsProcessInJob(processInfo->hProcess, NULL, &inJob))
1663 * Job objects are working, and the new process isn't in one,
1664 * so we can create one safely. If any problems show up when
1665 * setting it, we're going to ignore them.
1670 sprintf(jobname, "PostgreSQL_%lu", processInfo->dwProcessId);
1672 job = _CreateJobObject(NULL, jobname);
1675 JOBOBJECT_BASIC_LIMIT_INFORMATION basicLimit;
1676 JOBOBJECT_BASIC_UI_RESTRICTIONS uiRestrictions;
1677 JOBOBJECT_SECURITY_LIMIT_INFORMATION securityLimit;
1680 ZeroMemory(&basicLimit, sizeof(basicLimit));
1681 ZeroMemory(&uiRestrictions, sizeof(uiRestrictions));
1682 ZeroMemory(&securityLimit, sizeof(securityLimit));
1684 basicLimit.LimitFlags = JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION | JOB_OBJECT_LIMIT_PRIORITY_CLASS;
1685 basicLimit.PriorityClass = NORMAL_PRIORITY_CLASS;
1686 _SetInformationJobObject(job, JobObjectBasicLimitInformation, &basicLimit, sizeof(basicLimit));
1688 uiRestrictions.UIRestrictionsClass = JOB_OBJECT_UILIMIT_DESKTOP | JOB_OBJECT_UILIMIT_DISPLAYSETTINGS |
1689 JOB_OBJECT_UILIMIT_EXITWINDOWS | JOB_OBJECT_UILIMIT_READCLIPBOARD |
1690 JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS | JOB_OBJECT_UILIMIT_WRITECLIPBOARD;
1694 osv.dwOSVersionInfoSize = sizeof(osv);
1695 if (!GetVersionEx(&osv) ||
1696 osv.dwMajorVersion < 6 ||
1697 (osv.dwMajorVersion == 6 && osv.dwMinorVersion == 0))
1700 * On Windows 7 (and presumably later),
1701 * JOB_OBJECT_UILIMIT_HANDLES prevents us from
1702 * starting as a service. So we only enable it on
1703 * Vista and earlier (version <= 6.0)
1705 uiRestrictions.UIRestrictionsClass |= JOB_OBJECT_UILIMIT_HANDLES;
1708 _SetInformationJobObject(job, JobObjectBasicUIRestrictions, &uiRestrictions, sizeof(uiRestrictions));
1710 securityLimit.SecurityLimitFlags = JOB_OBJECT_SECURITY_NO_ADMIN | JOB_OBJECT_SECURITY_ONLY_TOKEN;
1711 securityLimit.JobToken = restrictedToken;
1712 _SetInformationJobObject(job, JobObjectSecurityLimitInformation, &securityLimit, sizeof(securityLimit));
1714 _AssignProcessToJobObject(job, processInfo->hProcess);
1721 CloseHandle(restrictedToken);
1723 ResumeThread(processInfo->hThread);
1725 FreeLibrary(Kernel32Handle);
1728 * We intentionally don't close the job object handle, because we want the
1729 * object to live on until pg_ctl shuts down.
1738 write_stderr(_("Try \"%s --help\" for more information.\n"), progname);
1746 printf(_("%s is a utility to initialize, start, stop, or control a PostgreSQL server.\n\n"), progname);
1747 printf(_("Usage:\n"));
1748 printf(_(" %s init[db] [-D DATADIR] [-s] [-o \"OPTIONS\"]\n"), progname);
1749 printf(_(" %s start [-w] [-t SECS] [-D DATADIR] [-s] [-l FILENAME] [-o \"OPTIONS\"]\n"), progname);
1750 printf(_(" %s stop [-W] [-t SECS] [-D DATADIR] [-s] [-m SHUTDOWN-MODE]\n"), progname);
1751 printf(_(" %s restart [-w] [-t SECS] [-D DATADIR] [-s] [-m SHUTDOWN-MODE]\n"
1752 " [-o \"OPTIONS\"]\n"), progname);
1753 printf(_(" %s reload [-D DATADIR] [-s]\n"), progname);
1754 printf(_(" %s status [-D DATADIR]\n"), progname);
1755 printf(_(" %s promote [-D DATADIR] [-s]\n"), progname);
1756 printf(_(" %s kill SIGNALNAME PID\n"), progname);
1757 #if defined(WIN32) || defined(__CYGWIN__)
1758 printf(_(" %s register [-N SERVICENAME] [-U USERNAME] [-P PASSWORD] [-D DATADIR]\n"
1759 " [-S START-TYPE] [-w] [-t SECS] [-o \"OPTIONS\"]\n"), progname);
1760 printf(_(" %s unregister [-N SERVICENAME]\n"), progname);
1763 printf(_("\nCommon options:\n"));
1764 printf(_(" -D, --pgdata DATADIR location of the database storage area\n"));
1765 printf(_(" -s, --silent only print errors, no informational messages\n"));
1766 printf(_(" -t SECS seconds to wait when using -w option\n"));
1767 printf(_(" -w wait until operation completes\n"));
1768 printf(_(" -W do not wait until operation completes\n"));
1769 printf(_(" --help show this help, then exit\n"));
1770 printf(_(" --version output version information, then exit\n"));
1771 printf(_("(The default is to wait for shutdown, but not for start or restart.)\n\n"));
1772 printf(_("If the -D option is omitted, the environment variable PGDATA is used.\n"));
1774 printf(_("\nOptions for start or restart:\n"));
1775 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_CORE)
1776 printf(_(" -c, --core-files allow postgres to produce core files\n"));
1778 printf(_(" -c, --core-files not applicable on this platform\n"));
1780 printf(_(" -l, --log FILENAME write (or append) server log to FILENAME\n"));
1781 printf(_(" -o OPTIONS command line options to pass to postgres\n"
1782 " (PostgreSQL server executable) or initdb\n"));
1783 printf(_(" -p PATH-TO-POSTGRES normally not necessary\n"));
1784 printf(_("\nOptions for stop or restart:\n"));
1785 printf(_(" -m SHUTDOWN-MODE can be \"smart\", \"fast\", or \"immediate\"\n"));
1787 printf(_("\nShutdown modes are:\n"));
1788 printf(_(" smart quit after all clients have disconnected\n"));
1789 printf(_(" fast quit directly, with proper shutdown\n"));
1790 printf(_(" immediate quit without complete shutdown; will lead to recovery on restart\n"));
1792 printf(_("\nAllowed signal names for kill:\n"));
1793 printf(" HUP INT QUIT ABRT TERM USR1 USR2\n");
1795 #if defined(WIN32) || defined(__CYGWIN__)
1796 printf(_("\nOptions for register and unregister:\n"));
1797 printf(_(" -N SERVICENAME service name with which to register PostgreSQL server\n"));
1798 printf(_(" -P PASSWORD password of account to register PostgreSQL server\n"));
1799 printf(_(" -U USERNAME user name of account to register PostgreSQL server\n"));
1800 printf(_(" -S START-TYPE service start type to register PostgreSQL server\n"));
1802 printf(_("\nStart types are:\n"));
1803 printf(_(" auto start service automatically during system startup (default)\n"));
1804 printf(_(" demand start service on demand\n"));
1807 printf(_("\nReport bugs to <pgsql-bugs@postgresql.org>.\n"));
1813 set_mode(char *modeopt)
1815 if (strcmp(modeopt, "s") == 0 || strcmp(modeopt, "smart") == 0)
1817 shutdown_mode = SMART_MODE;
1820 else if (strcmp(modeopt, "f") == 0 || strcmp(modeopt, "fast") == 0)
1822 shutdown_mode = FAST_MODE;
1825 else if (strcmp(modeopt, "i") == 0 || strcmp(modeopt, "immediate") == 0)
1827 shutdown_mode = IMMEDIATE_MODE;
1832 write_stderr(_("%s: unrecognized shutdown mode \"%s\"\n"), progname, modeopt);
1841 set_sig(char *signame)
1843 if (!strcmp(signame, "HUP"))
1845 else if (!strcmp(signame, "INT"))
1847 else if (!strcmp(signame, "QUIT"))
1849 else if (!strcmp(signame, "ABRT"))
1853 * probably should NOT provide SIGKILL
1855 * else if (!strcmp(signame,"KILL")) sig = SIGKILL;
1857 else if (!strcmp(signame, "TERM"))
1859 else if (!strcmp(signame, "USR1"))
1861 else if (!strcmp(signame, "USR2"))
1865 write_stderr(_("%s: unrecognized signal name \"%s\"\n"), progname, signame);
1872 #if defined(WIN32) || defined(__CYGWIN__)
1874 set_starttype(char *starttypeopt)
1876 if (strcmp(starttypeopt, "a") == 0 || strcmp(starttypeopt, "auto") == 0)
1877 pgctl_start_type = SERVICE_AUTO_START;
1878 else if (strcmp(starttypeopt, "d") == 0 || strcmp(starttypeopt, "demand") == 0)
1879 pgctl_start_type = SERVICE_DEMAND_START;
1882 write_stderr(_("%s: unrecognized start type \"%s\"\n"), progname, starttypeopt);
1891 main(int argc, char **argv)
1893 static struct option long_options[] = {
1894 {"help", no_argument, NULL, '?'},
1895 {"version", no_argument, NULL, 'V'},
1896 {"log", required_argument, NULL, 'l'},
1897 {"mode", required_argument, NULL, 'm'},
1898 {"pgdata", required_argument, NULL, 'D'},
1899 {"silent", no_argument, NULL, 's'},
1900 {"timeout", required_argument, NULL, 't'},
1901 {"core-files", no_argument, NULL, 'c'},
1907 pgpid_t killproc = 0;
1909 #if defined(WIN32) || defined(__CYGWIN__)
1910 setvbuf(stderr, NULL, _IONBF, 0);
1913 progname = get_progname(argv[0]);
1914 set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_ctl"));
1915 start_time = time(NULL);
1918 * save argv[0] so do_start() can look for the postmaster if necessary. we
1919 * don't look for postmaster here because in many cases we won't need it.
1923 umask(S_IRWXG | S_IRWXO);
1925 /* support --help and --version even if invoked as root */
1928 if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0 ||
1929 strcmp(argv[1], "-?") == 0)
1934 else if (strcmp(argv[1], "-V") == 0 || strcmp(argv[1], "--version") == 0)
1936 puts("pg_ctl (PostgreSQL) " PG_VERSION);
1942 * Disallow running as root, to forestall any possible security holes.
1947 write_stderr(_("%s: cannot be run as root\n"
1948 "Please log in (using, e.g., \"su\") as the "
1949 "(unprivileged) user that will\n"
1950 "own the server process.\n"),
1957 * 'Action' can be before or after args so loop over both. Some
1958 * getopt_long() implementations will reorder argv[] to place all flags
1959 * first (GNU?), but we don't rely on it. Our /port version doesn't do
1964 /* process command-line options */
1965 while (optind < argc)
1967 while ((c = getopt_long(argc, argv, "cD:l:m:N:o:p:P:sS:t:U:wW", long_options, &option_index)) != -1)
1974 char *env_var = pg_malloc(strlen(optarg) + 8);
1976 pgdata_D = xstrdup(optarg);
1977 canonicalize_path(pgdata_D);
1978 snprintf(env_var, strlen(optarg) + 8, "PGDATA=%s",
1983 * We could pass PGDATA just in an environment
1984 * variable but we do -D too for clearer postmaster
1987 pgdata_opt = pg_malloc(strlen(pgdata_D) + 7);
1988 snprintf(pgdata_opt, strlen(pgdata_D) + 7,
1994 log_file = xstrdup(optarg);
2000 register_servicename = xstrdup(optarg);
2003 post_opts = xstrdup(optarg);
2006 exec_path = xstrdup(optarg);
2009 register_password = xstrdup(optarg);
2015 #if defined(WIN32) || defined(__CYGWIN__)
2016 set_starttype(optarg);
2018 write_stderr(_("%s: -S option not supported on this platform\n"),
2024 wait_seconds = atoi(optarg);
2027 if (strchr(optarg, '\\'))
2028 register_username = xstrdup(optarg);
2030 /* Prepend .\ for local accounts */
2032 register_username = malloc(strlen(optarg) + 3);
2033 if (!register_username)
2035 write_stderr(_("%s: out of memory\n"), progname);
2038 strcpy(register_username, ".\\");
2039 strcat(register_username, optarg);
2051 allow_core_files = true;
2054 /* getopt_long already issued a suitable error message */
2060 /* Process an action */
2063 if (ctl_command != NO_COMMAND)
2065 write_stderr(_("%s: too many command-line arguments (first is \"%s\")\n"), progname, argv[optind]);
2070 if (strcmp(argv[optind], "init") == 0
2071 || strcmp(argv[optind], "initdb") == 0)
2072 ctl_command = INIT_COMMAND;
2073 else if (strcmp(argv[optind], "start") == 0)
2074 ctl_command = START_COMMAND;
2075 else if (strcmp(argv[optind], "stop") == 0)
2076 ctl_command = STOP_COMMAND;
2077 else if (strcmp(argv[optind], "restart") == 0)
2078 ctl_command = RESTART_COMMAND;
2079 else if (strcmp(argv[optind], "reload") == 0)
2080 ctl_command = RELOAD_COMMAND;
2081 else if (strcmp(argv[optind], "status") == 0)
2082 ctl_command = STATUS_COMMAND;
2083 else if (strcmp(argv[optind], "promote") == 0)
2084 ctl_command = PROMOTE_COMMAND;
2085 else if (strcmp(argv[optind], "kill") == 0)
2087 if (argc - optind < 3)
2089 write_stderr(_("%s: missing arguments for kill mode\n"), progname);
2093 ctl_command = KILL_COMMAND;
2094 set_sig(argv[++optind]);
2095 killproc = atol(argv[++optind]);
2097 #if defined(WIN32) || defined(__CYGWIN__)
2098 else if (strcmp(argv[optind], "register") == 0)
2099 ctl_command = REGISTER_COMMAND;
2100 else if (strcmp(argv[optind], "unregister") == 0)
2101 ctl_command = UNREGISTER_COMMAND;
2102 else if (strcmp(argv[optind], "runservice") == 0)
2103 ctl_command = RUN_AS_SERVICE_COMMAND;
2107 write_stderr(_("%s: unrecognized operation mode \"%s\"\n"), progname, argv[optind]);
2115 if (ctl_command == NO_COMMAND)
2117 write_stderr(_("%s: no operation specified\n"), progname);
2122 /* Note we put any -D switch into the env var above */
2123 pg_data = getenv("PGDATA");
2126 pg_data = xstrdup(pg_data);
2127 canonicalize_path(pg_data);
2130 if (pg_data == NULL &&
2131 ctl_command != KILL_COMMAND && ctl_command != UNREGISTER_COMMAND)
2133 write_stderr(_("%s: no database directory specified and environment variable PGDATA unset\n"),
2141 switch (ctl_command)
2143 case RESTART_COMMAND:
2155 if (ctl_command == RELOAD_COMMAND)
2163 snprintf(postopts_file, MAXPGPATH, "%s/postmaster.opts", pg_data);
2164 snprintf(pid_file, MAXPGPATH, "%s/postmaster.pid", pg_data);
2165 snprintf(backup_file, MAXPGPATH, "%s/backup_label", pg_data);
2166 snprintf(recovery_file, MAXPGPATH, "%s/recovery.conf", pg_data);
2167 snprintf(promote_file, MAXPGPATH, "%s/promote", pg_data);
2170 switch (ctl_command)
2175 case STATUS_COMMAND:
2184 case RESTART_COMMAND:
2187 case RELOAD_COMMAND:
2190 case PROMOTE_COMMAND:
2196 #if defined(WIN32) || defined(__CYGWIN__)
2197 case REGISTER_COMMAND:
2198 pgwin32_doRegister();
2200 case UNREGISTER_COMMAND:
2201 pgwin32_doUnregister();
2203 case RUN_AS_SERVICE_COMMAND:
2204 pgwin32_doRunAsService();