ServerApplication.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. //
  2. // ServerApplication.cpp
  3. //
  4. // $Id: //poco/Main/Util/src/ServerApplication.cpp#22 $
  5. //
  6. // Library: Util
  7. // Package: Application
  8. // Module: ServerApplication
  9. //
  10. // Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
  11. // and Contributors.
  12. //
  13. // Permission is hereby granted, free of charge, to any person or organization
  14. // obtaining a copy of the software and accompanying documentation covered by
  15. // this license (the "Software") to use, reproduce, display, distribute,
  16. // execute, and transmit the Software, and to prepare derivative works of the
  17. // Software, and to permit third-parties to whom the Software is furnished to
  18. // do so, all subject to the following:
  19. //
  20. // The copyright notices in the Software and this entire statement, including
  21. // the above license grant, this restriction and the following disclaimer,
  22. // must be included in all copies of the Software, in whole or in part, and
  23. // all derivative works of the Software, unless such copies or derivative
  24. // works are solely in the form of machine-executable object code generated by
  25. // a source language processor.
  26. //
  27. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  28. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  29. // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
  30. // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
  31. // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
  32. // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  33. // DEALINGS IN THE SOFTWARE.
  34. //
  35. #include "Poco/Util/ServerApplication.h"
  36. #include "Poco/Util/Option.h"
  37. #include "Poco/Util/OptionSet.h"
  38. #include "Poco/Exception.h"
  39. #include "Poco/Process.h"
  40. #include "Poco/NumberFormatter.h"
  41. #include "Poco/NamedEvent.h"
  42. #include "Poco/Logger.h"
  43. #if defined(POCO_OS_FAMILY_UNIX)
  44. #include <stdlib.h>
  45. #include <unistd.h>
  46. #include <stdio.h>
  47. #include <signal.h>
  48. #include <sys/stat.h>
  49. #elif defined(POCO_OS_FAMILY_WINDOWS)
  50. #include "Poco/Util/WinService.h"
  51. #include "Poco/UnWindows.h"
  52. #include <cstring>
  53. #endif
  54. #if defined(POCO_WIN32_UTF8)
  55. #include "Poco/UnicodeConverter.h"
  56. #endif
  57. using Poco::NamedEvent;
  58. using Poco::Process;
  59. using Poco::NumberFormatter;
  60. using Poco::Exception;
  61. using Poco::SystemException;
  62. namespace Poco {
  63. namespace Util {
  64. #if defined(POCO_OS_FAMILY_WINDOWS)
  65. Poco::Event ServerApplication::_terminated;
  66. SERVICE_STATUS ServerApplication::_serviceStatus;
  67. SERVICE_STATUS_HANDLE ServerApplication::_serviceStatusHandle = 0;
  68. #endif
  69. ServerApplication::ServerApplication()
  70. {
  71. #if defined(POCO_OS_FAMILY_WINDOWS)
  72. _action = SRV_RUN;
  73. std::memset(&_serviceStatus, 0, sizeof(_serviceStatus));
  74. #endif
  75. }
  76. ServerApplication::~ServerApplication()
  77. {
  78. }
  79. bool ServerApplication::isInteractive() const
  80. {
  81. bool runsInBackground = config().getBool("application.runAsDaemon", false) || config().getBool("application.runAsService", false);
  82. return !runsInBackground;
  83. }
  84. int ServerApplication::run()
  85. {
  86. return Application::run();
  87. }
  88. void ServerApplication::terminate()
  89. {
  90. Process::requestTermination(Process::id());
  91. }
  92. #if defined(POCO_OS_FAMILY_WINDOWS)
  93. //
  94. // Windows specific code
  95. //
  96. BOOL ServerApplication::ConsoleCtrlHandler(DWORD ctrlType)
  97. {
  98. switch (ctrlType)
  99. {
  100. case CTRL_C_EVENT:
  101. case CTRL_CLOSE_EVENT:
  102. case CTRL_BREAK_EVENT:
  103. terminate();
  104. return _terminated.tryWait(10000) ? TRUE : FALSE;
  105. default:
  106. return FALSE;
  107. }
  108. }
  109. void ServerApplication::ServiceControlHandler(DWORD control)
  110. {
  111. switch (control)
  112. {
  113. case SERVICE_CONTROL_STOP:
  114. case SERVICE_CONTROL_SHUTDOWN:
  115. terminate();
  116. _serviceStatus.dwCurrentState = SERVICE_STOP_PENDING;
  117. break;
  118. case SERVICE_CONTROL_INTERROGATE:
  119. break;
  120. }
  121. SetServiceStatus(_serviceStatusHandle, &_serviceStatus);
  122. }
  123. #if defined(POCO_WIN32_UTF8)
  124. void ServerApplication::ServiceMain(DWORD argc, LPWSTR* argv)
  125. #else
  126. void ServerApplication::ServiceMain(DWORD argc, LPTSTR* argv)
  127. #endif
  128. {
  129. ServerApplication& app = static_cast<ServerApplication&>(Application::instance());
  130. #if defined(POCO_WIN32_UTF8)
  131. _serviceStatusHandle = RegisterServiceCtrlHandlerW(L"", ServiceControlHandler);
  132. #else
  133. _serviceStatusHandle = RegisterServiceCtrlHandler("", ServiceControlHandler);
  134. #endif
  135. if (!_serviceStatusHandle)
  136. throw SystemException("cannot register service control handler");
  137. _serviceStatus.dwServiceType = SERVICE_WIN32;
  138. _serviceStatus.dwCurrentState = SERVICE_START_PENDING;
  139. _serviceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
  140. _serviceStatus.dwWin32ExitCode = 0;
  141. _serviceStatus.dwServiceSpecificExitCode = 0;
  142. _serviceStatus.dwCheckPoint = 0;
  143. _serviceStatus.dwWaitHint = 0;
  144. SetServiceStatus(_serviceStatusHandle, &_serviceStatus);
  145. try
  146. {
  147. #if defined(POCO_WIN32_UTF8)
  148. std::vector<std::string> args;
  149. for (DWORD i = 0; i < argc; ++i)
  150. {
  151. std::string arg;
  152. Poco::UnicodeConverter::toUTF8(argv[i], arg);
  153. args.push_back(arg);
  154. }
  155. app.init(args);
  156. #else
  157. app.init(argc, argv);
  158. #endif
  159. _serviceStatus.dwCurrentState = SERVICE_RUNNING;
  160. SetServiceStatus(_serviceStatusHandle, &_serviceStatus);
  161. int rc = app.run();
  162. _serviceStatus.dwWin32ExitCode = rc ? ERROR_SERVICE_SPECIFIC_ERROR : 0;
  163. _serviceStatus.dwServiceSpecificExitCode = rc;
  164. }
  165. catch (Exception& exc)
  166. {
  167. app.logger().log(exc);
  168. _serviceStatus.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR;
  169. _serviceStatus.dwServiceSpecificExitCode = EXIT_CONFIG;
  170. }
  171. catch (...)
  172. {
  173. app.logger().error("fatal error - aborting");
  174. _serviceStatus.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR;
  175. _serviceStatus.dwServiceSpecificExitCode = EXIT_SOFTWARE;
  176. }
  177. try
  178. {
  179. app.uninitialize();
  180. }
  181. catch (...)
  182. {
  183. }
  184. _serviceStatus.dwCurrentState = SERVICE_STOPPED;
  185. SetServiceStatus(_serviceStatusHandle, &_serviceStatus);
  186. }
  187. void ServerApplication::waitForTerminationRequest()
  188. {
  189. SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
  190. std::string evName("POCOTRM");
  191. evName.append(NumberFormatter::formatHex(Process::id(), 8));
  192. NamedEvent ev(evName);
  193. ev.wait();
  194. _terminated.set();
  195. }
  196. int ServerApplication::run(int argc, char** argv)
  197. {
  198. if (!hasConsole() && isService())
  199. {
  200. config().setBool("application.runAsService", true);
  201. return 0;
  202. }
  203. else
  204. {
  205. int rc = EXIT_OK;
  206. try
  207. {
  208. init(argc, argv);
  209. switch (_action)
  210. {
  211. case SRV_REGISTER:
  212. registerService();
  213. rc = EXIT_OK;
  214. break;
  215. case SRV_UNREGISTER:
  216. unregisterService();
  217. rc = EXIT_OK;
  218. break;
  219. default:
  220. rc = run();
  221. uninitialize();
  222. }
  223. }
  224. catch (Exception& exc)
  225. {
  226. logger().log(exc);
  227. rc = EXIT_SOFTWARE;
  228. }
  229. return rc;
  230. }
  231. }
  232. #if defined(POCO_WIN32_UTF8)
  233. int ServerApplication::run(int argc, wchar_t** argv)
  234. {
  235. if (!hasConsole() && isService())
  236. {
  237. config().setBool("application.runAsService", true);
  238. return 0;
  239. }
  240. else
  241. {
  242. int rc = EXIT_OK;
  243. try
  244. {
  245. init(argc, argv);
  246. switch (_action)
  247. {
  248. case SRV_REGISTER:
  249. registerService();
  250. rc = EXIT_OK;
  251. break;
  252. case SRV_UNREGISTER:
  253. unregisterService();
  254. rc = EXIT_OK;
  255. break;
  256. default:
  257. rc = run();
  258. uninitialize();
  259. }
  260. }
  261. catch (Exception& exc)
  262. {
  263. logger().log(exc);
  264. rc = EXIT_SOFTWARE;
  265. }
  266. return rc;
  267. }
  268. }
  269. #endif
  270. bool ServerApplication::isService()
  271. {
  272. #if defined(POCO_WIN32_UTF8)
  273. SERVICE_TABLE_ENTRYW svcDispatchTable[2];
  274. svcDispatchTable[0].lpServiceName = L"";
  275. svcDispatchTable[0].lpServiceProc = ServiceMain;
  276. svcDispatchTable[1].lpServiceName = NULL;
  277. svcDispatchTable[1].lpServiceProc = NULL;
  278. return StartServiceCtrlDispatcherW(svcDispatchTable) != 0;
  279. #else
  280. SERVICE_TABLE_ENTRY svcDispatchTable[2];
  281. svcDispatchTable[0].lpServiceName = "";
  282. svcDispatchTable[0].lpServiceProc = ServiceMain;
  283. svcDispatchTable[1].lpServiceName = NULL;
  284. svcDispatchTable[1].lpServiceProc = NULL;
  285. return StartServiceCtrlDispatcher(svcDispatchTable) != 0;
  286. #endif
  287. }
  288. bool ServerApplication::hasConsole()
  289. {
  290. HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
  291. return hStdOut != INVALID_HANDLE_VALUE && hStdOut != NULL;
  292. }
  293. void ServerApplication::registerService()
  294. {
  295. std::string name = config().getString("application.baseName");
  296. std::string path = config().getString("application.path");
  297. WinService service(name);
  298. if (_displayName.empty())
  299. service.registerService(path);
  300. else
  301. service.registerService(path, _displayName);
  302. logger().information("The application has been successfully registered as a service");
  303. }
  304. void ServerApplication::unregisterService()
  305. {
  306. std::string name = config().getString("application.baseName");
  307. WinService service(name);
  308. service.unregisterService();
  309. logger().information("The service has been successfully unregistered");
  310. }
  311. void ServerApplication::defineOptions(OptionSet& options)
  312. {
  313. Application::defineOptions(options);
  314. options.addOption(
  315. Option("registerService", "", "register application as a service")
  316. .required(false)
  317. .repeatable(false));
  318. options.addOption(
  319. Option("unregisterService", "", "unregister application as a service")
  320. .required(false)
  321. .repeatable(false));
  322. options.addOption(
  323. Option("displayName", "", "specify a display name for the service (only with /registerService)")
  324. .required(false)
  325. .repeatable(false)
  326. .argument("name"));
  327. }
  328. void ServerApplication::handleOption(const std::string& name, const std::string& value)
  329. {
  330. if (name == "registerService")
  331. _action = SRV_REGISTER;
  332. else if (name == "unregisterService")
  333. _action = SRV_UNREGISTER;
  334. else if (name == "displayName")
  335. _displayName = value;
  336. else
  337. Application::handleOption(name, value);
  338. }
  339. #elif defined(POCO_OS_FAMILY_UNIX)
  340. //
  341. // Unix specific code
  342. //
  343. void ServerApplication::waitForTerminationRequest()
  344. {
  345. sigset_t sset;
  346. sigemptyset(&sset);
  347. sigaddset(&sset, SIGINT);
  348. sigaddset(&sset, SIGQUIT);
  349. sigaddset(&sset, SIGTERM);
  350. sigprocmask(SIG_BLOCK, &sset, NULL);
  351. int sig;
  352. sigwait(&sset, &sig);
  353. }
  354. int ServerApplication::run(int argc, char** argv)
  355. {
  356. bool runAsDaemon = isDaemon(argc, argv);
  357. if (runAsDaemon)
  358. {
  359. beDaemon();
  360. }
  361. try
  362. {
  363. init(argc, argv);
  364. if (runAsDaemon)
  365. {
  366. chdir("/");
  367. }
  368. }
  369. catch (Exception& exc)
  370. {
  371. logger().log(exc);
  372. return EXIT_CONFIG;
  373. }
  374. int rc = run();
  375. try
  376. {
  377. uninitialize();
  378. }
  379. catch (Exception& exc)
  380. {
  381. logger().log(exc);
  382. rc = EXIT_CONFIG;
  383. }
  384. return rc;
  385. }
  386. bool ServerApplication::isDaemon(int argc, char** argv)
  387. {
  388. std::string option("--daemon");
  389. for (int i = 1; i < argc; ++i)
  390. {
  391. if (option == argv[i])
  392. return true;
  393. }
  394. return false;
  395. }
  396. void ServerApplication::beDaemon()
  397. {
  398. pid_t pid;
  399. if ((pid = fork()) < 0)
  400. throw SystemException("cannot fork daemon process");
  401. else if (pid != 0)
  402. exit(0);
  403. setsid();
  404. umask(0);
  405. close(0);
  406. close(1);
  407. close(2);
  408. }
  409. void ServerApplication::defineOptions(OptionSet& options)
  410. {
  411. Application::defineOptions(options);
  412. options.addOption(
  413. Option("daemon", "", "run application as a daemon")
  414. .required(false)
  415. .repeatable(false));
  416. }
  417. void ServerApplication::handleOption(const std::string& name, const std::string& value)
  418. {
  419. if (name == "daemon")
  420. {
  421. config().setBool("application.runAsDaemon", true);
  422. }
  423. else Application::handleOption(name, value);
  424. }
  425. #elif defined(POCO_OS_FAMILY_VMS)
  426. //
  427. // VMS specific code
  428. //
  429. namespace
  430. {
  431. static void handleSignal(int sig)
  432. {
  433. ServerApplication::terminate();
  434. }
  435. }
  436. void ServerApplication::waitForTerminationRequest()
  437. {
  438. struct sigaction handler;
  439. handler.sa_handler = handleSignal;
  440. handler.sa_flags = 0;
  441. sigemptyset(&handler.sa_mask);
  442. sigaction(SIGINT, &handler, NULL);
  443. sigaction(SIGQUIT, &handler, NULL);
  444. long ctrlY = LIB$M_CLI_CTRLY;
  445. unsigned short ioChan;
  446. $DESCRIPTOR(ttDsc, "TT:");
  447. lib$disable_ctrl(&ctrlY);
  448. sys$assign(&ttDsc, &ioChan, 0, 0);
  449. sys$qiow(0, ioChan, IO$_SETMODE | IO$M_CTRLYAST, 0, 0, 0, terminate, 0, 0, 0, 0, 0);
  450. sys$qiow(0, ioChan, IO$_SETMODE | IO$M_CTRLCAST, 0, 0, 0, terminate, 0, 0, 0, 0, 0);
  451. std::string evName("POCOTRM");
  452. evName.append(NumberFormatter::formatHex(Process::id(), 8));
  453. NamedEvent ev(evName);
  454. try
  455. {
  456. ev.wait();
  457. }
  458. catch (...)
  459. {
  460. // CTRL-C will cause an exception to be raised
  461. }
  462. sys$dassgn(ioChan);
  463. lib$enable_ctrl(&ctrlY);
  464. }
  465. int ServerApplication::run(int argc, char** argv)
  466. {
  467. try
  468. {
  469. init(argc, argv);
  470. }
  471. catch (Exception& exc)
  472. {
  473. logger().log(exc);
  474. return EXIT_CONFIG;
  475. }
  476. int rc = run();
  477. try
  478. {
  479. uninitialize();
  480. }
  481. catch (Exception& exc)
  482. {
  483. logger().log(exc);
  484. rc = EXIT_CONFIG;
  485. }
  486. return rc;
  487. }
  488. void ServerApplication::defineOptions(OptionSet& options)
  489. {
  490. Application::defineOptions(options);
  491. }
  492. void ServerApplication::handleOption(const std::string& name, const std::string& value)
  493. {
  494. Application::handleOption(name, value);
  495. }
  496. #endif
  497. } } // namespace Poco::Util