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

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