espp.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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. void CEspServer::sendSnmpMessage(const char* msg) { throwUnexpected(); }
  39. bool CEspServer::addCacheClient(const char *id, const char *cacheInitString)
  40. {
  41. Owned<IEspCache> cacheClient = createESPCache(cacheInitString);
  42. if (!cacheClient)
  43. return false;
  44. cacheClientMap.setValue(id, cacheClient);
  45. countCacheClients++;
  46. return true;
  47. }
  48. bool CEspServer::hasCacheClient()
  49. {
  50. return countCacheClients > 0;
  51. }
  52. const void *CEspServer::queryCacheClient(const char* id)
  53. {
  54. return countCacheClients > 1 ? cacheClientMap.getValue(id) : nullptr;
  55. }
  56. void CEspServer::clearCacheByGroupID(const char *ids, StringArray& errorMsgs)
  57. {
  58. StringArray idList;
  59. idList.appendListUniq(ids, ",");
  60. ForEachItemIn(i, idList)
  61. {
  62. const char *id = idList.item(i);
  63. IEspCache* cacheClient = (IEspCache*) queryCacheClient(id);
  64. if (cacheClient)
  65. cacheClient->flush(0);
  66. else
  67. {
  68. VStringBuffer msg("Failed to get ESPCache client %s.", id);
  69. errorMsgs.append(msg);
  70. }
  71. }
  72. }
  73. bool CEspServer::reSubscribeESPToDali()
  74. {
  75. return m_config->reSubscribeESPToDali();
  76. }
  77. bool CEspServer::unsubscribeESPFromDali()
  78. {
  79. return m_config->unsubscribeESPFromDali();
  80. }
  81. bool CEspServer::detachESPFromDali(bool force)
  82. {
  83. return m_config->detachESPFromDali(force);
  84. }
  85. bool CEspServer::attachESPToDali()
  86. {
  87. return m_config->attachESPToDali();
  88. }
  89. bool CEspServer::isAttachedToDali()
  90. {
  91. return !m_config->isDetachedFromDali();
  92. }
  93. bool CEspServer::isSubscribedToDali()
  94. {
  95. return m_config->isSubscribedToDali();
  96. }
  97. #ifdef _WIN32
  98. /*******************************************
  99. _WIN32
  100. *******************************************/
  101. #ifdef ESP_SINGLE_PROCESS
  102. int start_init_main(int argc, char** argv, int (*init_main_func)(int,char**))
  103. {
  104. return init_main_func(argc, argv);
  105. }
  106. #define START_WORK_MAIN(config, server, result) result = work_main((config), (server));
  107. #define SET_ESP_SIGNAL_HANDLER(sig, handler)
  108. #define RESET_ESP_SIGNAL_HANDLER(sig, handler)
  109. #else //!ESP_SINGLE_PROCESS
  110. #define SET_ESP_SIGNAL_HANDLER(sig, handler)
  111. #define RESET_ESP_SIGNAL_HANDLER(sig, handler)
  112. int start_init_main(int argc, char** argv, int (*init_main_func)(int, char**))
  113. {
  114. if(argc > 1 && !strcmp(argv[1], "work"))
  115. {
  116. char** newargv = new char*[argc - 1];
  117. newargv[0] = argv[0];
  118. for(int i = 2; i < argc; i++)
  119. {
  120. newargv[i - 1] = argv[i];
  121. }
  122. int rtcode = init_main_func(argc - 1, newargv);
  123. delete[] newargv;
  124. return rtcode;
  125. }
  126. else
  127. {
  128. StringBuffer command;
  129. command.append(argv[0]);
  130. command.append(" work ");
  131. for(int i = 1; i < argc; i++)
  132. {
  133. command.append(argv[i]);
  134. command.append(" ");
  135. }
  136. DWORD exitcode = 0;
  137. while(true)
  138. {
  139. PROGLOG("Starting working process: %s", command.str());
  140. PROCESS_INFORMATION process;
  141. STARTUPINFO si;
  142. GetStartupInfo(&si);
  143. if(!CreateProcess(NULL, (char*)command.str(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &process))
  144. {
  145. IERRLOG("Process failed: %d\r\n",GetLastError());
  146. exit(-1);
  147. }
  148. WaitForSingleObject(process.hProcess,INFINITE);
  149. GetExitCodeProcess(process.hProcess, &exitcode);
  150. PROGLOG("Working process exited, exitcode=%d", exitcode);
  151. if(exitcode == TERMINATE_EXITCODE)
  152. {
  153. DBGLOG("This is telling the monitoring process to exit too. Exiting once and for all....");
  154. exit(exitcode);
  155. }
  156. CloseHandle(process.hProcess);
  157. CloseHandle(process.hThread);
  158. Sleep(1000);
  159. }
  160. }
  161. }
  162. #define START_WORK_MAIN(config, server, result) result = work_main((config), (server));
  163. #endif //!ESP_SINGLE_PROCESS
  164. #else
  165. /*****************************************************
  166. LINUX
  167. ****************************************************/
  168. #define SET_ESP_SIGNAL_HANDLER(sig, handler) signal(sig, handler)
  169. #define RESET_ESP_SIGNAL_HANDLER(sig, handler) signal(sig, handler)
  170. int start_init_main(int argc, const char** argv, int (*init_main_func)(int, const char**))
  171. {
  172. return init_main_func(argc, argv);
  173. }
  174. int work_main(CEspConfig& config, CEspServer& server);
  175. int do_work_main(CEspConfig& config, CEspServer& server)
  176. {
  177. int result;
  178. int numchildren = 0;
  179. pid_t childpid=0;
  180. createworker:
  181. childpid = fork();
  182. if(childpid < 0)
  183. {
  184. IERRLOG("Unable to create new process");
  185. result = -1;
  186. }
  187. else if(childpid == 0)
  188. {
  189. result = work_main(config, server);
  190. }
  191. else
  192. {
  193. DBGLOG("New process generated, pid=%d", childpid);
  194. numchildren++;
  195. if(numchildren < MAX_CHILDREN)
  196. goto createworker;
  197. int status;
  198. childpid = wait3(&status, 0, NULL);
  199. DBGLOG("Attention: child process exited, pid = %d", childpid);
  200. numchildren--;
  201. DBGLOG("Bringing up a new process...");
  202. sleep(1);
  203. goto createworker;
  204. }
  205. return result;
  206. }
  207. #define START_WORK_MAIN(config, server, result) result = do_work_main(config, server)
  208. #endif
  209. void brokenpipe_handler(int sig)
  210. {
  211. //Reset the signal first
  212. RESET_ESP_SIGNAL_HANDLER(SIGPIPE, brokenpipe_handler);
  213. DBGLOG("Broken Pipe - remote side closed the socket");
  214. }
  215. int work_main(CEspConfig& config, CEspServer& server)
  216. {
  217. server.start();
  218. DBGLOG("ESP server started.");
  219. server.waitForExit(config);
  220. server.stop(true);
  221. config.stopping();
  222. config.clear();
  223. return 0;
  224. }
  225. void openEspLogFile(IPropertyTree* envpt, IPropertyTree* procpt)
  226. {
  227. StringBuffer logdir;
  228. if(procpt->hasProp("@name"))
  229. {
  230. StringBuffer espNameStr;
  231. procpt->getProp("@name", espNameStr);
  232. if (!getConfigurationDirectory(envpt->queryPropTree("Software/Directories"), "log", "esp", espNameStr.str(), logdir))
  233. {
  234. logdir.clear();
  235. }
  236. }
  237. if(logdir.length() == 0)
  238. {
  239. if(procpt->hasProp("@logDir"))
  240. procpt->getProp("@logDir", logdir);
  241. }
  242. Owned<IComponentLogFileCreator> lf = createComponentLogFileCreator(logdir.str(), "esp");
  243. lf->setName("esp_main");//override default filename
  244. lf->setAliasName("esp");
  245. lf->beginLogging();
  246. if (procpt->getPropBool("@enableSysLog", false))
  247. UseSysLogForOperatorMessages();
  248. }
  249. static constexpr const char * defaultYaml = R"!!(
  250. version: "1.0"
  251. esp:
  252. name: myesp
  253. daliServers: dali
  254. )!!";
  255. static void usage()
  256. {
  257. puts("ESP - Enterprise Service Platform server. (C) 2001-2011, HPCC Systems®.");
  258. puts("Usage:");
  259. puts(" esp [options]");
  260. puts("Options:");
  261. puts(" -?/-h: show this help page");
  262. puts(" --daemon|-d <instanceName>: run daemon as instance");
  263. puts(" interactive: start in interactive mode (pop up error dialog when exception occurs)");
  264. puts(" config=<file>: specify the config file name [default: esp.xml]");
  265. puts(" process=<name>: specify the process name in the config [default: the 1st process]");
  266. exit(1);
  267. }
  268. int init_main(int argc, const char* argv[])
  269. {
  270. for (unsigned i=0;i<(unsigned)argc;i++) {
  271. if (streq(argv[i],"--daemon") || streq(argv[i],"-d")) {
  272. if (daemon(1,0) || write_pidfile(argv[++i])) {
  273. perror("Failed to daemonize");
  274. return EXIT_FAILURE;
  275. }
  276. break;
  277. }
  278. }
  279. InitModuleObjects();
  280. Owned<IProperties> inputs = createProperties(true);
  281. bool interactive = false;
  282. for (int i = 1; i < argc; i++)
  283. {
  284. if (streq(argv[i], "-?") || streq(argv[i], "-h") || streq(argv[i], "-help")
  285. || streq(argv[i], "/?") || streq(argv[i], "/h"))
  286. usage();
  287. else if(streq(argv[i], "--daemon") || streq(argv[i], "-d"))
  288. i++; // skip the instance that follows --daemon|-d
  289. else if(streq(argv[i], "interactive"))
  290. interactive = true;
  291. else if (strchr(argv[i],'='))
  292. {
  293. inputs->loadProp(argv[i]);
  294. }
  295. else
  296. {
  297. fprintf(stderr, "Unknown option: %s", argv[i]);
  298. return 0;
  299. }
  300. }
  301. int result = -1;
  302. #ifdef _WIN32
  303. if (!interactive)
  304. ::SetErrorMode(SEM_NOGPFAULTERRORBOX|SEM_FAILCRITICALERRORS);
  305. #endif
  306. SET_ESP_SIGNAL_HANDLER(SIGPIPE, brokenpipe_handler);
  307. bool SEHMappingEnabled = false;
  308. CEspAbortHandler abortHandler;
  309. Owned<IFile> sentinelFile = createSentinelTarget();
  310. removeSentinelFile(sentinelFile);
  311. Owned<CEspConfig> config;
  312. Owned<CEspServer> server;
  313. try
  314. {
  315. const char* cfgfile = NULL;
  316. const char* procname = NULL;
  317. if(inputs.get())
  318. {
  319. if(inputs->hasProp("config"))
  320. cfgfile = inputs->queryProp("config");
  321. if(inputs->hasProp("process"))
  322. procname = inputs->queryProp("process");
  323. }
  324. if(!cfgfile || !*cfgfile)
  325. cfgfile = "esp.xml";
  326. Owned<IPropertyTree> envpt= createPTreeFromXMLFile(cfgfile, ipt_caseInsensitive);
  327. Owned<IPropertyTree> procpt = NULL;
  328. if (envpt)
  329. {
  330. envpt->addProp("@config", cfgfile);
  331. StringBuffer xpath;
  332. if (procname==NULL || strcmp(procname, ".")==0)
  333. xpath.appendf("Software/EspProcess[1]");
  334. else
  335. xpath.appendf("Software/EspProcess[@name=\"%s\"]", procname);
  336. DBGLOG("Using ESP configuration section [%s]", xpath.str());
  337. procpt.set(envpt->queryPropTree(xpath.str()));
  338. if (!procpt)
  339. throw MakeStringException(-1, "Config section [%s] not found", xpath.str());
  340. }
  341. else
  342. throw MakeStringException(-1, "Failed to load config file %s", cfgfile);
  343. #ifdef _CONTAINERIZED
  344. Owned<IPropertyTree> espConfig;
  345. /* For now, whilst esp lives with needing/reading a copy of the whole /Environment as it's configuration
  346. * continue to do so, but also read component configuration (esp.yaml), and carry it inside the envpt tree,
  347. * that is passed through services.
  348. * Each service that can pick up the component config from "Config"
  349. */
  350. espConfig.setown(loadConfiguration(defaultYaml, argv, "esp", "ESP", nullptr, nullptr));
  351. procpt->setProp("@daliServers", espConfig->queryProp("@daliServers"));
  352. envpt->setPropTree("Config", espConfig.getClear());
  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. CEspConfig* cfg = new CEspConfig(inputs.getLink(), envpt.getLink(), procpt.getLink(), false);
  377. if(cfg && cfg->isValid())
  378. {
  379. config.setown(cfg);
  380. abortHandler.setConfig(cfg);
  381. }
  382. }
  383. catch(IException* e)
  384. {
  385. StringBuffer description;
  386. IERRLOG("ESP Unhandled IException (%d -- %s)", e->errorCode(), e->errorMessage(description).str());
  387. e->Release();
  388. return -1;
  389. }
  390. catch (...)
  391. {
  392. IERRLOG("ESP Unhandled General Exception.");
  393. return -1;
  394. }
  395. if (config && config->isValid())
  396. {
  397. PROGLOG("Configuring Esp Platform...");
  398. try
  399. {
  400. CEspServer *srv = new CEspServer(config);
  401. if(SEHMappingEnabled)
  402. srv->setSavedSEHHandler(SEHMappingEnabled);
  403. server.setown(srv);
  404. abortHandler.setServer(srv);
  405. setEspContainer(server.get());
  406. config->loadAll();
  407. config->bindServer(*server.get(), *server.get());
  408. config->checkESPCache(*server.get());
  409. }
  410. catch(IException* e)
  411. {
  412. StringBuffer description;
  413. IERRLOG("ESP Unhandled IException (%d -- %s)", e->errorCode(), e->errorMessage(description).str());
  414. e->Release();
  415. return -1;
  416. }
  417. catch (...)
  418. {
  419. IERRLOG("ESP Unhandled General Exception.");
  420. return -1;
  421. }
  422. writeSentinelFile(sentinelFile);
  423. result = work_main(*config, *server.get());
  424. }
  425. else
  426. {
  427. OERRLOG("!!! Unable to load ESP configuration.");
  428. }
  429. return result;
  430. }
  431. //command line arguments:
  432. // [pre] if "work", special init behavior, but removed before init_main
  433. // [1] process name
  434. // [2] config location - local file name or dali address
  435. // [3] config location type - "dali" or ""
  436. int main(int argc, const char* argv[])
  437. {
  438. start_init_main(argc, argv, init_main);
  439. stopPerformanceMonitor();
  440. UseSysLogForOperatorMessages(false);
  441. releaseAtoms();
  442. return 0;
  443. }