X-Git-Url: http://git.iain.cx/?a=blobdiff_plain;f=service.cpp;h=e9fd109bb096f5c779dc607fcdea9e8f311e4ce1;hb=b0a6672810ee06052dc3dcf268274d06f0e82a50;hp=72e0192e10cd4264a457ccc9c2271c2dae57572d;hpb=02203cb8aff4be6a094b7a9ded867c3b5d743d77;p=nssm.git diff --git a/service.cpp b/service.cpp index 72e0192..e9fd109 100644 --- a/service.cpp +++ b/service.cpp @@ -13,6 +13,208 @@ const TCHAR *exit_action_strings[] = { _T("Restart"), _T("Ignore"), _T("Exit"), const TCHAR *startup_strings[] = { _T("SERVICE_AUTO_START"), _T("SERVICE_DELAYED_AUTO_START"), _T("SERVICE_DEMAND_START"), _T("SERVICE_DISABLED"), 0 }; const TCHAR *priority_strings[] = { _T("REALTIME_PRIORITY_CLASS"), _T("HIGH_PRIORITY_CLASS"), _T("ABOVE_NORMAL_PRIORITY_CLASS"), _T("NORMAL_PRIORITY_CLASS"), _T("BELOW_NORMAL_PRIORITY_CLASS"), _T("IDLE_PRIORITY_CLASS"), 0 }; +typedef struct { + int first; + int last; +} list_t; + +/* + Check the status in response to a control. + Returns: 1 if the status is expected, eg STOP following CONTROL_STOP. + 0 if the status is desired, eg STOPPED following CONTROL_STOP. + -1 if the status is undesired, eg STOPPED following CONTROL_START. +*/ +static inline int service_control_response(unsigned long control, unsigned long status) { + switch (control) { + case NSSM_SERVICE_CONTROL_START: + switch (status) { + case SERVICE_START_PENDING: + return 1; + + case SERVICE_RUNNING: + return 0; + + default: + return -1; + } + + case SERVICE_CONTROL_STOP: + case SERVICE_CONTROL_SHUTDOWN: + switch (status) { + case SERVICE_STOP_PENDING: + return 1; + + case SERVICE_STOPPED: + return 0; + + default: + return -1; + } + + case SERVICE_CONTROL_PAUSE: + switch (status) { + case SERVICE_PAUSE_PENDING: + return 1; + + case SERVICE_PAUSED: + return 0; + + default: + return -1; + } + + case SERVICE_CONTROL_CONTINUE: + switch (status) { + case SERVICE_CONTINUE_PENDING: + return 1; + + case SERVICE_RUNNING: + return 0; + + default: + return -1; + } + + case SERVICE_CONTROL_INTERROGATE: + return 0; + } + + return 0; +} + +static inline int await_service_control_response(unsigned long control, SC_HANDLE service_handle, SERVICE_STATUS *service_status, unsigned long initial_status) { + int tries = 0; + while (QueryServiceStatus(service_handle, service_status)) { + int response = service_control_response(control, service_status->dwCurrentState); + /* Alas we can't WaitForSingleObject() on an SC_HANDLE. */ + if (! response) return response; + if (response > 0 || service_status->dwCurrentState == initial_status) { + if (++tries > 10) return response; + Sleep(50 * tries); + } + else return response; + } + return -1; +} + +int affinity_mask_to_string(__int64 mask, TCHAR **string) { + if (! string) return 1; + if (! mask) { + *string = 0; + return 0; + } + + __int64 i, n; + + /* SetProcessAffinityMask() accepts a mask of up to 64 processors. */ + list_t set[64]; + for (n = 0; n < _countof(set); n++) set[n].first = set[n].last = -1; + + for (i = 0, n = 0; i < _countof(set); i++) { + if (mask & (1LL << i)) { + if (set[n].first == -1) set[n].first = set[n].last = (int) i; + else if (set[n].last == (int) i - 1) set[n].last = (int) i; + else { + n++; + set[n].first = set[n].last = (int) i; + } + } + } + + /* Worst case is 2x2 characters for first and last CPU plus - and/or , */ + size_t len = (size_t) (n + 1) * 6; + *string = (TCHAR *) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, len * sizeof(TCHAR)); + if (! string) return 2; + + size_t s = 0; + int ret; + for (i = 0; i <= n; i++) { + if (i) (*string)[s++] = _T(','); + ret = _sntprintf_s(*string + s, 3, _TRUNCATE, _T("%u"), set[i].first); + if (ret < 0) { + HeapFree(GetProcessHeap(), 0, *string); + *string = 0; + return 3; + } + else s += ret; + if (set[i].last != set[i].first) { + ret =_sntprintf_s(*string + s, 4, _TRUNCATE, _T("%c%u"), (set[i].last == set[i].first + 1) ? _T(',') : _T('-'), set[i].last); + if (ret < 0) { + HeapFree(GetProcessHeap(), 0, *string); + *string = 0; + return 4; + } + else s += ret; + } + } + + return 0; +} + +int affinity_string_to_mask(TCHAR *string, __int64 *mask) { + if (! mask) return 1; + + *mask = 0LL; + if (! string) return 0; + + list_t set[64]; + + TCHAR *s = string; + TCHAR *end; + int ret; + int i; + int n = 0; + unsigned long number; + + for (n = 0; n < _countof(set); n++) set[n].first = set[n].last = -1; + n = 0; + + while (*s) { + ret = str_number(s, &number, &end); + s = end; + if (ret == 0 || ret == 2) { + if (number >= _countof(set)) return 2; + set[n].first = set[n].last = (int) number; + + switch (*s) { + case 0: + break; + + case _T(','): + n++; + s++; + break; + + case _T('-'): + if (! *(++s)) return 3; + ret = str_number(s, &number, &end); + if (ret == 0 || ret == 2) { + s = end; + if (! *s || *s == _T(',')) { + set[n].last = (int) number; + if (! *s) break; + n++; + s++; + } + else return 3; + } + else return 3; + break; + + default: + return 3; + } + } + else return 4; + } + + for (i = 0; i <= n; i++) { + for (int j = set[i].first; j <= set[i].last; j++) (__int64) *mask |= (1LL << (__int64) j); + } + + return 0; +} + inline unsigned long priority_mask() { return REALTIME_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | ABOVE_NORMAL_PRIORITY_CLASS | NORMAL_PRIORITY_CLASS | BELOW_NORMAL_PRIORITY_CLASS | IDLE_PRIORITY_CLASS; } @@ -39,9 +241,9 @@ unsigned long priority_index_to_constant(int index) { return NORMAL_PRIORITY_CLASS; } -static inline int throttle_milliseconds(unsigned long throttle) { +static inline unsigned long throttle_milliseconds(unsigned long throttle) { /* pow() operates on doubles. */ - int ret = 1; for (unsigned long i = 1; i < throttle; i++) ret *= 2; + unsigned long ret = 1; for (unsigned long i = 1; i < throttle; i++) ret *= 2; return ret * 1000; } @@ -479,6 +681,7 @@ void cleanup_nssm_service(nssm_service_t *service) { if (service->wait_handle) UnregisterWait(service->process_handle); if (service->throttle_section_initialised) DeleteCriticalSection(&service->throttle_section); if (service->throttle_timer) CloseHandle(service->throttle_timer); + if (service->initial_env) FreeEnvironmentStrings(service->initial_env); HeapFree(GetProcessHeap(), 0, service); } @@ -578,14 +781,20 @@ int pre_edit_service(int argc, TCHAR **argv) { for (i = 0; settings[i].name; i++) _ftprintf(stderr, _T("%s\n"), settings[i].name); return 1; } - if (argc < mandatory) return usage(1); additional = 0; if (additional_mandatory) { + if (argc < mandatory) { + print_message(stderr, NSSM_MESSAGE_MISSING_SUBPARAMETER, parameter); + return 1; + } additional = argv[3]; remainder = 4; } - else additional = argv[remainder]; + else { + additional = argv[remainder]; + if (argc < mandatory) return usage(1); + } } nssm_service_t *service = alloc_nssm_service(); @@ -930,33 +1139,36 @@ int control_service(unsigned long control, int argc, TCHAR **argv) { int ret; unsigned long error; SERVICE_STATUS service_status; - if (control == 0) { + if (control == NSSM_SERVICE_CONTROL_START) { + unsigned long initial_status = SERVICE_STOPPED; ret = StartService(service_handle, (unsigned long) argc, (const TCHAR **) argv); error = GetLastError(); - CloseHandle(service_handle); CloseServiceHandle(services); if (error == ERROR_IO_PENDING) { /* Older versions of Windows return immediately with ERROR_IO_PENDING indicate that the operation is still in progress. Newer versions - will return it if there really is a delay. As far as we're - concerned the operation is a success. We don't claim to offer a - fully-feature service control method; it's just a quick 'n' dirty - interface. - - In the future we may identify and handle this situation properly. + will return it if there really is a delay. */ ret = 1; error = ERROR_SUCCESS; } if (ret) { - _tprintf(_T("%s: %s"), canonical_name, error_string(error)); + int response = await_service_control_response(control, service_handle, &service_status, initial_status); + CloseHandle(service_handle); + + if (response) { + print_message(stderr, NSSM_MESSAGE_BAD_CONTROL_RESPONSE, canonical_name, service_status_text(service_status.dwCurrentState), service_control_text(control)); + return 1; + } + else _tprintf(_T("%s: %s: %s"), canonical_name, service_control_text(control), error_string(error)); return 0; } else { - _ftprintf(stderr, _T("%s: %s"), canonical_name, error_string(error)); + CloseHandle(service_handle); + _ftprintf(stderr, _T("%s: %s: %s"), canonical_name, service_control_text(control), error_string(error)); return 1; } } @@ -970,16 +1182,7 @@ int control_service(unsigned long control, int argc, TCHAR **argv) { error = GetLastError(); if (ret) { - switch (service_status.dwCurrentState) { - case SERVICE_STOPPED: _tprintf(_T("SERVICE_STOPPED\n")); break; - case SERVICE_START_PENDING: _tprintf(_T("SERVICE_START_PENDING\n")); break; - case SERVICE_STOP_PENDING: _tprintf(_T("SERVICE_STOP_PENDING\n")); break; - case SERVICE_RUNNING: _tprintf(_T("SERVICE_RUNNING\n")); break; - case SERVICE_CONTINUE_PENDING: _tprintf(_T("SERVICE_CONTINUE_PENDING\n")); break; - case SERVICE_PAUSE_PENDING: _tprintf(_T("SERVICE_PAUSE_PENDING\n")); break; - case SERVICE_PAUSED: _tprintf(_T("SERVICE_PAUSED\n")); break; - default: _tprintf(_T("?\n")); return 1; - } + _tprintf(_T("%s\n"), service_status_text(service_status.dwCurrentState)); return 0; } else { @@ -989,8 +1192,8 @@ int control_service(unsigned long control, int argc, TCHAR **argv) { } else { ret = ControlService(service_handle, control, &service_status); + unsigned long initial_status = service_status.dwCurrentState; error = GetLastError(); - CloseHandle(service_handle); CloseServiceHandle(services); if (error == ERROR_IO_PENDING) { @@ -999,11 +1202,22 @@ int control_service(unsigned long control, int argc, TCHAR **argv) { } if (ret) { - _tprintf(_T("%s: %s"), canonical_name, error_string(error)); + int response = await_service_control_response(control, service_handle, &service_status, initial_status); + CloseHandle(service_handle); + + if (response) { + print_message(stderr, NSSM_MESSAGE_BAD_CONTROL_RESPONSE, canonical_name, service_status_text(service_status.dwCurrentState), service_control_text(control)); + return 1; + } + else _tprintf(_T("%s: %s: %s"), canonical_name, service_control_text(control), error_string(error)); return 0; } else { - _ftprintf(stderr, _T("%s: %s"), canonical_name, error_string(error)); + CloseHandle(service_handle); + _ftprintf(stderr, _T("%s: %s: %s"), canonical_name, service_control_text(control), error_string(error)); + if (error == ERROR_SERVICE_NOT_ACTIVE) { + if (control == SERVICE_CONTROL_SHUTDOWN || control == SERVICE_CONTROL_STOP) return 0; + } return 1; } } @@ -1111,6 +1325,9 @@ void WINAPI service_main(unsigned long argc, TCHAR **argv) { } } + /* Remember our initial environment. */ + service->initial_env = GetEnvironmentStrings(); + monitor_service(service); } @@ -1152,12 +1369,26 @@ int monitor_service(nssm_service_t *service) { TCHAR *service_control_text(unsigned long control) { switch (control) { /* HACK: there is no SERVICE_CONTROL_START constant */ - case 0: return _T("START"); + case NSSM_SERVICE_CONTROL_START: return _T("START"); case SERVICE_CONTROL_STOP: return _T("STOP"); case SERVICE_CONTROL_SHUTDOWN: return _T("SHUTDOWN"); case SERVICE_CONTROL_PAUSE: return _T("PAUSE"); case SERVICE_CONTROL_CONTINUE: return _T("CONTINUE"); case SERVICE_CONTROL_INTERROGATE: return _T("INTERROGATE"); + case NSSM_SERVICE_CONTROL_ROTATE: return _T("ROTATE"); + default: return 0; + } +} + +TCHAR *service_status_text(unsigned long status) { + switch (status) { + case SERVICE_STOPPED: return _T("SERVICE_STOPPED"); + case SERVICE_START_PENDING: return _T("SERVICE_START_PENDING"); + case SERVICE_STOP_PENDING: return _T("SERVICE_STOP_PENDING"); + case SERVICE_RUNNING: return _T("SERVICE_RUNNING"); + case SERVICE_CONTINUE_PENDING: return _T("SERVICE_CONTINUE_PENDING"); + case SERVICE_PAUSE_PENDING: return _T("SERVICE_PAUSE_PENDING"); + case SERVICE_PAUSED: return _T("SERVICE_PAUSED"); default: return 0; } } @@ -1232,7 +1463,8 @@ unsigned long WINAPI service_control_handler(unsigned long control, unsigned lon ZeroMemory(&service->throttle_duetime, sizeof(service->throttle_duetime)); SetWaitableTimer(service->throttle_timer, &service->throttle_duetime, 0, 0, 0, 0); } - service->status.dwCurrentState = SERVICE_CONTINUE_PENDING; + /* We can't continue if the application is running! */ + if (! service->process_handle) service->status.dwCurrentState = SERVICE_CONTINUE_PENDING; service->status.dwWaitHint = throttle_milliseconds(service->throttle) + NSSM_WAITHINT_MARGIN; log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_RESET_THROTTLE, service->name, 0); SetServiceStatus(service->status_handle, &service->status); @@ -1245,6 +1477,12 @@ unsigned long WINAPI service_control_handler(unsigned long control, unsigned lon */ log_service_control(service->name, control, false); return ERROR_CALL_NOT_IMPLEMENTED; + + case NSSM_SERVICE_CONTROL_ROTATE: + log_service_control(service->name, control, true); + if (service->rotate_stdout_online == NSSM_ROTATE_ONLINE) service->rotate_stdout_online = NSSM_ROTATE_ONLINE_ASAP; + if (service->rotate_stderr_online == NSSM_ROTATE_ONLINE) service->rotate_stderr_online = NSSM_ROTATE_ONLINE_ASAP; + return NO_ERROR; } /* Unknown control */ @@ -1285,21 +1523,20 @@ int start_service(nssm_service_t *service) { throttle_restart(service); + /* Set the environment. */ + if (service->env) duplicate_environment(service->env); + if (service->env_extra) set_environment_block(service->env_extra); + bool inherit_handles = false; if (si.dwFlags & STARTF_USESTDHANDLES) inherit_handles = true; unsigned long flags = service->priority & priority_mask(); -#ifdef UNICODE - flags |= CREATE_UNICODE_ENVIRONMENT; -#endif - if (! CreateProcess(0, cmd, 0, 0, inherit_handles, flags, service->env, service->dir, &si, &pi)) { + if (service->affinity) flags |= CREATE_SUSPENDED; + if (! CreateProcess(0, cmd, 0, 0, inherit_handles, flags, 0, service->dir, &si, &pi)) { unsigned long exitcode = 3; unsigned long error = GetLastError(); - if (error == ERROR_INVALID_PARAMETER && service->env) { - log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_CREATEPROCESS_FAILED_INVALID_ENVIRONMENT, service->name, service->exe, NSSM_REG_ENV, 0); - if (test_environment(service->env)) exitcode = 4; - } - else log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_CREATEPROCESS_FAILED, service->name, service->exe, error_string(error), 0); + log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_CREATEPROCESS_FAILED, service->name, service->exe, error_string(error), 0); close_output_handles(&si); + duplicate_environment(service->initial_env); return stop_service(service, exitcode, true, true); } service->process_handle = pi.hProcess; @@ -1309,6 +1546,40 @@ int start_service(nssm_service_t *service) { close_output_handles(&si); + if (! service->no_console) FreeConsole(); + + /* Restore our environment. */ + duplicate_environment(service->initial_env); + + if (service->affinity) { + /* + We are explicitly storing service->affinity as a 64-bit unsigned integer + so that we can parse it regardless of whether we're running in 32-bit + or 64-bit mode. The arguments to SetProcessAffinityMask(), however, are + defined as type DWORD_PTR and hence limited to 32 bits on a 32-bit system + (or when running the 32-bit NSSM). + + The result is a lot of seemingly-unnecessary casting throughout the code + and potentially confusion when we actually try to start the service. + Having said that, however, it's unlikely that we're actually going to + run in 32-bit mode on a system which has more than 32 CPUs so the + likelihood of seeing a confusing situation is somewhat diminished. + */ + DWORD_PTR affinity, system_affinity; + + if (GetProcessAffinityMask(service->process_handle, &affinity, &system_affinity)) affinity = service->affinity & system_affinity; + else { + affinity = (DWORD_PTR) service->affinity; + log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_GETPROCESSAFFINITYMASK_FAILED, service->name, error_string(GetLastError()), 0); + } + + if (! SetProcessAffinityMask(service->process_handle, affinity)) { + log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_SETPROCESSAFFINITYMASK_FAILED, service->name, error_string(GetLastError()), 0); + } + + ResumeThread(pi.hThread); + } + /* Wait for a clean startup before changing the service status to RUNNING but be mindful of the fact that we are blocking the service control manager @@ -1337,6 +1608,9 @@ int start_service(nssm_service_t *service) { else service->throttle = 0; } + /* Ensure the restart delay is always applied. */ + if (service->restart_delay && ! service->throttle) service->throttle++; + return 0; } @@ -1348,6 +1622,8 @@ int stop_service(nssm_service_t *service, unsigned long exitcode, bool graceful, service->wait_handle = 0; } + service->rotate_stdout_online = service->rotate_stderr_online = NSSM_ROTATE_OFFLINE; + if (default_action && ! exitcode && ! graceful) { log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_GRACEFUL_SUICIDE, service->name, service->exe, exit_action_strings[NSSM_EXIT_UNCLEAN], exit_action_strings[NSSM_EXIT_UNCLEAN], exit_action_strings[NSSM_EXIT_UNCLEAN], exit_action_strings[NSSM_EXIT_REALLY], 0); graceful = true; @@ -1395,6 +1671,8 @@ void CALLBACK end_service(void *arg, unsigned char why) { service->stopping = true; + service->rotate_stdout_online = service->rotate_stderr_online = NSSM_ROTATE_OFFLINE; + /* Check exit code */ unsigned long exitcode = 0; TCHAR code[16]; @@ -1479,14 +1757,22 @@ void throttle_restart(nssm_service_t *service) { /* This can't be a restart if the service is already running. */ if (! service->throttle++) return; - int ms = throttle_milliseconds(service->throttle); + unsigned long ms; + unsigned long throttle_ms = throttle_milliseconds(service->throttle); + TCHAR threshold[8], milliseconds[8]; + + if (service->restart_delay > throttle_ms) ms = service->restart_delay; + else ms = throttle_ms; if (service->throttle > 7) service->throttle = 8; - TCHAR threshold[8], milliseconds[8]; - _sntprintf_s(threshold, _countof(threshold), _TRUNCATE, _T("%lu"), service->throttle_delay); _sntprintf_s(milliseconds, _countof(milliseconds), _TRUNCATE, _T("%lu"), ms); - log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_THROTTLED, service->name, threshold, milliseconds, 0); + + if (service->throttle == 1 && service->restart_delay > throttle_ms) log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_RESTART_DELAY, service->name, milliseconds, 0); + else { + _sntprintf_s(threshold, _countof(threshold), _TRUNCATE, _T("%lu"), service->throttle_delay); + log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_THROTTLED, service->name, threshold, milliseconds, 0); + } if (use_critical_section) EnterCriticalSection(&service->throttle_section); else if (service->throttle_timer) {