espp.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. #pragma warning (disable : 4786)
  14. #if defined(_WIN32) && defined(_DEBUG)
  15. //#include <vld.h>
  16. #endif
  17. //Jlib
  18. #include "jliball.hpp"
  19. #include "jstats.h"
  20. #include "jutil.hpp"
  21. //CRT / OS
  22. #ifndef _WIN32
  23. #include <sys/types.h>
  24. #include <sys/wait.h>
  25. #include <sys/resource.h>
  26. #include <sys/time.h>
  27. #endif
  28. //SCM Interfaces
  29. #include "esp.hpp"
  30. // We can use "work" as the first parameter when debugging.
  31. #define ESP_SINGLE_PROCESS
  32. //ESP Core
  33. #include "espp.hpp"
  34. #include "espcfg.ipp"
  35. #include "esplog.hpp"
  36. #include "espcontext.hpp"
  37. #include "build-config.h"
  38. #include "rmtfile.hpp"
  39. void CEspServer::sendSnmpMessage(const char* msg) { throwUnexpected(); }
  40. bool CEspServer::addCacheClient(const char *id, const char *cacheInitString)
  41. {
  42. Owned<IEspCache> cacheClient = createESPCache(cacheInitString);
  43. if (!cacheClient)
  44. return false;
  45. cacheClientMap.setValue(id, cacheClient);
  46. countCacheClients++;
  47. return true;
  48. }
  49. bool CEspServer::hasCacheClient()
  50. {
  51. return countCacheClients > 0;
  52. }
  53. const void *CEspServer::queryCacheClient(const char* id)
  54. {
  55. return countCacheClients > 1 ? cacheClientMap.getValue(id) : nullptr;
  56. }
  57. void CEspServer::clearCacheByGroupID(const char *ids, StringArray& errorMsgs)
  58. {
  59. StringArray idList;
  60. idList.appendListUniq(ids, ",");
  61. ForEachItemIn(i, idList)
  62. {
  63. const char *id = idList.item(i);
  64. IEspCache* cacheClient = (IEspCache*) queryCacheClient(id);
  65. if (cacheClient)
  66. cacheClient->flush(0);
  67. else
  68. {
  69. VStringBuffer msg("Failed to get ESPCache client %s.", id);
  70. errorMsgs.append(msg);
  71. }
  72. }
  73. }
  74. bool CEspServer::reSubscribeESPToDali()
  75. {
  76. return m_config->reSubscribeESPToDali();
  77. }
  78. bool CEspServer::unsubscribeESPFromDali()
  79. {
  80. return m_config->unsubscribeESPFromDali();
  81. }
  82. bool CEspServer::detachESPFromDali(bool force)
  83. {
  84. return m_config->detachESPFromDali(force);
  85. }
  86. bool CEspServer::attachESPToDali()
  87. {
  88. return m_config->attachESPToDali();
  89. }
  90. bool CEspServer::isAttachedToDali()
  91. {
  92. return !m_config->isDetachedFromDali();
  93. }
  94. bool CEspServer::isSubscribedToDali()
  95. {
  96. return m_config->isSubscribedToDali();
  97. }
  98. #ifdef _WIN32
  99. /*******************************************
  100. _WIN32
  101. *******************************************/
  102. #ifdef ESP_SINGLE_PROCESS
  103. int start_init_main(int argc, const char** argv, int (*init_main_func)(int,const char**))
  104. {
  105. return init_main_func(argc, argv);
  106. }
  107. #define START_WORK_MAIN(config, server, result) result = work_main((config), (server));
  108. #define SET_ESP_SIGNAL_HANDLER(sig, handler)
  109. #define RESET_ESP_SIGNAL_HANDLER(sig, handler)
  110. #else //!ESP_SINGLE_PROCESS
  111. #define SET_ESP_SIGNAL_HANDLER(sig, handler)
  112. #define RESET_ESP_SIGNAL_HANDLER(sig, handler)
  113. int start_init_main(int argc, const char** argv, int (*init_main_func)(int, const char**))
  114. {
  115. if(argc > 1 && !strcmp(argv[1], "work"))
  116. {
  117. const char** newargv = new const char*[argc - 1];
  118. newargv[0] = argv[0];
  119. for(int i = 2; i < argc; i++)
  120. {
  121. newargv[i - 1] = argv[i];
  122. }
  123. int rtcode = init_main_func(argc - 1, newargv);
  124. delete[] newargv;
  125. return rtcode;
  126. }
  127. else
  128. {
  129. StringBuffer command;
  130. command.append(argv[0]);
  131. command.append(" work ");
  132. for(int i = 1; i < argc; i++)
  133. {
  134. command.append(argv[i]);
  135. command.append(" ");
  136. }
  137. DWORD exitcode = 0;
  138. while(true)
  139. {
  140. PROGLOG("Starting working process: %s", command.str());
  141. PROCESS_INFORMATION process;
  142. STARTUPINFO si;
  143. GetStartupInfo(&si);
  144. if(!CreateProcess(NULL, (char*)command.str(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &process))
  145. {
  146. IERRLOG("Process failed: %d\r\n",GetLastError());
  147. exit(-1);
  148. }
  149. WaitForSingleObject(process.hProcess,INFINITE);
  150. GetExitCodeProcess(process.hProcess, &exitcode);
  151. PROGLOG("Working process exited, exitcode=%d", exitcode);
  152. if(exitcode == TERMINATE_EXITCODE)
  153. {
  154. DBGLOG("This is telling the monitoring process to exit too. Exiting once and for all....");
  155. exit(exitcode);
  156. }
  157. CloseHandle(process.hProcess);
  158. CloseHandle(process.hThread);
  159. Sleep(1000);
  160. }
  161. }
  162. }
  163. #define START_WORK_MAIN(config, server, result) result = work_main((config), (server));
  164. #endif //!ESP_SINGLE_PROCESS
  165. #else
  166. /*****************************************************
  167. LINUX
  168. ****************************************************/
  169. #define SET_ESP_SIGNAL_HANDLER(sig, handler) signal(sig, handler)
  170. #define RESET_ESP_SIGNAL_HANDLER(sig, handler) signal(sig, handler)
  171. int start_init_main(int argc, const char** argv, int (*init_main_func)(int, const char**))
  172. {
  173. return init_main_func(argc, argv);
  174. }
  175. int work_main(CEspConfig& config, CEspServer& server);
  176. int do_work_main(CEspConfig& config, CEspServer& server)
  177. {
  178. int result;
  179. int numchildren = 0;
  180. pid_t childpid=0;
  181. createworker:
  182. childpid = fork();
  183. if(childpid < 0)
  184. {
  185. IERRLOG("Unable to create new process");
  186. result = -1;
  187. }
  188. else if(childpid == 0)
  189. {
  190. result = work_main(config, server);
  191. }
  192. else
  193. {
  194. DBGLOG("New process generated, pid=%d", childpid);
  195. numchildren++;
  196. if(numchildren < MAX_CHILDREN)
  197. goto createworker;
  198. int status;
  199. childpid = wait3(&status, 0, NULL);
  200. DBGLOG("Attention: child process exited, pid = %d", childpid);
  201. numchildren--;
  202. DBGLOG("Bringing up a new process...");
  203. sleep(1);
  204. goto createworker;
  205. }
  206. return result;
  207. }
  208. #define START_WORK_MAIN(config, server, result) result = do_work_main(config, server)
  209. #endif
  210. void brokenpipe_handler(int sig)
  211. {
  212. //Reset the signal first
  213. RESET_ESP_SIGNAL_HANDLER(SIGPIPE, brokenpipe_handler);
  214. DBGLOG("Broken Pipe - remote side closed the socket");
  215. }
  216. int work_main(CEspConfig& config, CEspServer& server)
  217. {
  218. server.start();
  219. DBGLOG("ESP server started.");
  220. server.waitForExit(config);
  221. server.stop(true);
  222. config.stopping();
  223. config.clear();
  224. return 0;
  225. }
  226. void openEspLogFile(IPropertyTree* envpt, IPropertyTree* procpt)
  227. {
  228. StringBuffer logdir;
  229. if(procpt->hasProp("@name"))
  230. {
  231. StringBuffer espNameStr;
  232. procpt->getProp("@name", espNameStr);
  233. if (!getConfigurationDirectory(envpt->queryPropTree("Software/Directories"), "log", "esp", espNameStr.str(), logdir))
  234. {
  235. logdir.clear();
  236. }
  237. }
  238. if(logdir.length() == 0)
  239. {
  240. if(procpt->hasProp("@logDir"))
  241. procpt->getProp("@logDir", logdir);
  242. }
  243. #ifndef _CONTAINERIZED
  244. Owned<IComponentLogFileCreator> lf = createComponentLogFileCreator(logdir.str(), "esp");
  245. lf->setName("esp_main");//override default filename
  246. lf->setAliasName("esp");
  247. lf->beginLogging();
  248. #else
  249. setupContainerizedLogMsgHandler();
  250. #endif
  251. if (procpt->getPropBool("@enableSysLog", false))
  252. UseSysLogForOperatorMessages();
  253. }
  254. static constexpr const char * defaultYaml = R"!!(
  255. version: "1.0"
  256. esp:
  257. name: myesp
  258. daliServers: dali
  259. )!!";
  260. static Owned<IPropertyTree> espConfig;
  261. static void usage()
  262. {
  263. puts("ESP - Enterprise Service Platform server. (C) 2001-2011, HPCC Systems®.");
  264. puts("Usage:");
  265. puts(" esp [options]");
  266. puts("Options:");
  267. puts(" -?/-h: show this help page");
  268. puts(" --daemon|-d <instanceName>: run daemon as instance");
  269. puts(" interactive: start in interactive mode (pop up error dialog when exception occurs)");
  270. puts(" config=<file>: specify the config file name [default: esp.xml]");
  271. puts(" process=<name>: specify the process name in the config [default: the 1st process]");
  272. exit(1);
  273. }
  274. int init_main(int argc, const char* argv[])
  275. {
  276. for (unsigned i=0;i<(unsigned)argc;i++) {
  277. if (streq(argv[i],"--daemon") || streq(argv[i],"-d")) {
  278. if (daemon(1,0) || write_pidfile(argv[++i])) {
  279. perror("Failed to daemonize");
  280. return EXIT_FAILURE;
  281. }
  282. break;
  283. }
  284. }
  285. InitModuleObjects();
  286. Owned<IProperties> inputs = createProperties(true);
  287. bool interactive = false;
  288. for (int i = 1; i < argc; i++)
  289. {
  290. if (streq(argv[i], "-?") || streq(argv[i], "-h") || streq(argv[i], "-help")
  291. || streq(argv[i], "/?") || streq(argv[i], "/h"))
  292. usage();
  293. else if(streq(argv[i], "--daemon") || streq(argv[i], "-d"))
  294. i++; // skip the instance that follows --daemon|-d
  295. else if(streq(argv[i], "interactive"))
  296. interactive = true;
  297. else if (strchr(argv[i],'='))
  298. {
  299. inputs->loadProp(argv[i]);
  300. }
  301. else
  302. {
  303. fprintf(stderr, "Unknown option: %s", argv[i]);
  304. return 0;
  305. }
  306. }
  307. int result = -1;
  308. #ifdef _WIN32
  309. if (!interactive)
  310. ::SetErrorMode(SEM_NOGPFAULTERRORBOX|SEM_FAILCRITICALERRORS);
  311. #endif
  312. SET_ESP_SIGNAL_HANDLER(SIGPIPE, brokenpipe_handler);
  313. bool SEHMappingEnabled = false;
  314. CEspAbortHandler abortHandler;
  315. Owned<IFile> sentinelFile = createSentinelTarget();
  316. removeSentinelFile(sentinelFile);
  317. Owned<CEspConfig> config;
  318. Owned<CEspServer> server;
  319. try
  320. {
  321. const char* cfgfile = NULL;
  322. const char* procname = NULL;
  323. if(inputs.get())
  324. {
  325. if(inputs->hasProp("config"))
  326. cfgfile = inputs->queryProp("config");
  327. if(inputs->hasProp("process"))
  328. procname = inputs->queryProp("process");
  329. }
  330. if(!cfgfile || !*cfgfile)
  331. cfgfile = "esp.xml";
  332. Owned<IPropertyTree> envpt= createPTreeFromXMLFile(cfgfile, ipt_caseInsensitive);
  333. Owned<IPropertyTree> procpt = NULL;
  334. if (envpt)
  335. {
  336. envpt->addProp("@config", cfgfile);
  337. StringBuffer xpath;
  338. if (procname==NULL || strcmp(procname, ".")==0)
  339. xpath.appendf("Software/EspProcess[1]");
  340. else
  341. xpath.appendf("Software/EspProcess[@name=\"%s\"]", procname);
  342. DBGLOG("Using ESP configuration section [%s]", xpath.str());
  343. procpt.set(envpt->queryPropTree(xpath.str()));
  344. if (!procpt)
  345. throw MakeStringException(-1, "Config section [%s] not found", xpath.str());
  346. }
  347. else
  348. throw MakeStringException(-1, "Failed to load config file %s", cfgfile);
  349. #ifdef _CONTAINERIZED
  350. espConfig.setown(loadConfiguration(defaultYaml, argv, "esp", "ESP", nullptr, nullptr));
  351. // TBD: Some esp services read daliServers from it's legacy config file
  352. procpt->setProp("@daliServers", espConfig->queryProp("@daliServers"));
  353. #endif
  354. const char* build_ver = BUILD_TAG;
  355. setBuildVersion(build_ver);
  356. const char* build_level = BUILD_LEVEL;
  357. setBuildLevel(build_level);
  358. const char * processName = procpt->queryProp("@name");
  359. setStatisticsComponentName(SCTesp, processName, true);
  360. openEspLogFile(envpt.get(), procpt.get());
  361. DBGLOG("Esp starting %s", BUILD_TAG);
  362. StringBuffer componentfilesDir;
  363. if(procpt->hasProp("@componentfilesDir"))
  364. procpt->getProp("@componentfilesDir", componentfilesDir);
  365. if(componentfilesDir.length() > 0 && strcmp(componentfilesDir.str(), ".") != 0)
  366. {
  367. setCFD(componentfilesDir.str());
  368. DBGLOG("componentfiles are under %s", getCFD());
  369. }
  370. StringBuffer sehsetting;
  371. procpt->getProp("@enableSEHMapping", sehsetting);
  372. if(!interactive && sehsetting.length() > 0 && (stricmp(sehsetting.str(), "true") == 0 || stricmp(sehsetting.str(), "1") == 0))
  373. SEHMappingEnabled = true;
  374. if(SEHMappingEnabled)
  375. EnableSEHtoExceptionMapping();
  376. installDefaultFileHooks(espConfig);
  377. CEspConfig* cfg = new CEspConfig(inputs.getLink(), envpt.getLink(), procpt.getLink(), false);
  378. if(cfg && cfg->isValid())
  379. {
  380. config.setown(cfg);
  381. abortHandler.setConfig(cfg);
  382. }
  383. }
  384. catch(IException* e)
  385. {
  386. StringBuffer description;
  387. IERRLOG("ESP Unhandled IException (%d -- %s)", e->errorCode(), e->errorMessage(description).str());
  388. e->Release();
  389. return -1;
  390. }
  391. catch (...)
  392. {
  393. IERRLOG("ESP Unhandled General Exception.");
  394. return -1;
  395. }
  396. if (config && config->isValid())
  397. {
  398. PROGLOG("Configuring Esp Platform...");
  399. try
  400. {
  401. CEspServer *srv = new CEspServer(config);
  402. if(SEHMappingEnabled)
  403. srv->setSavedSEHHandler(SEHMappingEnabled);
  404. server.setown(srv);
  405. abortHandler.setServer(srv);
  406. setEspContainer(server.get());
  407. config->loadAll();
  408. config->bindServer(*server.get(), *server.get());
  409. config->checkESPCache(*server.get());
  410. }
  411. catch(IException* e)
  412. {
  413. StringBuffer description;
  414. IERRLOG("ESP Unhandled IException (%d -- %s)", e->errorCode(), e->errorMessage(description).str());
  415. e->Release();
  416. return -1;
  417. }
  418. catch (...)
  419. {
  420. IERRLOG("ESP Unhandled General Exception.");
  421. return -1;
  422. }
  423. writeSentinelFile(sentinelFile);
  424. result = work_main(*config, *server.get());
  425. }
  426. else
  427. {
  428. OERRLOG("!!! Unable to load ESP configuration.");
  429. }
  430. return result;
  431. }
  432. //command line arguments:
  433. // [pre] if "work", special init behavior, but removed before init_main
  434. // [1] process name
  435. // [2] config location - local file name or dali address
  436. // [3] config location type - "dali" or ""
  437. int main(int argc, const char* argv[])
  438. {
  439. start_init_main(argc, argv, init_main);
  440. stopPerformanceMonitor();
  441. UseSysLogForOperatorMessages(false);
  442. releaseAtoms();
  443. return 0;
  444. }