espp.cpp 17 KB

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