You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

service.cpp 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784
  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::callbackTimeout_ms = 30 * 1000;
  102. Service::Service() {
  103. }
  104. Service &Service::getInstance() {
  105. std::lock_guard<std::mutex> scopeMutex(objectMutex);
  106. static Service service;
  107. return service;
  108. }
  109. int Service::main(int argc, char *argv[]) {
  110. // Under Windows, only arg 0 is passed. Under *nix, all arguments
  111. // are passed.
  112. loadArguments(argc, (char **) argv);
  113. #ifdef DEBUG_LOG_FILE
  114. std::ofstream logStream;
  115. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  116. logStream << "Service::main. argc: " << argc << std::endl;
  117. for (int i = 0; i < argc; i++) {
  118. logStream << "arg " << i << ": '" << argv[i] << "'" << std::endl;
  119. }
  120. logStream.close();
  121. #endif
  122. #ifdef WIN32
  123. SERVICE_TABLE_ENTRY ServiceTable[] = {
  124. {(LPTSTR) "", ServiceMain},
  125. {NULL, NULL}
  126. };
  127. if (StartServiceCtrlDispatcher(ServiceTable) == FALSE) {
  128. return GetLastError();
  129. }
  130. return 0;
  131. #else
  132. pid_t pid;
  133. // Fork the process.
  134. pid = fork();
  135. if (pid < 0) {
  136. perror("Error from first fork");
  137. return(EXIT_FAILURE);
  138. }
  139. // Terminate the parent.
  140. if (pid > 0) {
  141. return(EXIT_SUCCESS);
  142. }
  143. // This is the child. Become the session leader.
  144. if (setsid() < 0) {
  145. perror("Error from setsid");
  146. return(EXIT_FAILURE);
  147. }
  148. // Fork again.
  149. pid = fork();
  150. if (pid < 0) {
  151. perror("Error from second fork");
  152. return(EXIT_FAILURE);
  153. }
  154. // Terminate the parent.
  155. if (pid > 0) {
  156. return(EXIT_SUCCESS);
  157. }
  158. // Set default file permissions. This call always succeeds.
  159. umask(0);
  160. // Disassociate the process from the default directory of the
  161. // grandparent.
  162. if (chdir("/") != 0) {
  163. perror("Error from chdir");
  164. return(EXIT_FAILURE);
  165. }
  166. // Initialize the set of signals to wait for.
  167. if (sigemptyset(&signalSet) != 0) {
  168. perror("Error from sigemptyset");
  169. return(EXIT_FAILURE);
  170. }
  171. if ((sigaddset(&signalSet, SIGTSTP) != 0) ||
  172. (sigaddset(&signalSet, SIGCONT) != 0) ||
  173. (sigaddset(&signalSet, SIGHUP) != 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::setCallbackTimeout_ms(int timeout_ms) {
  289. callbackTimeout_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 = callbackTimeout_ms;
  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 = callbackTimeout_ms;
  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. #ifdef DEBUG_LOG_FILE
  419. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  420. logStream << "processCtrlMessage. Received "
  421. << (message == SERVICE_CONTROL_STOP ? "STOP" : "SHUTDOWN")
  422. << std::endl;
  423. logStream.close();
  424. #endif
  425. serviceStatus.dwControlsAccepted = 0;
  426. serviceStatus.dwCurrentState = SERVICE_STOP_PENDING;
  427. serviceStatus.dwWin32ExitCode = NO_ERROR;
  428. serviceStatus.dwCheckPoint = 1;
  429. serviceStatus.dwWaitHint = callbackTimeout_ms;
  430. (void) SetServiceStatus(serviceStatusHandle, &serviceStatus);
  431. stopReceived = true;
  432. for (auto callback : stopCallbacks) {
  433. (*callback)();
  434. serviceStatus.dwCheckPoint++;
  435. (void) SetServiceStatus(serviceStatusHandle, &serviceStatus);
  436. }
  437. break;
  438. default:
  439. break;
  440. }
  441. }
  442. #else
  443. void Service::processMessages() {
  444. int sigNum;
  445. int status;
  446. while (true) {
  447. // Wait for a signal.
  448. status = sigwait(&signalSet, &sigNum);
  449. if (0 != status) {
  450. perror("Error from sigwait");
  451. // TODO: Implement recovery.
  452. ;
  453. }
  454. // Process the message.
  455. switch (sigNum) {
  456. case SIGTSTP:
  457. {
  458. pauseReceived = true;
  459. callbacksActive = true;
  460. // Get the timeout time.
  461. timeoutTime =
  462. std::chrono::steady_clock::now() +
  463. std::chrono::milliseconds(callbackTimeout_ms);
  464. // Start watchdog thread.
  465. std::thread watchdogThread(&Service::watchdog, this);
  466. #ifdef DEBUG_LOG_FILE
  467. std::ofstream logStream;
  468. auto startTime = std::chrono::steady_clock::now();
  469. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  470. logStream << "Service::processMessages. Calling Pause callbacks--"
  471. << std::endl;
  472. #endif
  473. for (auto callback : pauseCallbacks) {
  474. (*callback)();
  475. timeoutTime =
  476. std::chrono::steady_clock::now() +
  477. std::chrono::milliseconds(callbackTimeout_ms);
  478. #ifdef DEBUG_LOG_FILE
  479. logStream << "Service::processMessages. "
  480. << "Cumulative time after callback (ms): "
  481. << std::chrono::duration_cast<std::chrono::milliseconds>
  482. (std::chrono::steady_clock::now() - startTime).count()
  483. << std::endl;
  484. #endif
  485. }
  486. callbacksActive = false;
  487. #ifdef DEBUG_LOG_FILE
  488. logStream << "Service::processMessages. "
  489. << "Cumulative time after all callback (ms): "
  490. << std::chrono::duration_cast<std::chrono::milliseconds>
  491. (std::chrono::steady_clock::now() - startTime).count()
  492. << std::endl;
  493. #endif
  494. watchdogThread.join();
  495. #ifdef DEBUG_LOG_FILE
  496. logStream << "Service::processMessages. "
  497. <<" Cumulative time after joining watchdog (ms): "
  498. << std::chrono::duration_cast<std::chrono::milliseconds>
  499. (std::chrono::steady_clock::now() - startTime).count()
  500. << std::endl;
  501. logStream.close();
  502. #endif
  503. }
  504. break;
  505. case SIGCONT:
  506. {
  507. resumeReceived = true;
  508. callbacksActive = true;
  509. // Get the timeout time.
  510. timeoutTime =
  511. std::chrono::steady_clock::now() +
  512. std::chrono::milliseconds(callbackTimeout_ms);
  513. // Start watchdog thread.
  514. std::thread watchdogThread(&Service::watchdog, this);
  515. for (auto callback : resumeCallbacks) {
  516. (*callback)();
  517. timeoutTime =
  518. std::chrono::steady_clock::now() +
  519. std::chrono::milliseconds(callbackTimeout_ms);
  520. }
  521. callbacksActive = false;
  522. watchdogThread.join();
  523. }
  524. break;
  525. case SIGTERM:
  526. {
  527. stopReceived = true;
  528. callbacksActive = true;
  529. // Get the timeout time.
  530. timeoutTime =
  531. std::chrono::steady_clock::now() +
  532. std::chrono::milliseconds(callbackTimeout_ms);
  533. // Start watchdog thread.
  534. std::thread watchdogThread(&Service::watchdog, this);
  535. for (auto callback : stopCallbacks) {
  536. (*callback)();
  537. timeoutTime =
  538. std::chrono::steady_clock::now() +
  539. std::chrono::milliseconds(callbackTimeout_ms);
  540. }
  541. callbacksActive = false;
  542. watchdogThread.join();
  543. }
  544. // Exit.
  545. return;
  546. break;
  547. default:
  548. ;
  549. } // switch.
  550. } // while.
  551. }
  552. void Service::watchdog() {
  553. #ifdef DEBUG_LOG_FILE
  554. auto startTime = std::chrono::steady_clock::now();
  555. std::ofstream logStream;
  556. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  557. logStream << "**Service::watchdog. Thread starting." << std::endl;
  558. logStream.close();
  559. #endif
  560. // Sleep and check whether the process should exit.
  561. std::chrono::milliseconds sleepTime(100);
  562. while (std::chrono::steady_clock::now() < timeoutTime) {
  563. std::this_thread::sleep_for(sleepTime);
  564. if (!callbacksActive) {
  565. #ifdef DEBUG_LOG_FILE
  566. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  567. logStream << "**Service::watchdog. Exiting at "
  568. << std::chrono::duration_cast<std::chrono::milliseconds>
  569. (std::chrono::steady_clock::now() - startTime).count()
  570. << " ms after starting"
  571. << std::endl;
  572. logStream.close();
  573. #endif
  574. return;
  575. }
  576. #ifdef DEBUG_LOG_FILE
  577. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  578. logStream << "Service::watchdog. Cumulative time since starting (ms): "
  579. << std::chrono::duration_cast<std::chrono::milliseconds>
  580. (std::chrono::steady_clock::now() - startTime).count()
  581. << std::endl;
  582. logStream.close();
  583. #endif
  584. }
  585. // Timeout expired.
  586. #ifdef DEBUG_LOG_FILE
  587. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  588. logStream << "**Service::watchdog. Callback timeout expired. "
  589. << "Cumulative time (ms): "
  590. << std::chrono::duration_cast<std::chrono::milliseconds>
  591. (std::chrono::steady_clock::now() - startTime).count()
  592. << std::endl;
  593. logStream.close();
  594. #endif
  595. std::exit(EXIT_FAILURE);
  596. }
  597. #endif
  598. }