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 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  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. Service::Service() {
  102. }
  103. Service &Service::getInstance() {
  104. std::lock_guard<std::mutex> scopeMutex(objectMutex);
  105. static Service service;
  106. return service;
  107. }
  108. int Service::main(int argc, char *argv[]) {
  109. // Under Windows, only arg 0 is passed. Under *nix, all arguments
  110. // are passed.
  111. loadArguments(argc, (char **) argv);
  112. #ifdef DEBUG_LOG_FILE
  113. std::ofstream logStream;
  114. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  115. logStream << "Service::main. argc: " << argc << std::endl;
  116. for (int i = 0; i < argc; i++) {
  117. logStream << "arg " << i << ": '" << argv[i] << "'" << std::endl;
  118. }
  119. logStream.close();
  120. #endif
  121. #ifdef WIN32
  122. SERVICE_TABLE_ENTRY ServiceTable[] = {
  123. {(LPTSTR) "", ServiceMain},
  124. {NULL, NULL}
  125. };
  126. if (StartServiceCtrlDispatcher(ServiceTable) == FALSE) {
  127. return GetLastError();
  128. }
  129. return 0;
  130. #else
  131. pid_t pid;
  132. // Fork the process.
  133. pid = fork();
  134. if (pid < 0) {
  135. perror("Error from first fork");
  136. return(EXIT_FAILURE);
  137. }
  138. // Terminate the parent.
  139. if (pid > 0) {
  140. return(EXIT_SUCCESS);
  141. }
  142. // This is the child. Become the session leader.
  143. if (setsid() < 0) {
  144. perror("Error from setsid");
  145. return(EXIT_FAILURE);
  146. }
  147. // Fork again.
  148. pid = fork();
  149. if (pid < 0) {
  150. perror("Error from second fork");
  151. return(EXIT_FAILURE);
  152. }
  153. // Terminate the parent.
  154. if (pid > 0) {
  155. return(EXIT_SUCCESS);
  156. }
  157. // Set default file permissions. This call always succeeds.
  158. umask(0);
  159. // Disassociate the process from the default directory of the
  160. // grandparent.
  161. if (chdir("/") != 0) {
  162. perror("Error from chdir");
  163. return(EXIT_FAILURE);
  164. }
  165. // Initialize the set of signals to wait for.
  166. if (sigemptyset(&signalSet) != 0) {
  167. perror("Error from sigemptyset");
  168. return(EXIT_FAILURE);
  169. }
  170. if ((sigaddset(&signalSet, SIGTSTP) != 0) ||
  171. (sigaddset(&signalSet, SIGCONT) != 0) ||
  172. (sigaddset(&signalSet, SIGHUP) != 0) ||
  173. (sigaddset(&signalSet, SIGTERM) != 0)) {
  174. perror("Error from sigaddset");
  175. return(EXIT_FAILURE);
  176. }
  177. // Block the signals.
  178. if (sigprocmask(SIG_BLOCK, &signalSet, NULL) != 0) {
  179. perror("Error from sigprocmask");
  180. return(EXIT_FAILURE);
  181. }
  182. // Close all open file descriptors.
  183. for (int fd = 2; fd >= 0; fd--) {
  184. if (close(fd) != 0) {
  185. // There is no controlling terminal to send any message to.
  186. return(EXIT_FAILURE);
  187. }
  188. }
  189. // Connect standard I/O to the null device.
  190. int fd;
  191. // stdin.
  192. fd = open("/dev/null", O_RDONLY);
  193. if (fd < 0) {
  194. return(EXIT_FAILURE);
  195. }
  196. // stdout.
  197. fd = open("/dev/null", O_WRONLY);
  198. if (fd < 0) {
  199. return(EXIT_FAILURE);
  200. }
  201. // stderr.
  202. fd = open("/dev/null", O_WRONLY);
  203. if (fd < 0) {
  204. return(EXIT_FAILURE);
  205. }
  206. // Start the thread to process messages.
  207. std::thread messageThread(&Service::processMessages, this);
  208. // Run the service.
  209. int status;
  210. status = run();
  211. // Send a Stop message so that messageThread exits.
  212. pthread_kill(messageThread.native_handle(), SIGTERM);
  213. messageThread.join();
  214. return(status);
  215. #endif
  216. }
  217. #ifdef WIN32
  218. void Service::serviceMain(DWORD argc, LPTSTR *argv) {
  219. // Arg 0 contains the service name; skip it. The remaining
  220. // arguments contain the command-line arguments, excluding the
  221. // executable name; append them to the object's argument list.
  222. loadArguments(argc - 1, (char **) argv + 1);
  223. // Register the service control handler with the SCM.
  224. serviceStatusHandle =
  225. RegisterServiceCtrlHandler("", ServiceCtrlHandler);
  226. #ifdef DEBUG_LOG_FILE
  227. std::ofstream logStream;
  228. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  229. logStream << "ServiceMain. argc: " << argc << std::endl;
  230. for (DWORD i = 0; i < argc; i++) {
  231. logStream << "arg " << i << ": '" << argv[i] << "'" << std::endl;
  232. }
  233. logStream << " serviceStatusHandle == NULL: " <<
  234. (NULL == serviceStatusHandle) << std::endl;
  235. logStream.close();
  236. #endif
  237. if (serviceStatusHandle == NULL) {
  238. return;
  239. }
  240. ZeroMemory(&serviceStatus, sizeof(serviceStatus));
  241. serviceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
  242. serviceStatus.dwControlsAccepted = 0;
  243. serviceStatus.dwCurrentState = SERVICE_START_PENDING;
  244. serviceStatus.dwWin32ExitCode = NO_ERROR;
  245. serviceStatus.dwServiceSpecificExitCode = 0;
  246. serviceStatus.dwCheckPoint = 0;
  247. serviceStatus.dwWaitHint = 5000;
  248. (void) SetServiceStatus(serviceStatusHandle, &serviceStatus);
  249. // Tell the service controller that the service has started.
  250. serviceStatus.dwControlsAccepted =
  251. SERVICE_ACCEPT_STOP |
  252. SERVICE_ACCEPT_PAUSE_CONTINUE;
  253. serviceStatus.dwCurrentState = SERVICE_RUNNING;
  254. serviceStatus.dwWin32ExitCode = 0;
  255. serviceStatus.dwCheckPoint = 0;
  256. (void) SetServiceStatus(serviceStatusHandle, &serviceStatus);
  257. #ifdef DEBUG_LOG_FILE
  258. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  259. logStream << "Starting application thread." << std::endl;
  260. logStream.close();
  261. #endif
  262. // Start the application thread.
  263. int status;
  264. status = run();
  265. // Change status to stopped.
  266. serviceStatus.dwControlsAccepted = 0;
  267. serviceStatus.dwCurrentState = SERVICE_STOPPED;
  268. serviceStatus.dwWin32ExitCode = status;
  269. serviceStatus.dwCheckPoint = 0;
  270. (void) SetServiceStatus(serviceStatusHandle, &serviceStatus);
  271. #ifdef DEBUG_LOG_FILE
  272. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  273. logStream << "Exiting." << std::endl;
  274. logStream.close();
  275. #endif
  276. return;
  277. }
  278. #endif
  279. void Service::loadArguments(int argc, char *argv[]) {
  280. for (int i = 0; i < argc; i++) {
  281. cmdLineArgs.push_back(argv[i]);
  282. }
  283. }
  284. const std::vector<std::string> &Service::arguments() {
  285. return cmdLineArgs;
  286. }
  287. void Service::onPauseCall(Callback &pauseFunctor) {
  288. std::lock_guard<std::mutex> scopeMutex(objectMutex);
  289. pauseCallbacks.push_back(&pauseFunctor);
  290. }
  291. void Service::onResumeCall(Callback &resumeFunctor) {
  292. std::lock_guard<std::mutex> scopeMutex(objectMutex);
  293. resumeCallbacks.push_back(&resumeFunctor);
  294. }
  295. void Service::onStopCall(Callback &stopFunctor) {
  296. std::lock_guard<std::mutex> scopeMutex(objectMutex);
  297. stopCallbacks.push_back(&stopFunctor);
  298. }
  299. bool Service::receivedPause() {
  300. return (pauseReceived);
  301. }
  302. bool Service::receivedResume() {
  303. return (resumeReceived);
  304. }
  305. bool Service::receivedStop() {
  306. return (stopReceived);
  307. }
  308. void Service::clearReceivedPause() {
  309. pauseReceived = false;
  310. }
  311. void Service::clearReceivedResume() {
  312. resumeReceived = false;
  313. }
  314. void Service::clearReceivedStop() {
  315. stopReceived = false;
  316. }
  317. #ifdef WIN32
  318. void Service::processCtrlMessage(DWORD message) {
  319. #ifdef DEBUG_LOG_FILE
  320. std::ofstream logStream;
  321. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  322. logStream << "processCtrlMessage. message: " << message << std::endl;
  323. logStream.close();
  324. #endif
  325. switch (message) {
  326. case SERVICE_CONTROL_PAUSE:
  327. #ifdef DEBUG_LOG_FILE
  328. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  329. logStream << "processCtrlMessage. Received Pause" << std::endl;
  330. logStream.close();
  331. #endif
  332. serviceStatus.dwControlsAccepted = 0;
  333. serviceStatus.dwCurrentState = SERVICE_PAUSE_PENDING;
  334. serviceStatus.dwWin32ExitCode = NO_ERROR;
  335. serviceStatus.dwCheckPoint = 1;
  336. serviceStatus.dwWaitHint = 5000;
  337. (void) SetServiceStatus(serviceStatusHandle, &serviceStatus);
  338. pauseReceived = true;
  339. for (auto callback : pauseCallbacks) {
  340. (*callback)();
  341. }
  342. serviceStatus.dwControlsAccepted =
  343. SERVICE_ACCEPT_STOP |
  344. SERVICE_ACCEPT_PAUSE_CONTINUE;
  345. serviceStatus.dwCurrentState = SERVICE_PAUSED;
  346. serviceStatus.dwWin32ExitCode = NO_ERROR;
  347. serviceStatus.dwCheckPoint = 0;
  348. (void) SetServiceStatus(serviceStatusHandle, &serviceStatus);
  349. break;
  350. case SERVICE_CONTROL_CONTINUE:
  351. #ifdef DEBUG_LOG_FILE
  352. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  353. logStream << "processCtrlMessage. Received Resume" << std::endl;
  354. logStream.close();
  355. #endif
  356. serviceStatus.dwControlsAccepted = 0;
  357. serviceStatus.dwCurrentState = SERVICE_CONTINUE_PENDING;
  358. serviceStatus.dwWin32ExitCode = NO_ERROR;
  359. serviceStatus.dwCheckPoint = 1;
  360. serviceStatus.dwWaitHint = 5000;
  361. (void) SetServiceStatus(serviceStatusHandle, &serviceStatus);
  362. resumeReceived = true;
  363. for (auto callback : resumeCallbacks) {
  364. (*callback)();
  365. }
  366. serviceStatus.dwControlsAccepted =
  367. SERVICE_ACCEPT_STOP |
  368. SERVICE_ACCEPT_PAUSE_CONTINUE;
  369. serviceStatus.dwCurrentState = SERVICE_RUNNING;
  370. serviceStatus.dwWin32ExitCode = NO_ERROR;
  371. serviceStatus.dwCheckPoint = 0;
  372. (void) SetServiceStatus(serviceStatusHandle, &serviceStatus);
  373. break;
  374. case SERVICE_CONTROL_STOP:
  375. #ifdef DEBUG_LOG_FILE
  376. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  377. logStream << "processCtrlMessage. Received STOP" << std::endl;
  378. logStream.close();
  379. #endif
  380. serviceStatus.dwControlsAccepted = 0;
  381. serviceStatus.dwCurrentState = SERVICE_STOP_PENDING;
  382. serviceStatus.dwWin32ExitCode = NO_ERROR;
  383. serviceStatus.dwCheckPoint = 1;
  384. serviceStatus.dwWaitHint = 5000;
  385. (void) SetServiceStatus(serviceStatusHandle, &serviceStatus);
  386. stopReceived = true;
  387. for (auto callback : stopCallbacks) {
  388. (*callback)();
  389. }
  390. break;
  391. default:
  392. break;
  393. }
  394. }
  395. #else
  396. void Service::processMessages() {
  397. int sigNum;
  398. int status;
  399. while (true) {
  400. // Wait for a signal.
  401. status = sigwait(&signalSet, &sigNum);
  402. if (0 != status) {
  403. perror("Error from sigwait");
  404. // TODO: Implement recovery.
  405. ;
  406. }
  407. // Process the message.
  408. switch (sigNum) {
  409. case SIGTSTP:
  410. pauseReceived = true;
  411. for (auto callback : pauseCallbacks) {
  412. (*callback)();
  413. }
  414. break;
  415. case SIGCONT:
  416. resumeReceived = true;
  417. for (auto callback : resumeCallbacks) {
  418. (*callback)();
  419. }
  420. break;
  421. case SIGTERM:
  422. stopReceived = true;
  423. for (auto callback : stopCallbacks) {
  424. (*callback)();
  425. }
  426. // Exit.
  427. return;
  428. break;
  429. default:
  430. ;
  431. } // switch.
  432. } // while.
  433. }
  434. #endif
  435. }