1 /*-------------------------------------------------------------------------
3 * pg_ctl --- start/stops/restarts the PostgreSQL server
5 * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
7 * $PostgreSQL: pgsql/src/bin/pg_ctl/pg_ctl.c,v 1.97 2008/04/23 13:44:59 mha Exp $
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 0x0500
20 #include "postgres_fe.h"
25 #include <sys/types.h>
29 #ifdef HAVE_SYS_RESOURCE_H
31 #include <sys/resource.h>
34 #include "libpq/pqsignal.h"
35 #include "getopt_long.h"
36 #include "miscadmin.h"
38 #if defined(__CYGWIN__)
39 #include <sys/cygwin.h>
41 /* Cygwin defines WIN32 in windows.h, but we don't want it. */
45 #ifndef HAVE_INT_OPTRESET
49 /* PID can be negative for standalone backend */
72 RUN_AS_SERVICE_COMMAND
75 #define DEFAULT_WAIT 60
77 static bool do_wait = false;
78 static bool wait_set = false;
79 static int wait_seconds = DEFAULT_WAIT;
80 static bool silent_mode = false;
81 static ShutdownMode shutdown_mode = SMART_MODE;
82 static int sig = SIGTERM; /* default */
83 static CtlCommand ctl_command = NO_COMMAND;
84 static char *pg_data = 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 *postgres_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;
97 write_stderr(const char *fmt,...)
98 /* This extension allows gcc to check the format string for consistency with
99 the supplied arguments. */
100 __attribute__((format(printf, 1, 2)));
101 static void *pg_malloc(size_t size);
102 static char *xstrdup(const char *s);
103 static void do_advice(void);
104 static void do_help(void);
105 static void set_mode(char *modeopt);
106 static void set_sig(char *signame);
107 static void do_start(void);
108 static void do_stop(void);
109 static void do_restart(void);
110 static void do_reload(void);
111 static void do_status(void);
112 static void do_kill(pgpid_t pid);
113 static void print_msg(const char *msg);
115 #if defined(WIN32) || defined(__CYGWIN__)
116 static bool pgwin32_IsInstalled(SC_HANDLE);
117 static char *pgwin32_CommandLine(bool);
118 static void pgwin32_doRegister(void);
119 static void pgwin32_doUnregister(void);
120 static void pgwin32_SetServiceStatus(DWORD);
121 static void WINAPI pgwin32_ServiceHandler(DWORD);
122 static void WINAPI pgwin32_ServiceMain(DWORD, LPTSTR *);
123 static void pgwin32_doRunAsService(void);
124 static int CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION * processInfo);
126 static SERVICE_STATUS status;
127 static SERVICE_STATUS_HANDLE hStatus = (SERVICE_STATUS_HANDLE) 0;
128 static HANDLE shutdownHandles[2];
129 static pid_t postmasterPID = -1;
131 #define shutdownEvent shutdownHandles[0]
132 #define postmasterProcess shutdownHandles[1]
135 static pgpid_t get_pgpid(void);
136 static char **readfile(const char *path);
137 static int start_postmaster(void);
138 static void read_post_opts(void);
140 static bool test_postmaster_connection(bool);
141 static bool postmaster_is_alive(pid_t pid);
143 static char def_postopts_file[MAXPGPATH];
144 static char postopts_file[MAXPGPATH];
145 static char pid_file[MAXPGPATH];
146 static char conf_file[MAXPGPATH];
147 static char backup_file[MAXPGPATH];
149 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_CORE)
150 static void unlimit_core_size(void);
154 #if defined(WIN32) || defined(__CYGWIN__)
156 write_eventlog(int level, const char *line)
158 static HANDLE evtHandle = INVALID_HANDLE_VALUE;
160 if (evtHandle == INVALID_HANDLE_VALUE)
162 evtHandle = RegisterEventSource(NULL, "PostgreSQL");
163 if (evtHandle == NULL)
165 evtHandle = INVALID_HANDLE_VALUE;
170 ReportEvent(evtHandle,
173 0, /* All events are Id 0 */
183 * Write errors to stderr (or by equal means when stderr is
187 write_stderr(const char *fmt,...)
192 #if !defined(WIN32) && !defined(__CYGWIN__)
193 /* On Unix, we just fprintf to stderr */
194 vfprintf(stderr, fmt, ap);
198 * On Win32, we print to stderr if running on a console, or write to
199 * eventlog if running as a service
201 if (!isatty(fileno(stderr))) /* Running as a service */
203 char errbuf[2048]; /* Arbitrary size? */
205 vsnprintf(errbuf, sizeof(errbuf), fmt, ap);
207 write_eventlog(EVENTLOG_ERROR_TYPE, errbuf);
210 /* Not running as service, write to stderr */
211 vfprintf(stderr, fmt, ap);
217 * routines to check memory allocations and fail noisily.
221 pg_malloc(size_t size)
225 result = malloc(size);
228 write_stderr(_("%s: out of memory\n"), progname);
236 xstrdup(const char *s)
243 write_stderr(_("%s: out of memory\n"), progname);
250 * Given an already-localized string, print it to stdout unless the
251 * user has specified that no messages should be printed.
254 print_msg(const char *msg)
269 pidf = fopen(pid_file, "r");
272 /* No pid file, not an error on startup */
277 write_stderr(_("%s: could not open PID file \"%s\": %s\n"),
278 progname, pid_file, strerror(errno));
282 if (fscanf(pidf, "%ld", &pid) != 1)
284 write_stderr(_("%s: invalid data in PID file \"%s\"\n"),
289 return (pgpid_t) pid;
294 * get the lines from a text file - return NULL if file can't be opened
297 readfile(const char *path)
307 if ((infile = fopen(path, "r")) == NULL)
310 /* pass over the file twice - the first time to size the result */
312 while ((c = fgetc(infile)) != EOF)
318 if (linelen > maxlength)
324 /* handle last line without a terminating newline (yuck) */
327 if (linelen > maxlength)
330 /* set up the result and the line buffer */
331 result = (char **) pg_malloc((nlines + 1) * sizeof(char *));
332 buffer = (char *) pg_malloc(maxlength + 1);
334 /* now reprocess the file and store the lines */
337 while (fgets(buffer, maxlength + 1, infile) != NULL)
338 result[nlines++] = xstrdup(buffer);
342 result[nlines] = NULL;
350 * start/test/stop routines
354 start_postmaster(void)
361 * Since there might be quotes to handle here, it is easier simply to pass
362 * everything to a shell to process them.
364 if (log_file != NULL)
365 snprintf(cmd, MAXPGPATH, "%s\"%s\" %s%s < \"%s\" >> \"%s\" 2>&1 &%s",
366 SYSTEMQUOTE, postgres_path, pgdata_opt, post_opts,
367 DEVNULL, log_file, SYSTEMQUOTE);
369 snprintf(cmd, MAXPGPATH, "%s\"%s\" %s%s < \"%s\" 2>&1 &%s",
370 SYSTEMQUOTE, postgres_path, pgdata_opt, post_opts,
371 DEVNULL, SYSTEMQUOTE);
377 * On win32 we don't use system(). So we don't need to use & (which would
378 * be START /B on win32). However, we still call the shell (CMD.EXE) with
379 * it to handle redirection etc.
381 PROCESS_INFORMATION pi;
383 if (log_file != NULL)
384 snprintf(cmd, MAXPGPATH, "CMD /C %s\"%s\" %s%s < \"%s\" >> \"%s\" 2>&1%s",
385 SYSTEMQUOTE, postgres_path, pgdata_opt, post_opts,
386 DEVNULL, log_file, SYSTEMQUOTE);
388 snprintf(cmd, MAXPGPATH, "CMD /C %s\"%s\" %s%s < \"%s\" 2>&1%s",
389 SYSTEMQUOTE, postgres_path, pgdata_opt, post_opts,
390 DEVNULL, SYSTEMQUOTE);
392 if (!CreateRestrictedProcess(cmd, &pi))
393 return GetLastError();
394 CloseHandle(pi.hProcess);
395 CloseHandle(pi.hThread);
403 * Find the pgport and try a connection
404 * Note that the checkpoint parameter enables a Windows service control
405 * manager checkpoint, it's got nothing to do with database checkpoints!!
408 test_postmaster_connection(bool do_checkpoint)
411 bool success = false;
416 char connstr[128]; /* Should be way more than enough! */
421 * Look in post_opts for a -p switch.
423 * This parsing code is not amazingly bright; it could for instance
424 * get fooled if ' -p' occurs within a quoted argument value. Given
425 * that few people pass complicated settings in post_opts, it's
426 * probably good enough.
428 for (p = post_opts; *p;)
430 /* advance past whitespace */
431 while (isspace((unsigned char) *p))
434 if (strncmp(p, "-p", 2) == 0)
437 /* advance past any whitespace/quoting */
438 while (isspace((unsigned char) *p) || *p == '\'' || *p == '"')
440 /* find end of value (not including any ending quote!) */
443 !(isspace((unsigned char) *q) || *q == '\'' || *q == '"'))
445 /* and save the argument value */
446 strlcpy(portstr, p, Min((q - p) + 1, sizeof(portstr)));
447 /* keep looking, maybe there is another -p */
450 /* Advance to next whitespace */
451 while (*p && !isspace((unsigned char) *p))
456 * Search config file for a 'port' option.
458 * This parsing code isn't amazingly bright either, but it should be
459 * okay for valid port settings.
465 optlines = readfile(conf_file);
466 if (optlines != NULL)
468 for (; *optlines != NULL; optlines++)
472 while (isspace((unsigned char) *p))
474 if (strncmp(p, "port", 4) != 0)
477 while (isspace((unsigned char) *p))
482 /* advance past any whitespace/quoting */
483 while (isspace((unsigned char) *p) || *p == '\'' || *p == '"')
485 /* find end of value (not including any ending quote/comment!) */
488 !(isspace((unsigned char) *q) ||
489 *q == '\'' || *q == '"' || *q == '#'))
491 /* and save the argument value */
492 strlcpy(portstr, p, Min((q - p) + 1, sizeof(portstr)));
493 /* keep looking, maybe there is another */
498 /* Check environment */
499 if (!*portstr && getenv("PGPORT") != NULL)
500 strlcpy(portstr, getenv("PGPORT"), sizeof(portstr));
502 /* Else use compiled-in default */
504 snprintf(portstr, sizeof(portstr), "%d", DEF_PGPORT);
507 * We need to set a connect timeout otherwise on Windows the SCM will
508 * probably timeout first
510 snprintf(connstr, sizeof(connstr),
511 "dbname=postgres port=%s connect_timeout=5", portstr);
513 for (i = 0; i < wait_seconds; i++)
515 if ((conn = PQconnectdb(connstr)) != NULL &&
516 (PQstatus(conn) == CONNECTION_OK ||
517 PQconnectionNeedsPassword(conn)))
531 * Increment the wait hint by 6 secs (connection timeout +
532 * sleep) We must do this to indicate to the SCM that our
533 * startup time is changing, otherwise it'll usually send a
534 * stop signal after 20 seconds, despite incrementing the
535 * checkpoint counter.
537 status.dwWaitHint += 6000;
538 status.dwCheckPoint++;
539 SetServiceStatus(hStatus, (LPSERVICE_STATUS) & status);
546 pg_usleep(1000000); /* 1 sec */
554 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_CORE)
556 unlimit_core_size(void)
560 getrlimit(RLIMIT_CORE, &lim);
561 if (lim.rlim_max == 0)
563 write_stderr(_("%s: cannot set core file size limit; disallowed by hard limit\n"),
567 else if (lim.rlim_max == RLIM_INFINITY || lim.rlim_cur < lim.rlim_max)
569 lim.rlim_cur = lim.rlim_max;
570 setrlimit(RLIMIT_CORE, &lim);
578 char *optline = NULL;
580 if (post_opts == NULL)
585 optlines = readfile(ctl_command == RESTART_COMMAND ?
586 postopts_file : def_postopts_file);
587 if (optlines == NULL)
589 if (ctl_command == START_COMMAND || ctl_command == RUN_AS_SERVICE_COMMAND)
593 write_stderr(_("%s: could not read file \"%s\"\n"), progname, postopts_file);
597 else if (optlines[0] == NULL || optlines[1] != NULL)
599 write_stderr(_("%s: option file \"%s\" must have exactly one line\n"),
600 progname, ctl_command == RESTART_COMMAND ?
601 postopts_file : def_postopts_file);
606 optline = optlines[0];
607 len = strcspn(optline, "\r\n");
610 if (ctl_command == RESTART_COMMAND)
614 arg1 = strchr(optline, *SYSTEMQUOTE);
615 if (arg1 == NULL || arg1 == optline)
619 *(arg1 - 1) = '\0'; /* this should be a space */
622 if (postgres_path != NULL)
623 postgres_path = optline;
638 if (ctl_command != RESTART_COMMAND)
640 old_pid = get_pgpid();
642 write_stderr(_("%s: another server might be running; "
643 "trying to start server anyway\n"),
649 /* No -D or -D already added during server start */
650 if (ctl_command == RESTART_COMMAND || pgdata_opt == NULL)
653 if (postgres_path == NULL)
655 char *postmaster_path;
658 postmaster_path = pg_malloc(MAXPGPATH);
660 if ((ret = find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
661 postmaster_path)) < 0)
663 char full_path[MAXPGPATH];
665 if (find_my_exec(argv0, full_path) < 0)
666 strlcpy(full_path, progname, sizeof(full_path));
669 write_stderr(_("The program \"postgres\" is needed by %s "
670 "but was not found in the\n"
671 "same directory as \"%s\".\n"
672 "Check your installation.\n"),
673 progname, full_path);
675 write_stderr(_("The program \"postgres\" was found by \"%s\"\n"
676 "but was not the same version as %s.\n"
677 "Check your installation.\n"),
678 full_path, progname);
681 postgres_path = postmaster_path;
684 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_CORE)
685 if (allow_core_files)
689 exitcode = start_postmaster();
692 write_stderr(_("%s: could not start server: exit code was %d\n"),
703 write_stderr(_("%s: could not start server\n"
704 "Examine the log output.\n"),
712 print_msg(_("waiting for server to start..."));
714 if (test_postmaster_connection(false) == false)
716 printf(_("could not start server\n"));
721 print_msg(_(" done\n"));
722 print_msg(_("server started\n"));
726 print_msg(_("server starting\n"));
739 if (pid == 0) /* no pid file */
741 write_stderr(_("%s: PID file \"%s\" does not exist\n"), progname, pid_file);
742 write_stderr(_("Is server running?\n"));
745 else if (pid < 0) /* standalone backend, not postmaster */
748 write_stderr(_("%s: cannot stop server; "
749 "single-user server is running (PID: %ld)\n"),
754 if (kill((pid_t) pid, sig) != 0)
756 write_stderr(_("%s: could not send stop signal (PID: %ld): %s\n"), progname, pid,
763 print_msg(_("server shutting down\n"));
768 if ((shutdown_mode == SMART_MODE) && (stat(backup_file, &statbuf) == 0))
770 print_msg(_("WARNING: online backup mode is active; must be ended\n"
771 " with pg_stop_backup() for shutdown to complete\n\n"));
774 print_msg(_("waiting for server to shut down..."));
776 for (cnt = 0; cnt < wait_seconds; cnt++)
778 if ((pid = get_pgpid()) != 0)
781 pg_usleep(1000000); /* 1 sec */
787 if (pid != 0) /* pid file still exists */
789 print_msg(_(" failed\n"));
791 write_stderr(_("%s: server does not shut down\n"), progname);
794 print_msg(_(" done\n"));
796 printf(_("server stopped\n"));
802 * restart/reload routines
814 if (pid == 0) /* no pid file */
816 write_stderr(_("%s: PID file \"%s\" does not exist\n"),
818 write_stderr(_("Is server running?\n"));
819 write_stderr(_("starting server anyway\n"));
823 else if (pid < 0) /* standalone backend, not postmaster */
826 if (postmaster_is_alive((pid_t) pid))
828 write_stderr(_("%s: cannot restart server; "
829 "single-user server is running (PID: %ld)\n"),
831 write_stderr(_("Please terminate the single-user server and try again.\n"));
836 if (postmaster_is_alive((pid_t) pid))
838 if (kill((pid_t) pid, sig) != 0)
840 write_stderr(_("%s: could not send stop signal (PID: %ld): %s\n"), progname, pid,
845 if ((shutdown_mode == SMART_MODE) && (stat(backup_file, &statbuf) == 0))
847 print_msg(_("WARNING: online backup mode is active; must be ended\n"
848 " with pg_stop_backup() for shutdown to complete\n\n"));
851 print_msg(_("waiting for server to shut down..."));
853 /* always wait for restart */
855 for (cnt = 0; cnt < wait_seconds; cnt++)
857 if ((pid = get_pgpid()) != 0)
860 pg_usleep(1000000); /* 1 sec */
866 if (pid != 0) /* pid file still exists */
868 print_msg(_(" failed\n"));
870 write_stderr(_("%s: server does not shut down\n"), progname);
874 print_msg(_(" done\n"));
875 printf(_("server stopped\n"));
879 write_stderr(_("%s: old server process (PID: %ld) seems to be gone\n"),
881 write_stderr(_("starting server anyway\n"));
894 if (pid == 0) /* no pid file */
896 write_stderr(_("%s: PID file \"%s\" does not exist\n"), progname, pid_file);
897 write_stderr(_("Is server running?\n"));
900 else if (pid < 0) /* standalone backend, not postmaster */
903 write_stderr(_("%s: cannot reload server; "
904 "single-user server is running (PID: %ld)\n"),
906 write_stderr(_("Please terminate the single-user server and try again.\n"));
910 if (kill((pid_t) pid, sig) != 0)
912 write_stderr(_("%s: could not send reload signal (PID: %ld): %s\n"),
913 progname, pid, strerror(errno));
917 print_msg(_("server signaled\n"));
925 postmaster_is_alive(pid_t pid)
928 * Test to see if the process is still there. Note that we do not
929 * consider an EPERM failure to mean that the process is still there;
930 * EPERM must mean that the given PID belongs to some other userid, and
931 * considering the permissions on $PGDATA, that means it's not the
932 * postmaster we are after.
934 * Don't believe that our own PID or parent shell's PID is the postmaster,
935 * either. (Windows hasn't got getppid(), though.)
940 if (pid == getppid())
943 if (kill(pid, 0) == 0)
954 if (pid != 0) /* 0 means no pid file */
956 if (pid < 0) /* standalone backend */
959 if (postmaster_is_alive((pid_t) pid))
961 printf(_("%s: single-user server is running (PID: %ld)\n"),
969 if (postmaster_is_alive((pid_t) pid))
973 printf(_("%s: server is running (PID: %ld)\n"),
976 optlines = readfile(postopts_file);
977 if (optlines != NULL)
978 for (; *optlines != NULL; optlines++)
979 fputs(*optlines, stdout);
984 printf(_("%s: no server running\n"), progname);
993 if (kill((pid_t) pid, sig) != 0)
995 write_stderr(_("%s: could not send signal %d (PID: %ld): %s\n"),
996 progname, sig, pid, strerror(errno));
1001 #if defined(WIN32) || defined(__CYGWIN__)
1004 pgwin32_IsInstalled(SC_HANDLE hSCM)
1006 SC_HANDLE hService = OpenService(hSCM, register_servicename, SERVICE_QUERY_CONFIG);
1007 bool bResult = (hService != NULL);
1010 CloseServiceHandle(hService);
1015 pgwin32_CommandLine(bool registration)
1017 static char cmdLine[MAXPGPATH];
1021 char buf[MAXPGPATH];
1026 ret = find_my_exec(argv0, cmdLine);
1029 write_stderr(_("%s: could not find own program executable\n"), progname);
1035 ret = find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
1039 write_stderr(_("%s: could not find postgres program executable\n"), progname);
1045 /* need to convert to windows path */
1046 cygwin_conv_to_full_win32_path(cmdLine, buf);
1047 strcpy(cmdLine, buf);
1052 if (pg_strcasecmp(cmdLine + strlen(cmdLine) - 4, ".exe"))
1054 /* If commandline does not end in .exe, append it */
1055 strcat(cmdLine, ".exe");
1057 strcat(cmdLine, " runservice -N \"");
1058 strcat(cmdLine, register_servicename);
1059 strcat(cmdLine, "\"");
1064 strcat(cmdLine, " -D \"");
1065 strcat(cmdLine, pg_data);
1066 strcat(cmdLine, "\"");
1069 if (registration && do_wait)
1070 strcat(cmdLine, " -w");
1072 if (registration && wait_seconds != DEFAULT_WAIT)
1074 sprintf(cmdLine + strlen(cmdLine), " -t %d", wait_seconds);
1078 strcat(cmdLine, " ");
1080 strcat(cmdLine, " -o \"");
1081 strcat(cmdLine, post_opts);
1083 strcat(cmdLine, "\"");
1090 pgwin32_doRegister(void)
1093 SC_HANDLE hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
1097 write_stderr(_("%s: could not open service manager\n"), progname);
1100 if (pgwin32_IsInstalled(hSCM))
1102 CloseServiceHandle(hSCM);
1103 write_stderr(_("%s: service \"%s\" already registered\n"), progname, register_servicename);
1107 if ((hService = CreateService(hSCM, register_servicename, register_servicename,
1108 SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
1109 SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
1110 pgwin32_CommandLine(true),
1111 NULL, NULL, "RPCSS\0", register_username, register_password)) == NULL)
1113 CloseServiceHandle(hSCM);
1114 write_stderr(_("%s: could not register service \"%s\": error code %d\n"), progname, register_servicename, (int) GetLastError());
1117 CloseServiceHandle(hService);
1118 CloseServiceHandle(hSCM);
1122 pgwin32_doUnregister(void)
1125 SC_HANDLE hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
1129 write_stderr(_("%s: could not open service manager\n"), progname);
1132 if (!pgwin32_IsInstalled(hSCM))
1134 CloseServiceHandle(hSCM);
1135 write_stderr(_("%s: service \"%s\" not registered\n"), progname, register_servicename);
1139 if ((hService = OpenService(hSCM, register_servicename, DELETE)) == NULL)
1141 CloseServiceHandle(hSCM);
1142 write_stderr(_("%s: could not open service \"%s\": error code %d\n"), progname, register_servicename, (int) GetLastError());
1145 if (!DeleteService(hService))
1147 CloseServiceHandle(hService);
1148 CloseServiceHandle(hSCM);
1149 write_stderr(_("%s: could not unregister service \"%s\": error code %d\n"), progname, register_servicename, (int) GetLastError());
1152 CloseServiceHandle(hService);
1153 CloseServiceHandle(hSCM);
1157 pgwin32_SetServiceStatus(DWORD currentState)
1159 status.dwCurrentState = currentState;
1160 SetServiceStatus(hStatus, (LPSERVICE_STATUS) & status);
1164 pgwin32_ServiceHandler(DWORD request)
1168 case SERVICE_CONTROL_STOP:
1169 case SERVICE_CONTROL_SHUTDOWN:
1172 * We only need a short wait hint here as it just needs to wait
1173 * for the next checkpoint. They occur every 5 seconds during
1176 status.dwWaitHint = 10000;
1177 pgwin32_SetServiceStatus(SERVICE_STOP_PENDING);
1178 SetEvent(shutdownEvent);
1181 case SERVICE_CONTROL_PAUSE:
1182 /* Win32 config reloading */
1183 status.dwWaitHint = 5000;
1184 kill(postmasterPID, SIGHUP);
1187 /* FIXME: These could be used to replace other signals etc */
1188 case SERVICE_CONTROL_CONTINUE:
1189 case SERVICE_CONTROL_INTERROGATE:
1196 pgwin32_ServiceMain(DWORD argc, LPTSTR * argv)
1198 PROCESS_INFORMATION pi;
1200 DWORD check_point_start;
1202 /* Initialize variables */
1203 status.dwWin32ExitCode = S_OK;
1204 status.dwCheckPoint = 0;
1205 status.dwWaitHint = 60000;
1206 status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
1207 status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_PAUSE_CONTINUE;
1208 status.dwServiceSpecificExitCode = 0;
1209 status.dwCurrentState = SERVICE_START_PENDING;
1211 memset(&pi, 0, sizeof(pi));
1215 /* Register the control request handler */
1216 if ((hStatus = RegisterServiceCtrlHandler(register_servicename, pgwin32_ServiceHandler)) == (SERVICE_STATUS_HANDLE) 0)
1219 if ((shutdownEvent = CreateEvent(NULL, true, false, NULL)) == NULL)
1222 /* Start the postmaster */
1223 pgwin32_SetServiceStatus(SERVICE_START_PENDING);
1224 if (!CreateRestrictedProcess(pgwin32_CommandLine(false), &pi))
1226 pgwin32_SetServiceStatus(SERVICE_STOPPED);
1229 postmasterPID = pi.dwProcessId;
1230 postmasterProcess = pi.hProcess;
1231 CloseHandle(pi.hThread);
1235 write_eventlog(EVENTLOG_INFORMATION_TYPE, _("Waiting for server startup...\n"));
1236 if (test_postmaster_connection(true) == false)
1238 write_eventlog(EVENTLOG_INFORMATION_TYPE, _("Timed out waiting for server startup\n"));
1239 pgwin32_SetServiceStatus(SERVICE_STOPPED);
1242 write_eventlog(EVENTLOG_INFORMATION_TYPE, _("Server started and accepting connections\n"));
1246 * Save the checkpoint value as it might have been incremented in
1247 * test_postmaster_connection
1249 check_point_start = status.dwCheckPoint;
1251 pgwin32_SetServiceStatus(SERVICE_RUNNING);
1253 /* Wait for quit... */
1254 ret = WaitForMultipleObjects(2, shutdownHandles, FALSE, INFINITE);
1256 pgwin32_SetServiceStatus(SERVICE_STOP_PENDING);
1259 case WAIT_OBJECT_0: /* shutdown event */
1260 kill(postmasterPID, SIGINT);
1263 * Increment the checkpoint and try again Abort after 12
1264 * checkpoints as the postmaster has probably hung
1266 while (WaitForSingleObject(postmasterProcess, 5000) == WAIT_TIMEOUT && status.dwCheckPoint < 12)
1267 status.dwCheckPoint++;
1270 case (WAIT_OBJECT_0 + 1): /* postmaster went down */
1274 /* shouldn't get here? */
1278 CloseHandle(shutdownEvent);
1279 CloseHandle(postmasterProcess);
1281 pgwin32_SetServiceStatus(SERVICE_STOPPED);
1285 pgwin32_doRunAsService(void)
1287 SERVICE_TABLE_ENTRY st[] = {{register_servicename, pgwin32_ServiceMain},
1290 if (StartServiceCtrlDispatcher(st) == 0)
1292 write_stderr(_("%s: could not start service \"%s\": error code %d\n"), progname, register_servicename, (int) GetLastError());
1299 * Mingw headers are incomplete, and so are the libraries. So we have to load
1300 * a whole lot of API functions dynamically. Since we have to do this anyway,
1301 * also load the couple of functions that *do* exist in minwg headers but not
1302 * on NT4. That way, we don't break on NT4.
1304 typedef BOOL(WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE);
1305 typedef BOOL(WINAPI * __IsProcessInJob) (HANDLE, HANDLE, PBOOL);
1306 typedef HANDLE(WINAPI * __CreateJobObject) (LPSECURITY_ATTRIBUTES, LPCTSTR);
1307 typedef BOOL(WINAPI * __SetInformationJobObject) (HANDLE, JOBOBJECTINFOCLASS, LPVOID, DWORD);
1308 typedef BOOL(WINAPI * __AssignProcessToJobObject) (HANDLE, HANDLE);
1309 typedef BOOL(WINAPI * __QueryInformationJobObject) (HANDLE, JOBOBJECTINFOCLASS, LPVOID, DWORD, LPDWORD);
1311 /* Windows API define missing from MingW headers */
1312 #define DISABLE_MAX_PRIVILEGE 0x1
1315 * Create a restricted token, a job object sandbox, and execute the specified
1318 * Returns 0 on success, non-zero on failure, same as CreateProcess().
1320 * On NT4, or any other system not containing the required functions, will
1321 * launch the process under the current token without doing any modifications.
1323 * NOTE! Job object will only work when running as a service, because it's
1324 * automatically destroyed when pg_ctl exits.
1327 CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION * processInfo)
1333 HANDLE restrictedToken;
1334 SID_IDENTIFIER_AUTHORITY NtAuthority = {SECURITY_NT_AUTHORITY};
1335 SID_AND_ATTRIBUTES dropSids[2];
1337 /* Functions loaded dynamically */
1338 __CreateRestrictedToken _CreateRestrictedToken = NULL;
1339 __IsProcessInJob _IsProcessInJob = NULL;
1340 __CreateJobObject _CreateJobObject = NULL;
1341 __SetInformationJobObject _SetInformationJobObject = NULL;
1342 __AssignProcessToJobObject _AssignProcessToJobObject = NULL;
1343 __QueryInformationJobObject _QueryInformationJobObject = NULL;
1344 HANDLE Kernel32Handle;
1345 HANDLE Advapi32Handle;
1347 ZeroMemory(&si, sizeof(si));
1350 Advapi32Handle = LoadLibrary("ADVAPI32.DLL");
1351 if (Advapi32Handle != NULL)
1353 _CreateRestrictedToken = (__CreateRestrictedToken) GetProcAddress(Advapi32Handle, "CreateRestrictedToken");
1356 if (_CreateRestrictedToken == NULL)
1359 * NT4 doesn't have CreateRestrictedToken, so just call ordinary
1362 write_stderr("WARNING: cannot create restricted tokens on this platform\n");
1363 if (Advapi32Handle != NULL)
1364 FreeLibrary(Advapi32Handle);
1365 return CreateProcess(NULL, cmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, processInfo);
1368 /* Open the current token to use as a base for the restricted one */
1369 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken))
1371 write_stderr("Failed to open process token: %lu\n", GetLastError());
1375 /* Allocate list of SIDs to remove */
1376 ZeroMemory(&dropSids, sizeof(dropSids));
1377 if (!AllocateAndInitializeSid(&NtAuthority, 2,
1378 SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0,
1379 0, &dropSids[0].Sid) ||
1380 !AllocateAndInitializeSid(&NtAuthority, 2,
1381 SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0,
1382 0, &dropSids[1].Sid))
1384 write_stderr("Failed to allocate SIDs: %lu\n", GetLastError());
1388 b = _CreateRestrictedToken(origToken,
1389 DISABLE_MAX_PRIVILEGE,
1390 sizeof(dropSids) / sizeof(dropSids[0]),
1396 FreeSid(dropSids[1].Sid);
1397 FreeSid(dropSids[0].Sid);
1398 CloseHandle(origToken);
1399 FreeLibrary(Advapi32Handle);
1403 write_stderr("Failed to create restricted token: %lu\n", GetLastError());
1407 r = CreateProcessAsUser(restrictedToken, NULL, cmd, NULL, NULL, TRUE, CREATE_SUSPENDED, NULL, NULL, &si, processInfo);
1409 Kernel32Handle = LoadLibrary("KERNEL32.DLL");
1410 if (Kernel32Handle != NULL)
1412 _IsProcessInJob = (__IsProcessInJob) GetProcAddress(Kernel32Handle, "IsProcessInJob");
1413 _CreateJobObject = (__CreateJobObject) GetProcAddress(Kernel32Handle, "CreateJobObjectA");
1414 _SetInformationJobObject = (__SetInformationJobObject) GetProcAddress(Kernel32Handle, "SetInformationJobObject");
1415 _AssignProcessToJobObject = (__AssignProcessToJobObject) GetProcAddress(Kernel32Handle, "AssignProcessToJobObject");
1416 _QueryInformationJobObject = (__QueryInformationJobObject) GetProcAddress(Kernel32Handle, "QueryInformationJobObject");
1419 /* Verify that we found all functions */
1420 if (_IsProcessInJob == NULL || _CreateJobObject == NULL || _SetInformationJobObject == NULL || _AssignProcessToJobObject == NULL || _QueryInformationJobObject == NULL)
1423 * IsProcessInJob() is not available on < WinXP, so there is no need
1424 * to log the error every time in that case
1428 osv.dwOSVersionInfoSize = sizeof(osv);
1429 if (!GetVersionEx(&osv) || /* could not get version */
1430 (osv.dwMajorVersion == 5 && osv.dwMinorVersion > 0) || /* 5.1=xp, 5.2=2003, etc */
1431 osv.dwMajorVersion > 5) /* anything newer should have the API */
1434 * Log error if we can't get version, or if we're on WinXP/2003 or
1437 write_stderr("WARNING: could not locate all job object functions in system API\n");
1443 if (_IsProcessInJob(processInfo->hProcess, NULL, &inJob))
1448 * Job objects are working, and the new process isn't in one,
1449 * so we can create one safely. If any problems show up when
1450 * setting it, we're going to ignore them.
1455 sprintf(jobname, "PostgreSQL_%lu", processInfo->dwProcessId);
1457 job = _CreateJobObject(NULL, jobname);
1460 JOBOBJECT_BASIC_LIMIT_INFORMATION basicLimit;
1461 JOBOBJECT_BASIC_UI_RESTRICTIONS uiRestrictions;
1462 JOBOBJECT_SECURITY_LIMIT_INFORMATION securityLimit;
1464 ZeroMemory(&basicLimit, sizeof(basicLimit));
1465 ZeroMemory(&uiRestrictions, sizeof(uiRestrictions));
1466 ZeroMemory(&securityLimit, sizeof(securityLimit));
1468 basicLimit.LimitFlags = JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION | JOB_OBJECT_LIMIT_PRIORITY_CLASS;
1469 basicLimit.PriorityClass = NORMAL_PRIORITY_CLASS;
1470 _SetInformationJobObject(job, JobObjectBasicLimitInformation, &basicLimit, sizeof(basicLimit));
1472 uiRestrictions.UIRestrictionsClass = JOB_OBJECT_UILIMIT_DESKTOP | JOB_OBJECT_UILIMIT_DISPLAYSETTINGS |
1473 JOB_OBJECT_UILIMIT_EXITWINDOWS | JOB_OBJECT_UILIMIT_HANDLES | JOB_OBJECT_UILIMIT_READCLIPBOARD |
1474 JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS | JOB_OBJECT_UILIMIT_WRITECLIPBOARD;
1475 _SetInformationJobObject(job, JobObjectBasicUIRestrictions, &uiRestrictions, sizeof(uiRestrictions));
1477 securityLimit.SecurityLimitFlags = JOB_OBJECT_SECURITY_NO_ADMIN | JOB_OBJECT_SECURITY_ONLY_TOKEN;
1478 securityLimit.JobToken = restrictedToken;
1479 _SetInformationJobObject(job, JobObjectSecurityLimitInformation, &securityLimit, sizeof(securityLimit));
1481 _AssignProcessToJobObject(job, processInfo->hProcess);
1488 AddUserToDacl(processInfo->hProcess);
1491 CloseHandle(restrictedToken);
1493 ResumeThread(processInfo->hThread);
1495 FreeLibrary(Kernel32Handle);
1498 * We intentionally don't close the job object handle, because we want the
1499 * object to live on until pg_ctl shuts down.
1508 write_stderr(_("Try \"%s --help\" for more information.\n"), progname);
1516 printf(_("%s is a utility to start, stop, restart, reload configuration files,\n"
1517 "report the status of a PostgreSQL server, or signal a PostgreSQL process.\n\n"), progname);
1518 printf(_("Usage:\n"));
1519 printf(_(" %s start [-w] [-t SECS] [-D DATADIR] [-s] [-l FILENAME] [-o \"OPTIONS\"]\n"), progname);
1520 printf(_(" %s stop [-W] [-t SECS] [-D DATADIR] [-s] [-m SHUTDOWN-MODE]\n"), progname);
1521 printf(_(" %s restart [-w] [-t SECS] [-D DATADIR] [-s] [-m SHUTDOWN-MODE]\n"
1522 " [-o \"OPTIONS\"]\n"), progname);
1523 printf(_(" %s reload [-D DATADIR] [-s]\n"), progname);
1524 printf(_(" %s status [-D DATADIR]\n"), progname);
1525 printf(_(" %s kill SIGNALNAME PID\n"), progname);
1526 #if defined(WIN32) || defined(__CYGWIN__)
1527 printf(_(" %s register [-N SERVICENAME] [-U USERNAME] [-P PASSWORD] [-D DATADIR]\n"
1528 " [-w] [-t SECS] [-o \"OPTIONS\"]\n"), progname);
1529 printf(_(" %s unregister [-N SERVICENAME]\n"), progname);
1532 printf(_("\nCommon options:\n"));
1533 printf(_(" -D, --pgdata DATADIR location of the database storage area\n"));
1534 printf(_(" -s, --silent only print errors, no informational messages\n"));
1535 printf(_(" -t SECS seconds to wait when using -w option\n"));
1536 printf(_(" -w wait until operation completes\n"));
1537 printf(_(" -W do not wait until operation completes\n"));
1538 printf(_(" --help show this help, then exit\n"));
1539 printf(_(" --version output version information, then exit\n"));
1540 printf(_("(The default is to wait for shutdown, but not for start or restart.)\n\n"));
1541 printf(_("If the -D option is omitted, the environment variable PGDATA is used.\n"));
1543 printf(_("\nOptions for start or restart:\n"));
1544 printf(_(" -l, --log FILENAME write (or append) server log to FILENAME\n"));
1545 printf(_(" -o OPTIONS command line options to pass to postgres\n"
1546 " (PostgreSQL server executable)\n"));
1547 printf(_(" -p PATH-TO-POSTGRES normally not necessary\n"));
1548 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_CORE)
1549 printf(_(" -c, --core-files allow postgres to produce core files\n"));
1551 printf(_(" -c, --core-files not applicable on this platform\n"));
1553 printf(_("\nOptions for stop or restart:\n"));
1554 printf(_(" -m SHUTDOWN-MODE can be \"smart\", \"fast\", or \"immediate\"\n"));
1556 printf(_("\nShutdown modes are:\n"));
1557 printf(_(" smart quit after all clients have disconnected\n"));
1558 printf(_(" fast quit directly, with proper shutdown\n"));
1559 printf(_(" immediate quit without complete shutdown; will lead to recovery on restart\n"));
1561 printf(_("\nAllowed signal names for kill:\n"));
1562 printf(" HUP INT QUIT ABRT TERM USR1 USR2\n");
1564 #if defined(WIN32) || defined(__CYGWIN__)
1565 printf(_("\nOptions for register and unregister:\n"));
1566 printf(_(" -N SERVICENAME service name with which to register PostgreSQL server\n"));
1567 printf(_(" -P PASSWORD password of account to register PostgreSQL server\n"));
1568 printf(_(" -U USERNAME user name of account to register PostgreSQL server\n"));
1571 printf(_("\nReport bugs to <pgsql-bugs@postgresql.org>.\n"));
1577 set_mode(char *modeopt)
1579 if (strcmp(modeopt, "s") == 0 || strcmp(modeopt, "smart") == 0)
1581 shutdown_mode = SMART_MODE;
1584 else if (strcmp(modeopt, "f") == 0 || strcmp(modeopt, "fast") == 0)
1586 shutdown_mode = FAST_MODE;
1589 else if (strcmp(modeopt, "i") == 0 || strcmp(modeopt, "immediate") == 0)
1591 shutdown_mode = IMMEDIATE_MODE;
1596 write_stderr(_("%s: unrecognized shutdown mode \"%s\"\n"), progname, modeopt);
1605 set_sig(char *signame)
1607 if (!strcmp(signame, "HUP"))
1609 else if (!strcmp(signame, "INT"))
1611 else if (!strcmp(signame, "QUIT"))
1613 else if (!strcmp(signame, "ABRT"))
1617 * probably should NOT provide SIGKILL
1619 * else if (!strcmp(signame,"KILL")) sig = SIGKILL;
1621 else if (!strcmp(signame, "TERM"))
1623 else if (!strcmp(signame, "USR1"))
1625 else if (!strcmp(signame, "USR2"))
1629 write_stderr(_("%s: unrecognized signal name \"%s\"\n"), progname, signame);
1639 main(int argc, char **argv)
1641 static struct option long_options[] = {
1642 {"help", no_argument, NULL, '?'},
1643 {"version", no_argument, NULL, 'V'},
1644 {"log", required_argument, NULL, 'l'},
1645 {"mode", required_argument, NULL, 'm'},
1646 {"pgdata", required_argument, NULL, 'D'},
1647 {"silent", no_argument, NULL, 's'},
1648 {"timeout", required_argument, NULL, 't'},
1649 {"core-files", no_argument, NULL, 'c'},
1655 pgpid_t killproc = 0;
1657 #if defined(WIN32) || defined(__CYGWIN__)
1658 setvbuf(stderr, NULL, _IONBF, 0);
1661 progname = get_progname(argv[0]);
1662 set_pglocale_pgservice(argv[0], "pg_ctl");
1665 * save argv[0] so do_start() can look for the postmaster if necessary. we
1666 * don't look for postmaster here because in many cases we won't need it.
1672 /* support --help and --version even if invoked as root */
1675 if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0 ||
1676 strcmp(argv[1], "-?") == 0)
1681 else if (strcmp(argv[1], "-V") == 0 || strcmp(argv[1], "--version") == 0)
1683 puts("pg_ctl (PostgreSQL) " PG_VERSION);
1689 * Disallow running as root, to forestall any possible security holes.
1694 write_stderr(_("%s: cannot be run as root\n"
1695 "Please log in (using, e.g., \"su\") as the "
1696 "(unprivileged) user that will\n"
1697 "own the server process.\n"),
1704 * 'Action' can be before or after args so loop over both. Some
1705 * getopt_long() implementations will reorder argv[] to place all flags
1706 * first (GNU?), but we don't rely on it. Our /port version doesn't do
1711 /* process command-line options */
1712 while (optind < argc)
1714 while ((c = getopt_long(argc, argv, "cD:l:m:N:o:p:P:st:U:wW", long_options, &option_index)) != -1)
1721 char *env_var = pg_malloc(strlen(optarg) + 8);
1723 pgdata_D = xstrdup(optarg);
1724 canonicalize_path(pgdata_D);
1725 snprintf(env_var, strlen(optarg) + 8, "PGDATA=%s",
1730 * We could pass PGDATA just in an environment
1731 * variable but we do -D too for clearer postmaster
1734 pgdata_opt = pg_malloc(strlen(pgdata_D) + 7);
1735 snprintf(pgdata_opt, strlen(pgdata_D) + 7,
1741 log_file = xstrdup(optarg);
1747 register_servicename = xstrdup(optarg);
1750 post_opts = xstrdup(optarg);
1753 postgres_path = xstrdup(optarg);
1756 register_password = xstrdup(optarg);
1762 wait_seconds = atoi(optarg);
1765 if (strchr(optarg, '\\'))
1766 register_username = xstrdup(optarg);
1768 /* Prepend .\ for local accounts */
1770 register_username = malloc(strlen(optarg) + 3);
1771 if (!register_username)
1773 write_stderr(_("%s: out of memory\n"), progname);
1776 strcpy(register_username, ".\\");
1777 strcat(register_username, optarg);
1789 allow_core_files = true;
1792 /* getopt_long already issued a suitable error message */
1798 /* Process an action */
1801 if (ctl_command != NO_COMMAND)
1803 write_stderr(_("%s: too many command-line arguments (first is \"%s\")\n"), progname, argv[optind]);
1808 if (strcmp(argv[optind], "start") == 0)
1809 ctl_command = START_COMMAND;
1810 else if (strcmp(argv[optind], "stop") == 0)
1811 ctl_command = STOP_COMMAND;
1812 else if (strcmp(argv[optind], "restart") == 0)
1813 ctl_command = RESTART_COMMAND;
1814 else if (strcmp(argv[optind], "reload") == 0)
1815 ctl_command = RELOAD_COMMAND;
1816 else if (strcmp(argv[optind], "status") == 0)
1817 ctl_command = STATUS_COMMAND;
1818 else if (strcmp(argv[optind], "kill") == 0)
1820 if (argc - optind < 3)
1822 write_stderr(_("%s: missing arguments for kill mode\n"), progname);
1826 ctl_command = KILL_COMMAND;
1827 set_sig(argv[++optind]);
1828 killproc = atol(argv[++optind]);
1830 #if defined(WIN32) || defined(__CYGWIN__)
1831 else if (strcmp(argv[optind], "register") == 0)
1832 ctl_command = REGISTER_COMMAND;
1833 else if (strcmp(argv[optind], "unregister") == 0)
1834 ctl_command = UNREGISTER_COMMAND;
1835 else if (strcmp(argv[optind], "runservice") == 0)
1836 ctl_command = RUN_AS_SERVICE_COMMAND;
1840 write_stderr(_("%s: unrecognized operation mode \"%s\"\n"), progname, argv[optind]);
1848 if (ctl_command == NO_COMMAND)
1850 write_stderr(_("%s: no operation specified\n"), progname);
1855 /* Note we put any -D switch into the env var above */
1856 pg_data = getenv("PGDATA");
1859 pg_data = xstrdup(pg_data);
1860 canonicalize_path(pg_data);
1863 if (pg_data == NULL &&
1864 ctl_command != KILL_COMMAND && ctl_command != UNREGISTER_COMMAND)
1866 write_stderr(_("%s: no database directory specified "
1867 "and environment variable PGDATA unset\n"),
1875 switch (ctl_command)
1877 case RESTART_COMMAND:
1889 if (ctl_command == RELOAD_COMMAND)
1897 snprintf(def_postopts_file, MAXPGPATH, "%s/postmaster.opts.default", pg_data);
1898 snprintf(postopts_file, MAXPGPATH, "%s/postmaster.opts", pg_data);
1899 snprintf(pid_file, MAXPGPATH, "%s/postmaster.pid", pg_data);
1900 snprintf(conf_file, MAXPGPATH, "%s/postgresql.conf", pg_data);
1901 snprintf(backup_file, MAXPGPATH, "%s/backup_label", pg_data);
1904 switch (ctl_command)
1906 case STATUS_COMMAND:
1915 case RESTART_COMMAND:
1918 case RELOAD_COMMAND:
1924 #if defined(WIN32) || defined(__CYGWIN__)
1925 case REGISTER_COMMAND:
1926 pgwin32_doRegister();
1928 case UNREGISTER_COMMAND:
1929 pgwin32_doUnregister();
1931 case RUN_AS_SERVICE_COMMAND:
1932 pgwin32_doRunAsService();