Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

service.cpp 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  1. // \file service.cpp
  2. //
  3. // Copyright (C) 2014 MicroNeil Research Corporation.
  4. //
  5. // This program is part of the MicroNeil Research Open Library Project. For
  6. // more information go to http://www.microneil.com/OpenLibrary/index.html
  7. //
  8. // This program is free software; you can redistribute it and/or modify it
  9. // under the terms of the GNU General Public License as published by the
  10. // Free Software Foundation; either version 2 of the License, or (at your
  11. // option) any later version.
  12. //
  13. // This program is distributed in the hope that it will be useful, but WITHOUT
  14. // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  15. // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  16. // more details.
  17. //
  18. // You should have received a copy of the GNU General Public License along with
  19. // this program; if not, write to the Free Software Foundation, Inc., 59 Temple
  20. // Place, Suite 330, Boston, MA 02111-1307 USA
  21. //==============================================================================
  22. #ifdef WIN32
  23. #include <windows.h>
  24. #include <strsafe.h>
  25. #else
  26. #include <unistd.h>
  27. #include <sys/types.h>
  28. #include <sys/stat.h>
  29. #include <fcntl.h>
  30. #include <signal.h>
  31. #endif
  32. #ifdef DEBUG_LOG_FILE
  33. #include <fstream>
  34. #endif
  35. #include <cstdio>
  36. #include <cstdlib>
  37. #include <thread>
  38. #include "service.hpp"
  39. #ifdef WIN32
  40. // Application main entry point for Windows.
  41. int main(int argc, char *argv[]) {
  42. #ifdef DEBUG_LOG_FILE
  43. std::ofstream logStream;
  44. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  45. logStream << "main. argc: " << argc << std::endl;
  46. for (int i = 0; i < argc; i++) {
  47. logStream << "arg " << i << ": '" << argv[i] << "'" << std::endl;
  48. }
  49. logStream.close();
  50. #endif
  51. CodeDweller::Service &service = CodeDweller::Service::getInstance();
  52. return service.main(argc, (char **) argv);
  53. }
  54. // Service entry point for Windows.
  55. VOID WINAPI ServiceMain(DWORD argc, LPTSTR *argv) {
  56. #ifdef DEBUG_LOG_FILE
  57. std::ofstream logStream;
  58. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  59. logStream << "ServiceMain. argc: " << argc << std::endl;
  60. for (unsigned int i = 0; i < argc; i++) {
  61. logStream << "arg " << i << ": '" << argv[i] << "'" << std::endl;
  62. }
  63. logStream.close();
  64. #endif
  65. CodeDweller::Service &service = CodeDweller::Service::getInstance();
  66. return service.serviceMain(argc, argv);
  67. }
  68. /// Control message handler for Windows.
  69. VOID WINAPI ServiceCtrlHandler(DWORD message) {
  70. #ifdef DEBUG_LOG_FILE
  71. std::ofstream logStream;
  72. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  73. logStream << "ServiceCtrlHandler. message: " << message
  74. << ". Calling processCtrlMessage" << std::endl;
  75. logStream.close();
  76. #endif
  77. CodeDweller::Service &service = CodeDweller::Service::getInstance();
  78. service.processCtrlMessage(message);
  79. #ifdef DEBUG_LOG_FILE
  80. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  81. logStream << "ServiceCtrlHandler. Done." << std::endl;
  82. logStream.close();
  83. #endif
  84. }
  85. #else
  86. // Main program for *nix daemon.
  87. int main(int argc, char *argv[]) {
  88. CodeDweller::Service &service = CodeDweller::Service::getInstance();
  89. return service.main(argc, argv);
  90. }
  91. #endif
  92. namespace CodeDweller {
  93. std::mutex Service::objectMutex;
  94. std::vector<std::string> Service::cmdLineArgs;
  95. bool Service::pauseReceived = false;
  96. bool Service::resumeReceived = false;
  97. bool Service::stopReceived = false;
  98. std::vector<Service::Callback *> Service::pauseCallbacks;
  99. std::vector<Service::Callback *> Service::resumeCallbacks;
  100. std::vector<Service::Callback *> Service::stopCallbacks;
  101. int Service::stopCallbackTimeout_ms = 30 * 1000;
  102. Service::Service() :
  103. stopCallbacksActive(true) {
  104. }
  105. Service &Service::getInstance() {
  106. std::lock_guard<std::mutex> scopeMutex(objectMutex);
  107. static Service service;
  108. return service;
  109. }
  110. int Service::main(int argc, char *argv[]) {
  111. // Under Windows, only arg 0 is passed. Under *nix, all arguments
  112. // are passed.
  113. loadArguments(argc, (char **) argv);
  114. #ifdef DEBUG_LOG_FILE
  115. std::ofstream logStream;
  116. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  117. logStream << "Service::main. argc: " << argc << std::endl;
  118. for (int i = 0; i < argc; i++) {
  119. logStream << "arg " << i << ": '" << argv[i] << "'" << std::endl;
  120. }
  121. logStream.close();
  122. #endif
  123. #ifdef WIN32
  124. SERVICE_TABLE_ENTRY ServiceTable[] = {
  125. {(LPTSTR) "", ServiceMain},
  126. {NULL, NULL}
  127. };
  128. if (StartServiceCtrlDispatcher(ServiceTable) == FALSE) {
  129. return GetLastError();
  130. }
  131. return 0;
  132. #else
  133. pid_t pid;
  134. // Fork the process.
  135. pid = fork();
  136. if (pid < 0) {
  137. perror("Error from first fork");
  138. return(EXIT_FAILURE);
  139. }
  140. // Terminate the parent.
  141. if (pid > 0) {
  142. return(EXIT_SUCCESS);
  143. }
  144. // This is the child. Become the session leader.
  145. if (setsid() < 0) {
  146. perror("Error from setsid");
  147. return(EXIT_FAILURE);
  148. }
  149. // Fork again.
  150. pid = fork();
  151. if (pid < 0) {
  152. perror("Error from second fork");
  153. return(EXIT_FAILURE);
  154. }
  155. // Terminate the parent.
  156. if (pid > 0) {
  157. return(EXIT_SUCCESS);
  158. }
  159. // Set default file permissions. This call always succeeds.
  160. umask(0);
  161. // Disassociate the process from the default directory of the
  162. // grandparent.
  163. if (chdir("/") != 0) {
  164. perror("Error from chdir");
  165. return(EXIT_FAILURE);
  166. }
  167. // Initialize the set of signals to wait for.
  168. if (sigemptyset(&signalSet) != 0) {
  169. perror("Error from sigemptyset");
  170. return(EXIT_FAILURE);
  171. }
  172. if ((sigaddset(&signalSet, SIGTSTP) != 0) ||
  173. (sigaddset(&signalSet, SIGCONT) != 0) ||
  174. (sigaddset(&signalSet, SIGTERM) != 0)) {
  175. perror("Error from sigaddset");
  176. return(EXIT_FAILURE);
  177. }
  178. // Block the signals.
  179. if (sigprocmask(SIG_BLOCK, &signalSet, NULL) != 0) {
  180. perror("Error from sigprocmask");
  181. return(EXIT_FAILURE);
  182. }
  183. // Close all open file descriptors.
  184. for (int fd = 2; fd >= 0; fd--) {
  185. if (close(fd) != 0) {
  186. // There is no controlling terminal to send any message to.
  187. return(EXIT_FAILURE);
  188. }
  189. }
  190. // Connect standard I/O to the null device.
  191. int fd;
  192. // stdin.
  193. fd = open("/dev/null", O_RDONLY);
  194. if (fd < 0) {
  195. return(EXIT_FAILURE);
  196. }
  197. // stdout.
  198. fd = open("/dev/null", O_WRONLY);
  199. if (fd < 0) {
  200. return(EXIT_FAILURE);
  201. }
  202. // stderr.
  203. fd = open("/dev/null", O_WRONLY);
  204. if (fd < 0) {
  205. return(EXIT_FAILURE);
  206. }
  207. // Start the thread to process messages.
  208. std::thread messageThread(&Service::processMessages, this);
  209. // Run the service.
  210. int status;
  211. status = run();
  212. // Send a Stop message so that messageThread exits.
  213. pthread_kill(messageThread.native_handle(), SIGTERM);
  214. messageThread.join();
  215. return(status);
  216. #endif
  217. }
  218. #ifdef WIN32
  219. void Service::serviceMain(DWORD argc, LPTSTR *argv) {
  220. // Arg 0 contains the service name; skip it. The remaining
  221. // arguments contain the command-line arguments, excluding the
  222. // executable name; append them to the object's argument list.
  223. loadArguments(argc - 1, (char **) argv + 1);
  224. // Register the service control handler with the SCM.
  225. serviceStatusHandle =
  226. RegisterServiceCtrlHandler("", ServiceCtrlHandler);
  227. #ifdef DEBUG_LOG_FILE
  228. std::ofstream logStream;
  229. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  230. logStream << "ServiceMain. argc: " << argc << std::endl;
  231. for (DWORD i = 0; i < argc; i++) {
  232. logStream << "arg " << i << ": '" << argv[i] << "'" << std::endl;
  233. }
  234. logStream << " serviceStatusHandle == NULL: " <<
  235. (NULL == serviceStatusHandle) << std::endl;
  236. logStream.close();
  237. #endif
  238. if (serviceStatusHandle == NULL) {
  239. return;
  240. }
  241. ZeroMemory(&serviceStatus, sizeof(serviceStatus));
  242. serviceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
  243. serviceStatus.dwControlsAccepted = 0;
  244. serviceStatus.dwCurrentState = SERVICE_START_PENDING;
  245. serviceStatus.dwWin32ExitCode = NO_ERROR;
  246. serviceStatus.dwServiceSpecificExitCode = 0;
  247. serviceStatus.dwCheckPoint = 0;
  248. serviceStatus.dwWaitHint = 5000;
  249. (void) SetServiceStatus(serviceStatusHandle, &serviceStatus);
  250. // Tell the service controller that the service has started.
  251. serviceStatus.dwControlsAccepted =
  252. SERVICE_ACCEPT_STOP |
  253. SERVICE_ACCEPT_PAUSE_CONTINUE;
  254. serviceStatus.dwCurrentState = SERVICE_RUNNING;
  255. serviceStatus.dwWin32ExitCode = 0;
  256. serviceStatus.dwCheckPoint = 0;
  257. (void) SetServiceStatus(serviceStatusHandle, &serviceStatus);
  258. #ifdef DEBUG_LOG_FILE
  259. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  260. logStream << "Starting application thread." << std::endl;
  261. logStream.close();
  262. #endif
  263. // Start the application thread.
  264. int status;
  265. status = run();
  266. // Change status to stopped.
  267. serviceStatus.dwControlsAccepted = 0;
  268. serviceStatus.dwCurrentState = SERVICE_STOPPED;
  269. serviceStatus.dwWin32ExitCode = status;
  270. serviceStatus.dwCheckPoint = 0;
  271. (void) SetServiceStatus(serviceStatusHandle, &serviceStatus);
  272. #ifdef DEBUG_LOG_FILE
  273. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  274. logStream << "Exiting." << std::endl;
  275. logStream.close();
  276. #endif
  277. return;
  278. }
  279. #endif
  280. void Service::loadArguments(int argc, char *argv[]) {
  281. for (int i = 0; i < argc; i++) {
  282. cmdLineArgs.push_back(argv[i]);
  283. }
  284. }
  285. const std::vector<std::string> &Service::arguments() {
  286. return cmdLineArgs;
  287. }
  288. void Service::setStopCallbackTimeout_ms(int timeout_ms) {
  289. stopCallbackTimeout_ms = (timeout_ms < 1 ? 1 : timeout_ms);
  290. }
  291. void Service::onPauseCall(Callback &pauseFunctor) {
  292. std::lock_guard<std::mutex> scopeMutex(objectMutex);
  293. pauseCallbacks.push_back(&pauseFunctor);
  294. }
  295. void Service::onResumeCall(Callback &resumeFunctor) {
  296. std::lock_guard<std::mutex> scopeMutex(objectMutex);
  297. resumeCallbacks.push_back(&resumeFunctor);
  298. }
  299. void Service::onStopCall(Callback &stopFunctor) {
  300. std::lock_guard<std::mutex> scopeMutex(objectMutex);
  301. stopCallbacks.push_back(&stopFunctor);
  302. }
  303. bool Service::receivedPause() {
  304. return (pauseReceived);
  305. }
  306. bool Service::receivedResume() {
  307. return (resumeReceived);
  308. }
  309. bool Service::receivedStop() {
  310. return (stopReceived);
  311. }
  312. void Service::clearReceivedPause() {
  313. pauseReceived = false;
  314. }
  315. void Service::clearReceivedResume() {
  316. resumeReceived = false;
  317. }
  318. void Service::clearReceivedStop() {
  319. stopReceived = false;
  320. }
  321. #ifdef WIN32
  322. void Service::processCtrlMessage(DWORD message) {
  323. #ifdef DEBUG_LOG_FILE
  324. std::ofstream logStream;
  325. auto startTime = std::chrono::steady_clock::now();
  326. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  327. logStream << "processCtrlMessage. message: " << message << std::endl;
  328. logStream.close();
  329. #endif
  330. switch (message) {
  331. case SERVICE_CONTROL_PAUSE:
  332. #ifdef DEBUG_LOG_FILE
  333. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  334. logStream << "processCtrlMessage. Received Pause" << std::endl;
  335. logStream.close();
  336. #endif
  337. serviceStatus.dwControlsAccepted = 0;
  338. serviceStatus.dwCurrentState = SERVICE_PAUSE_PENDING;
  339. serviceStatus.dwWin32ExitCode = NO_ERROR;
  340. serviceStatus.dwCheckPoint = 1;
  341. serviceStatus.dwWaitHint = 1000 * 60;
  342. (void) SetServiceStatus(serviceStatusHandle, &serviceStatus);
  343. pauseReceived = true;
  344. #ifdef DEBUG_LOG_FILE
  345. startTime = std::chrono::steady_clock::now();
  346. #endif
  347. for (auto callback : pauseCallbacks) {
  348. (*callback)();
  349. serviceStatus.dwCheckPoint++;
  350. #ifdef DEBUG_LOG_FILE
  351. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  352. logStream << "Service::processCtrlMessage. "
  353. << "Cumulative time after callback (ms): "
  354. << std::chrono::duration_cast<std::chrono::milliseconds>
  355. (std::chrono::steady_clock::now() - startTime).count()
  356. << ", dwWaitHint: " << serviceStatus.dwWaitHint
  357. << std::endl;
  358. logStream.close();
  359. #endif
  360. (void) SetServiceStatus(serviceStatusHandle, &serviceStatus);
  361. #ifdef DEBUG_LOG_FILE
  362. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  363. logStream << "Service::processCtrlMessage. "
  364. << "Cumulative time after SetServiceStatus (ms): "
  365. << std::chrono::duration_cast<std::chrono::milliseconds>
  366. (std::chrono::steady_clock::now() - startTime).count()
  367. << std::endl;
  368. logStream.close();
  369. #endif
  370. }
  371. serviceStatus.dwControlsAccepted =
  372. SERVICE_ACCEPT_SHUTDOWN |
  373. SERVICE_ACCEPT_STOP |
  374. SERVICE_ACCEPT_PAUSE_CONTINUE;
  375. serviceStatus.dwCurrentState = SERVICE_PAUSED;
  376. serviceStatus.dwWin32ExitCode = NO_ERROR;
  377. serviceStatus.dwCheckPoint = 0;
  378. (void) SetServiceStatus(serviceStatusHandle, &serviceStatus);
  379. #ifdef DEBUG_LOG_FILE
  380. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  381. logStream << "Service::processCtrlMessage. "
  382. << "Cumulative time after final SetServiceStatus (ms): "
  383. << std::chrono::duration_cast<std::chrono::milliseconds>
  384. (std::chrono::steady_clock::now() - startTime).count()
  385. << std::endl;
  386. logStream.close();
  387. #endif
  388. break;
  389. case SERVICE_CONTROL_CONTINUE:
  390. #ifdef DEBUG_LOG_FILE
  391. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  392. logStream << "processCtrlMessage. Received Resume" << std::endl;
  393. logStream.close();
  394. #endif
  395. serviceStatus.dwControlsAccepted = 0;
  396. serviceStatus.dwCurrentState = SERVICE_CONTINUE_PENDING;
  397. serviceStatus.dwWin32ExitCode = NO_ERROR;
  398. serviceStatus.dwCheckPoint = 1;
  399. serviceStatus.dwWaitHint = 1000 * 60;
  400. (void) SetServiceStatus(serviceStatusHandle, &serviceStatus);
  401. resumeReceived = true;
  402. for (auto callback : resumeCallbacks) {
  403. (*callback)();
  404. serviceStatus.dwCheckPoint++;
  405. (void) SetServiceStatus(serviceStatusHandle, &serviceStatus);
  406. }
  407. serviceStatus.dwControlsAccepted =
  408. SERVICE_ACCEPT_SHUTDOWN |
  409. SERVICE_ACCEPT_STOP |
  410. SERVICE_ACCEPT_PAUSE_CONTINUE;
  411. serviceStatus.dwCurrentState = SERVICE_RUNNING;
  412. serviceStatus.dwWin32ExitCode = NO_ERROR;
  413. serviceStatus.dwCheckPoint = 0;
  414. (void) SetServiceStatus(serviceStatusHandle, &serviceStatus);
  415. break;
  416. case SERVICE_CONTROL_STOP:
  417. case SERVICE_CONTROL_SHUTDOWN:
  418. {
  419. #ifdef DEBUG_LOG_FILE
  420. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  421. logStream << "processCtrlMessage. Received "
  422. << (message == SERVICE_CONTROL_STOP ? "STOP" : "SHUTDOWN")
  423. << std::endl;
  424. logStream.close();
  425. #endif
  426. serviceStatus.dwControlsAccepted = 0;
  427. serviceStatus.dwCurrentState = SERVICE_STOP_PENDING;
  428. serviceStatus.dwWin32ExitCode = NO_ERROR;
  429. serviceStatus.dwCheckPoint = 1;
  430. serviceStatus.dwWaitHint = stopCallbackTimeout_ms;
  431. (void) SetServiceStatus(serviceStatusHandle, &serviceStatus);
  432. stopReceived = true;
  433. stopCallbacksActive = true;
  434. // Get the timeout time.
  435. timeoutTime =
  436. std::chrono::steady_clock::now() +
  437. std::chrono::milliseconds(stopCallbackTimeout_ms);
  438. // Start watchdog thread.
  439. std::thread watchdogThread(&Service::watchdog, this);
  440. for (auto callback : stopCallbacks) {
  441. (*callback)();
  442. timeoutTime =
  443. std::chrono::steady_clock::now() +
  444. std::chrono::milliseconds(stopCallbackTimeout_ms);
  445. serviceStatus.dwCheckPoint++;
  446. (void) SetServiceStatus(serviceStatusHandle, &serviceStatus);
  447. }
  448. stopCallbacksActive = false;
  449. watchdogThread.join();
  450. }
  451. break;
  452. default:
  453. break;
  454. }
  455. }
  456. #else
  457. void Service::processMessages() {
  458. int sigNum;
  459. int status;
  460. while (true) {
  461. // Wait for a signal.
  462. status = sigwait(&signalSet, &sigNum);
  463. if (0 != status) {
  464. perror("Error from sigwait");
  465. // TODO: Implement recovery.
  466. ;
  467. }
  468. // Process the message.
  469. switch (sigNum) {
  470. case SIGTSTP:
  471. {
  472. pauseReceived = true;
  473. for (auto callback : pauseCallbacks) {
  474. (*callback)();
  475. }
  476. }
  477. break;
  478. case SIGCONT:
  479. {
  480. resumeReceived = true;
  481. for (auto callback : resumeCallbacks) {
  482. (*callback)();
  483. }
  484. }
  485. break;
  486. case SIGTERM:
  487. {
  488. stopReceived = true;
  489. stopCallbacksActive = true;
  490. // Get the timeout time.
  491. timeoutTime =
  492. std::chrono::steady_clock::now() +
  493. std::chrono::milliseconds(stopCallbackTimeout_ms);
  494. // Start watchdog thread.
  495. std::thread watchdogThread(&Service::watchdog, this);
  496. for (auto callback : stopCallbacks) {
  497. (*callback)();
  498. timeoutTime =
  499. std::chrono::steady_clock::now() +
  500. std::chrono::milliseconds(stopCallbackTimeout_ms);
  501. }
  502. stopCallbacksActive = false;
  503. watchdogThread.join();
  504. }
  505. // Exit.
  506. return;
  507. break;
  508. default:
  509. ;
  510. } // switch.
  511. } // while.
  512. }
  513. void Service::watchdog() {
  514. // Sleep and check whether the process should exit.
  515. std::chrono::milliseconds sleepTime(100);
  516. while (std::chrono::steady_clock::now() < timeoutTime) {
  517. std::this_thread::sleep_for(sleepTime);
  518. if (!stopCallbacksActive) {
  519. return;
  520. }
  521. }
  522. // Timeout expired.
  523. std::exit(EXIT_FAILURE);
  524. }
  525. #endif
  526. }