ccdmain.cpp 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425
  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. #include <platform.h>
  14. #include <signal.h>
  15. #include <algorithm>
  16. #include <jlib.hpp>
  17. #include <jio.hpp>
  18. #include <jmisc.hpp>
  19. #include <jqueue.tpp>
  20. #include <jsocket.hpp>
  21. #include <jlog.hpp>
  22. #include <jprop.hpp>
  23. #include <jfile.hpp>
  24. #include <jencrypt.hpp>
  25. #include "jutil.hpp"
  26. #include <build-config.h>
  27. #include <udptopo.hpp>
  28. #include "rtlformat.hpp"
  29. #include "dalienv.hpp"
  30. #include "rmtfile.hpp"
  31. #include "ccd.hpp"
  32. #include "ccdquery.hpp"
  33. #include "ccdstate.hpp"
  34. #include "ccdqueue.ipp"
  35. #include "ccdserver.hpp"
  36. #include "ccdlistener.hpp"
  37. #include "ccdsnmp.hpp"
  38. #include "thorplugin.hpp"
  39. #if defined (__linux__)
  40. #include <sys/syscall.h>
  41. #include "ioprio.h"
  42. #endif
  43. #ifdef _USE_CPPUNIT
  44. #include <cppunit/extensions/TestFactoryRegistry.h>
  45. #include <cppunit/ui/text/TestRunner.h>
  46. #endif
  47. //=================================================================================
  48. bool shuttingDown = false;
  49. unsigned numChannels;
  50. unsigned callbackRetries = 3;
  51. unsigned callbackTimeout = 5000;
  52. unsigned lowTimeout = 10000;
  53. unsigned highTimeout = 2000;
  54. unsigned slaTimeout = 2000;
  55. unsigned numServerThreads = 30;
  56. unsigned numSlaveThreads = 30;
  57. bool prestartSlaveThreads = false;
  58. unsigned numRequestArrayThreads = 5;
  59. unsigned headRegionSize;
  60. unsigned ccdMulticastPort;
  61. bool enableHeartBeat = true;
  62. unsigned parallelLoopFlowLimit = 100;
  63. unsigned perChannelFlowLimit = 10;
  64. time_t startupTime;
  65. unsigned statsExpiryTime = 3600;
  66. unsigned miscDebugTraceLevel = 0; // separate trace settings purely for debugging specific items (i.e. all possible locations to look for files at startup)
  67. unsigned readTimeout = 300;
  68. unsigned indexReadChunkSize = 60000;
  69. unsigned maxBlockSize = 10000000;
  70. unsigned maxLockAttempts = 5;
  71. bool pretendAllOpt = false;
  72. bool traceStartStop = false;
  73. bool traceServerSideCache = false;
  74. bool defaultTimeActivities = true;
  75. bool defaultTraceEnabled = false;
  76. bool traceTranslations = true;
  77. unsigned defaultTraceLimit = 10;
  78. unsigned watchActivityId = 0;
  79. unsigned testSlaveFailure = 0;
  80. RelaxedAtomic<unsigned> restarts;
  81. RecordTranslationMode fieldTranslationEnabled = RecordTranslationMode::Payload;
  82. bool mergeSlaveStatistics = true;
  83. PTreeReaderOptions defaultXmlReadFlags = ptr_ignoreWhiteSpace;
  84. bool runOnce = false;
  85. unsigned udpMulticastBufferSize = 262142;
  86. bool roxieMulticastEnabled = true;
  87. IPropertyTree *topology;
  88. MapStringTo<int> *preferredClusters;
  89. StringBuffer topologyFile;
  90. CriticalSection ccdChannelsCrit;
  91. StringArray allQuerySetNames;
  92. bool alwaysTrustFormatCrcs;
  93. bool allFilesDynamic;
  94. bool lockSuperFiles;
  95. bool useRemoteResources;
  96. bool checkFileDate;
  97. bool lazyOpen;
  98. bool localSlave;
  99. bool useAeron;
  100. bool ignoreOrphans;
  101. bool doIbytiDelay = true;
  102. bool copyResources;
  103. bool enableKeyDiff = true;
  104. bool chunkingHeap = true;
  105. bool logFullQueries;
  106. bool blindLogging = false;
  107. bool debugPermitted = true;
  108. bool checkCompleted = true;
  109. unsigned preabortKeyedJoinsThreshold = 100;
  110. unsigned preabortIndexReadsThreshold = 100;
  111. bool preloadOnceData;
  112. bool reloadRetriesFailed;
  113. bool selfTestMode = false;
  114. bool defaultCollectFactoryStatistics = true;
  115. bool useOldTopology = false;
  116. int backgroundCopyClass = 0;
  117. int backgroundCopyPrio = 0;
  118. unsigned memoryStatsInterval = 0;
  119. memsize_t defaultMemoryLimit;
  120. unsigned defaultTimeLimit[3] = {0, 0, 0};
  121. unsigned defaultWarnTimeLimit[3] = {0, 5000, 5000};
  122. unsigned defaultThorConnectTimeout;
  123. unsigned defaultParallelJoinPreload = 0;
  124. unsigned defaultPrefetchProjectPreload = 10;
  125. unsigned defaultConcatPreload = 0;
  126. unsigned defaultFetchPreload = 0;
  127. unsigned defaultFullKeyedJoinPreload = 0;
  128. unsigned defaultKeyedJoinPreload = 0;
  129. unsigned dafilesrvLookupTimeout = 10000;
  130. bool defaultCheckingHeap = false;
  131. bool defaultDisableLocalOptimizations = false;
  132. unsigned defaultStrandBlockSize = 512;
  133. unsigned defaultForceNumStrands = 0;
  134. unsigned defaultHeapFlags = roxiemem::RHFnone;
  135. unsigned slaveQueryReleaseDelaySeconds = 60;
  136. unsigned coresPerQuery = 0;
  137. unsigned logQueueLen;
  138. unsigned logQueueDrop;
  139. bool useLogQueue;
  140. bool fastLaneQueue;
  141. unsigned mtu_size = 1400; // upper limit on outbound buffer size - allow some header room too
  142. StringBuffer fileNameServiceDali;
  143. StringBuffer roxieName;
  144. bool trapTooManyActiveQueries;
  145. unsigned maxEmptyLoopIterations;
  146. unsigned maxGraphLoopIterations;
  147. bool probeAllRows;
  148. bool steppingEnabled = true;
  149. bool simpleLocalKeyedJoins = true;
  150. unsigned __int64 minFreeDiskSpace = 1024 * 0x100000; // default to 1 GB
  151. unsigned socketCheckInterval = 5000;
  152. StringBuffer logDirectory;
  153. StringBuffer pluginDirectory;
  154. StringBuffer queryDirectory;
  155. StringBuffer codeDirectory;
  156. StringBuffer tempDirectory;
  157. ClientCertificate clientCert;
  158. bool useHardLink;
  159. unsigned maxFileAge[2] = {0xffffffff, 60*60*1000}; // local files don't expire, remote expire in 1 hour, by default
  160. unsigned minFilesOpen[2] = {2000, 500};
  161. unsigned maxFilesOpen[2] = {4000, 1000};
  162. SocketEndpoint debugEndpoint;
  163. HardwareInfo hdwInfo;
  164. unsigned parallelAggregate;
  165. bool inMemoryKeysEnabled = true;
  166. unsigned serverSideCacheSize = 0;
  167. bool nodeCachePreload = false;
  168. unsigned nodeCacheMB = 100;
  169. unsigned leafCacheMB = 50;
  170. unsigned blobCacheMB = 0;
  171. unsigned roxiePort = 0;
  172. Owned<IPerfMonHook> perfMonHook;
  173. MODULE_INIT(INIT_PRIORITY_STANDARD)
  174. {
  175. topology = NULL;
  176. return true;
  177. }
  178. MODULE_EXIT()
  179. {
  180. ::Release(topology);
  181. }
  182. //=========================================================================================
  183. //////////////////////////////////////////////////////////////////////////////////////////////
  184. extern "C" void caughtSIGPIPE(int sig)
  185. {
  186. DBGLOG("Caught sigpipe %d", sig);
  187. }
  188. extern "C" void caughtSIGHUP(int sig)
  189. {
  190. DBGLOG("Caught sighup %d", sig);
  191. }
  192. extern "C" void caughtSIGALRM(int sig)
  193. {
  194. DBGLOG("Caught sigalrm %d", sig);
  195. }
  196. extern "C" void caughtSIGTERM(int sig)
  197. {
  198. DBGLOG("Caught sigterm %d", sig);
  199. }
  200. void init_signals()
  201. {
  202. // signal(SIGTERM, caughtSIGTERM);
  203. #ifndef _WIN32
  204. signal(SIGPIPE, caughtSIGPIPE);
  205. signal(SIGHUP, caughtSIGHUP);
  206. signal(SIGALRM, caughtSIGALRM);
  207. #endif
  208. }
  209. //=========================================================================================
  210. class Waiter : public CInterface, implements IAbortHandler
  211. {
  212. Semaphore aborted;
  213. public:
  214. IMPLEMENT_IINTERFACE;
  215. bool wait(unsigned timeout)
  216. {
  217. return aborted.wait(timeout);
  218. }
  219. void wait()
  220. {
  221. aborted.wait();
  222. }
  223. bool onAbort()
  224. {
  225. aborted.signal();
  226. roxieMetrics.clear();
  227. #ifdef _DEBUG
  228. return false; // we want full leak checking info
  229. #else
  230. return true; // we don't care - just exit as fast as we can
  231. #endif
  232. }
  233. } waiter;
  234. void closedown()
  235. {
  236. Owned<IFile> sentinelFile = createSentinelTarget();
  237. removeSentinelFile(sentinelFile);
  238. waiter.onAbort();
  239. }
  240. void getAccessList(const char *aclName, const IPropertyTree *topology, IPropertyTree *aclInfo)
  241. {
  242. StringBuffer xpath;
  243. xpath.append("ACL[@name='").append(aclName).append("']");
  244. if (aclInfo->queryPropTree(xpath))
  245. throw MakeStringException(MSGAUD_operator, ROXIE_INVALID_TOPOLOGY, "Invalid topology file - recursive ACL definition of %s", aclName);
  246. aclInfo->addPropTree("ACL")->setProp("@name", aclName);
  247. Owned<IPropertyTree> acl = topology->getPropTree(xpath.str());
  248. if (!acl)
  249. throw MakeStringException(MSGAUD_operator, ROXIE_INVALID_TOPOLOGY, "Invalid topology file - acl %s not found", aclName);
  250. Owned<IPropertyTreeIterator> access = acl->getElements("Access");
  251. ForEach(*access)
  252. {
  253. IPropertyTree &child = access->query();
  254. const char *base = child.queryProp("@base");
  255. if (base)
  256. getAccessList(base, topology, aclInfo);
  257. else
  258. aclInfo->addPropTree(child.queryName(), LINK(&child));
  259. }
  260. aclInfo->removeProp(xpath);
  261. }
  262. bool ipMatch(IpAddress &ip)
  263. {
  264. return ip.isLocal();
  265. }
  266. extern void doUNIMPLEMENTED(unsigned line, const char *file)
  267. {
  268. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "UNIMPLEMENTED at %s:%d", sanitizeSourceFile(file), line);
  269. }
  270. void FatalError(const char *format, ...)
  271. {
  272. va_list args;
  273. va_start(args, format);
  274. StringBuffer errMsg;
  275. errMsg.valist_appendf(format, args);
  276. va_end(args);
  277. Owned<IException> E = MakeStringException(MSGAUD_operator, ROXIE_INTERNAL_ERROR, "%s", errMsg.str());
  278. EXCLOG(E, "Fatal error");
  279. Sleep(5000);
  280. _exit(1);
  281. }
  282. // If changing these, please change roxie.cpp's roxie_server_usage() as well
  283. static void roxie_common_usage(const char * progName)
  284. {
  285. StringBuffer program;
  286. program.append(progName);
  287. getFileNameOnly(program, false);
  288. // Things that are also relevant to stand-alone executables
  289. printf("Usage: %s [options]\n", program.str());
  290. printf("\nOptions:\n");
  291. printf(" --[xml|csv|raw] : Output format (default ascii)\n");
  292. printf(" --daliServers=[host1,...] : List of Dali servers to use\n");
  293. printf(" --tracelevel=[integer] : Amount of information to dump on logs\n");
  294. printf(" --stdlog=[boolean] : Standard log format (based on tracelevel)\n");
  295. printf(" --logfile=[filename] : Outputs to logfile, rather than stdout\n");
  296. printf(" --help|-h : This message\n");
  297. printf("\n");
  298. }
  299. class MAbortHandler : implements IExceptionHandler
  300. {
  301. public:
  302. virtual bool fireException(IException *e)
  303. {
  304. ForEachItemIn(idx, socketListeners)
  305. {
  306. socketListeners.item(idx).stopListening();
  307. }
  308. return false; // It returns to excsighandler() to abort!
  309. }
  310. } abortHandler;
  311. #ifdef _WIN32
  312. int myhook(int alloctype, void *, size_t nSize, int p1, long allocSeq, const unsigned char *file, int line)
  313. {
  314. // Handy place to put breakpoints when tracking down obscure memory leaks...
  315. if (nSize==68 && !file)
  316. {
  317. DBGLOG("memory hook matched");
  318. }
  319. return true;
  320. }
  321. #endif
  322. void saveTopology()
  323. {
  324. // Write back changes that have been made via certain control:xxx changes, so that they survive a roxie restart
  325. // Note that they are overwritten when Roxie is manually stopped/started via hpcc-init service - these changes
  326. // are only intended to be temporary for the current session
  327. if (!useOldTopology)
  328. return;
  329. try
  330. {
  331. saveXML(topologyFile.str(), topology);
  332. }
  333. catch (IException *E)
  334. {
  335. // If we can't save the topology, then tough. Carry on without it. Changes will not survive an unexpected roxie restart
  336. EXCLOG(E, "Error saving topology file");
  337. E->Release();
  338. }
  339. }
  340. class CHpccProtocolPluginCtx : implements IHpccProtocolPluginContext, public CInterface
  341. {
  342. public:
  343. IMPLEMENT_IINTERFACE;
  344. virtual int ctxGetPropInt(const char *propName, int defaultValue) const
  345. {
  346. return topology->getPropInt(propName, defaultValue);
  347. }
  348. virtual bool ctxGetPropBool(const char *propName, bool defaultValue) const
  349. {
  350. return topology->getPropBool(propName, defaultValue);
  351. }
  352. virtual const char *ctxQueryProp(const char *propName) const
  353. {
  354. return topology->queryProp(propName);
  355. }
  356. };
  357. static std::vector<RoxieEndpointInfo> myRoles;
  358. static std::vector<unsigned> farmerPorts;
  359. static std::vector<std::pair<unsigned, unsigned>> slaveChannels;
  360. void readStaticTopology()
  361. {
  362. // If dynamicServers not set, we read a list of all servers form the topology file, and deduce which ones are on which channel
  363. // and the total number of channels
  364. std::vector<RoxieEndpointInfo> allRoles;
  365. IpAddressArray nodeTable;
  366. unsigned numNodes = topology->getCount("./RoxieServerProcess");
  367. Owned<IPropertyTreeIterator> roxieServers = topology->getElements("./RoxieServerProcess");
  368. bool myNodeSet = false;
  369. unsigned calcNumChannels = 0;
  370. ForEach(*roxieServers)
  371. {
  372. IPropertyTree &roxieServer = roxieServers->query();
  373. const char *iptext = roxieServer.queryProp("@netAddress");
  374. IpAddress ip(iptext);
  375. if (ip.isNull())
  376. throw MakeStringException(ROXIE_UDP_ERROR, "Could not resolve address %s", iptext);
  377. if (ip.isLocal() && !myNodeSet)
  378. {
  379. myNodeSet = true;
  380. myNode.setIp(ip);
  381. mySlaveEP.set(ccdMulticastPort, myNode.getNodeAddress());
  382. }
  383. ForEachItemIn(idx, nodeTable)
  384. {
  385. if (ip.ipequals(nodeTable.item(idx)))
  386. throw MakeStringException(ROXIE_UDP_ERROR, "Duplicated node %s in RoxieServerProcess list", iptext);
  387. }
  388. nodeTable.append(ip);
  389. Owned<IPropertyTreeIterator> roxieFarms = topology->getElements("./RoxieFarmProcess");
  390. ForEach(*roxieFarms)
  391. {
  392. IPropertyTree &roxieFarm = roxieFarms->query();
  393. unsigned port = roxieFarm.getPropInt("@port", ROXIE_SERVER_PORT);
  394. RoxieEndpointInfo server = {RoxieEndpointInfo::RoxieServer, 0, { (unsigned short) port, ip }, 0};
  395. allRoles.push_back(server);
  396. }
  397. }
  398. if (!myNodeSet)
  399. throw MakeStringException(MSGAUD_operator, ROXIE_INVALID_TOPOLOGY, "Invalid topology file - current node is not in server list");
  400. // Generate the slave channels
  401. unsigned numDataCopies = topology->getPropInt("@numDataCopies", 1);
  402. if (!numDataCopies)
  403. throw MakeStringException(MSGAUD_operator, ROXIE_INVALID_TOPOLOGY, "Invalid topology file - numDataCopies should be > 0");
  404. unsigned channelsPerNode = topology->getPropInt("@channelsPerNode", 1);
  405. const char *slaveConfig = topology->queryProp("@slaveConfig");
  406. if (!slaveConfig)
  407. slaveConfig = "simple";
  408. if (strnicmp(slaveConfig, "cyclic", 6) == 0)
  409. {
  410. calcNumChannels = numNodes;
  411. unsigned cyclicOffset = topology->getPropInt("@cyclicOffset", 1);
  412. for (unsigned copy=0; copy<numDataCopies; copy++)
  413. {
  414. // Note this code is a little confusing - easy to get the cyclic offset backwards
  415. // cyclic offset means node n+offset has copy 2 for channel n, so node n has copy 2 for channel n-offset
  416. for (unsigned i=0; i<numNodes; i++)
  417. {
  418. int channel = (int)i+1 - (copy * cyclicOffset);
  419. while (channel < 1)
  420. channel = channel + numNodes;
  421. RoxieEndpointInfo slave = {RoxieEndpointInfo::RoxieSlave, (unsigned) channel, { (unsigned short) ccdMulticastPort, nodeTable.item(i) }, copy};
  422. allRoles.push_back(slave);
  423. }
  424. }
  425. }
  426. else if (strnicmp(slaveConfig, "overloaded", 10) == 0)
  427. {
  428. if (!channelsPerNode)
  429. throw MakeStringException(MSGAUD_operator, ROXIE_INVALID_TOPOLOGY, "Invalid topology file - channelsPerNode should be > 0");
  430. calcNumChannels = numNodes * channelsPerNode;
  431. for (unsigned copy=0; copy<channelsPerNode; copy++)
  432. {
  433. for (unsigned i=0; i<numNodes; i++)
  434. {
  435. unsigned channel = i+1;
  436. RoxieEndpointInfo slave = {RoxieEndpointInfo::RoxieSlave, channel, { (unsigned short) ccdMulticastPort, nodeTable.item(i) }, copy};
  437. allRoles.push_back(slave);
  438. channel += numNodes;
  439. }
  440. }
  441. }
  442. else // 'Full redundancy' or 'simple' mode
  443. {
  444. if (numNodes % numDataCopies)
  445. throw MakeStringException(MSGAUD_operator, ROXIE_INVALID_TOPOLOGY, "Invalid topology file - numChannels not an integer");
  446. calcNumChannels = numNodes / numDataCopies;
  447. unsigned channel = 1;
  448. for (unsigned i=0; i<numNodes; i++)
  449. {
  450. RoxieEndpointInfo slave = {RoxieEndpointInfo::RoxieSlave, channel, { (unsigned short) ccdMulticastPort, nodeTable.item(i) }, 0 };
  451. allRoles.push_back(slave);
  452. channel++;
  453. if (channel > calcNumChannels)
  454. channel = 1;
  455. }
  456. }
  457. if (numChannels && numChannels != calcNumChannels)
  458. throw MakeStringException(MSGAUD_operator, ROXIE_INVALID_TOPOLOGY, "Invalid topology file - numChannels calculated at %u but specified as %u", calcNumChannels, numChannels);
  459. if (!calcNumChannels)
  460. throw MakeStringException(MSGAUD_operator, ROXIE_INVALID_TOPOLOGY, "Invalid topology file - numChannels calculated at 0");
  461. if (calcNumChannels > 1 && localSlave)
  462. throw MakeStringException(MSGAUD_operator, ROXIE_INVALID_TOPOLOGY, "Invalid topology file - localSlave requires single channel (%d channels specified)", calcNumChannels);
  463. numChannels = calcNumChannels;
  464. createStaticTopology(allRoles, traceLevel);
  465. }
  466. int CCD_API roxie_main(int argc, const char *argv[], const char * defaultYaml)
  467. {
  468. #ifndef _CONTAINERIZED
  469. for (unsigned i=0;i<(unsigned)argc;i++) {
  470. if (streq(argv[i],"--daemon") || streq(argv[i],"-d")) {
  471. if (daemon(1,0) || write_pidfile(argv[++i])) {
  472. perror("Failed to daemonize");
  473. return EXIT_FAILURE;
  474. }
  475. break;
  476. }
  477. }
  478. #endif
  479. EnableSEHtoExceptionMapping();
  480. setTerminateOnSEH();
  481. init_signals();
  482. // We need to do the above BEFORE we call InitModuleObjects
  483. try
  484. {
  485. InitModuleObjects();
  486. }
  487. catch (IException *E)
  488. {
  489. EXCLOG(E);
  490. E->Release();
  491. return EXIT_FAILURE;
  492. }
  493. init_signals();
  494. for (unsigned i=0; i<(unsigned)argc; i++)
  495. {
  496. if (stricmp(argv[i], "--help")==0 ||
  497. stricmp(argv[i], "-h")==0)
  498. {
  499. roxie_common_usage(argv[0]);
  500. return EXIT_SUCCESS;
  501. }
  502. else if (strsame(argv[i], "-xml")) // Back compatibility
  503. argv[i] = "--xml";
  504. else if (strsame(argv[i], "-csv"))
  505. argv[i] = "--csv";
  506. else if (strsame(argv[i], "-raw"))
  507. argv[i] = "--raw";
  508. }
  509. #ifdef _USE_CPPUNIT
  510. if (argc>=2 && (stricmp(argv[1], "-selftest")==0 || stricmp(argv[1], "--selftest")==0))
  511. {
  512. selfTestMode = true;
  513. queryStderrLogMsgHandler()->setMessageFields(MSGFIELD_time | MSGFIELD_milliTime | MSGFIELD_prefix);
  514. CppUnit::TextUi::TestRunner runner;
  515. if (argc==2)
  516. {
  517. CppUnit::TestFactoryRegistry &registry = CppUnit::TestFactoryRegistry::getRegistry();
  518. runner.addTest( registry.makeTest() );
  519. }
  520. else
  521. {
  522. // MORE - maybe add a 'list' function here?
  523. for (int name = 2; name < argc; name++)
  524. {
  525. if (stricmp(argv[name], "-q")==0)
  526. {
  527. traceLevel = 0;
  528. roxiemem::setMemTraceLevel(0);
  529. removeLog();
  530. }
  531. else
  532. {
  533. CppUnit::TestFactoryRegistry &registry = CppUnit::TestFactoryRegistry::getRegistry(argv[name]);
  534. runner.addTest( registry.makeTest() );
  535. }
  536. }
  537. }
  538. bool wasSucessful = runner.run( "", false );
  539. releaseAtoms();
  540. return wasSucessful;
  541. }
  542. #endif
  543. #ifdef _DEBUG
  544. #ifdef _WIN32
  545. _CrtSetAllocHook(myhook);
  546. #endif
  547. #endif
  548. #ifndef __64BIT__
  549. // Restrict stack sizes on 32-bit systems
  550. Thread::setDefaultStackSize(0x10000); // NB under windows requires linker setting (/stack:)
  551. #endif
  552. srand( (unsigned)time( NULL ) );
  553. char currentDirectory[_MAX_DIR];
  554. if (!getcwd(currentDirectory, sizeof(currentDirectory)))
  555. throw MakeStringException(ROXIE_INTERNAL_ERROR, "getcwd failed (%d)", errno);
  556. codeDirectory.set(currentDirectory);
  557. addNonEmptyPathSepChar(codeDirectory);
  558. try
  559. {
  560. Owned<IFile> sentinelFile = createSentinelTarget();
  561. removeSentinelFile(sentinelFile);
  562. topologyFile.append(codeDirectory).append(PATHSEPCHAR).append("RoxieTopology.xml");
  563. useOldTopology = checkFileExists(topologyFile.str());
  564. topology = loadConfiguration(useOldTopology ? nullptr : defaultYaml, argv, "roxie", "ROXIE", topologyFile, nullptr, "@netAddress");
  565. saveTopology();
  566. const char *channels = topology->queryProp("@channels");
  567. if (channels)
  568. {
  569. StringArray channelSpecs;
  570. channelSpecs.appendList(channels, ",", true);
  571. ForEachItemIn(idx, channelSpecs)
  572. {
  573. char *tail = nullptr;
  574. unsigned channel = strtoul(channelSpecs.item(idx), &tail, 10);
  575. unsigned repl = 0;
  576. if (*tail==':')
  577. {
  578. tail++;
  579. repl = atoi(tail);
  580. }
  581. else if (*tail)
  582. throw makeStringExceptionV(ROXIE_INTERNAL_ERROR, "Invalid channel specification %s", channels);
  583. slaveChannels.push_back(std::pair<unsigned, unsigned>(channel, repl));
  584. }
  585. }
  586. const char *topos = topology->queryProp("@topologyServers");
  587. StringArray topoValues;
  588. if (topos)
  589. topoValues.appendList(topos, ",", true);
  590. const char *serverPorts = topology->queryProp("@serverPorts");
  591. if (serverPorts)
  592. {
  593. StringArray values;
  594. values.appendList(serverPorts, ",", true);
  595. ForEachItemIn(idx, values)
  596. {
  597. farmerPorts.push_back(atoi(values.item(idx)));
  598. }
  599. }
  600. if (topology->hasProp("PreferredCluster"))
  601. {
  602. preferredClusters = new MapStringTo<int>(true);
  603. Owned<IPropertyTreeIterator> clusters = topology->getElements("PreferredCluster");
  604. ForEach(*clusters)
  605. {
  606. IPropertyTree &child = clusters->query();
  607. const char *name = child.queryProp("@name");
  608. int priority = child.getPropInt("@priority", 100);
  609. if (name && *name)
  610. preferredClusters->setValue(name, priority);
  611. }
  612. }
  613. topology->getProp("@name", roxieName);
  614. if (roxieName.length())
  615. setStatisticsComponentName(SCTroxie, roxieName, true);
  616. else
  617. setStatisticsComponentName(SCTroxie, "roxie", true);
  618. Owned<const IQueryDll> standAloneDll;
  619. const char *wuid = topology->queryProp("@workunit");
  620. if (topology->hasProp("@loadWorkunit"))
  621. {
  622. StringBuffer workunitName;
  623. topology->getProp("@loadWorkunit", workunitName);
  624. standAloneDll.setown(createQueryDll(workunitName));
  625. }
  626. else
  627. {
  628. Owned<ILoadedDllEntry> dll = createExeDllEntry(argv[0]);
  629. if (checkEmbeddedWorkUnitXML(dll))
  630. standAloneDll.setown(createExeQueryDll(argv[0]));
  631. }
  632. if (standAloneDll || wuid)
  633. {
  634. unsigned port = topology->getPropInt("@port", 0);
  635. runOnce = port == 0;
  636. if (port)
  637. {
  638. farmerPorts.clear();
  639. farmerPorts.push_back(port);
  640. }
  641. }
  642. if (!topology->hasProp("@resolveLocally"))
  643. topology->setPropBool("@resolveLocally", !topology->hasProp("@daliServers"));
  644. traceLevel = topology->getPropInt("@traceLevel", runOnce ? 0 : 1);
  645. if (traceLevel > MAXTRACELEVEL)
  646. traceLevel = MAXTRACELEVEL;
  647. if (traceLevel && topology->hasProp("logging/@disabled"))
  648. topology->setPropBool("logging/@disabled", false);
  649. udpTraceLevel = topology->getPropInt("@udpTraceLevel", runOnce ? 0 : 1);
  650. roxiemem::setMemTraceLevel(topology->getPropInt("@memTraceLevel", runOnce ? 0 : 1));
  651. soapTraceLevel = topology->getPropInt("@soapTraceLevel", runOnce ? 0 : 1);
  652. miscDebugTraceLevel = topology->getPropInt("@miscDebugTraceLevel", 0);
  653. Linked<IPropertyTree> directoryTree = topology->queryPropTree("Directories");
  654. if (!directoryTree)
  655. {
  656. Owned<IPropertyTree> envFile = getHPCCEnvironment();
  657. if (envFile)
  658. directoryTree.set(envFile->queryPropTree("Software/Directories"));
  659. }
  660. if (directoryTree)
  661. {
  662. getConfigurationDirectory(directoryTree, "query", "roxie", roxieName, queryDirectory);
  663. for (unsigned replicationLevel = 0; replicationLevel < MAX_REPLICATION_LEVELS; replicationLevel++)
  664. {
  665. StringBuffer dataDir;
  666. StringBuffer dirId("data");
  667. if (replicationLevel)
  668. dirId.append(replicationLevel+1);
  669. if (getConfigurationDirectory(directoryTree, dirId, "roxie", roxieName, dataDir))
  670. setBaseDirectory(dataDir, replicationLevel, DFD_OSdefault);
  671. }
  672. }
  673. directoryTree.clear();
  674. //Logging stuff
  675. #ifndef _CONTAINERIZED
  676. if (topology->getPropBool("@stdlog", traceLevel != 0) || topology->getPropBool("@forceStdLog", false))
  677. queryStderrLogMsgHandler()->setMessageFields(MSGFIELD_time | MSGFIELD_milliTime | MSGFIELD_thread | MSGFIELD_prefix);
  678. else
  679. removeLog();
  680. if (topology->hasProp("@logfile"))
  681. {
  682. Owned<IComponentLogFileCreator> lf = createComponentLogFileCreator(topology, "roxie");
  683. lf->setMaxDetail(TopDetail);
  684. lf->beginLogging();
  685. logDirectory.set(lf->queryLogDir());
  686. #ifdef _DEBUG
  687. unsigned useLogQueue = topology->getPropBool("@useLogQueue", false);
  688. #else
  689. unsigned useLogQueue = topology->getPropBool("@useLogQueue", true);
  690. #endif
  691. if (useLogQueue)
  692. {
  693. unsigned logQueueLen = topology->getPropInt("@logQueueLen", 512);
  694. unsigned logQueueDrop = topology->getPropInt("@logQueueDrop", 32);
  695. queryLogMsgManager()->enterQueueingMode();
  696. queryLogMsgManager()->setQueueDroppingLimit(logQueueLen, logQueueDrop);
  697. }
  698. if (topology->getPropBool("@enableSysLog",true))
  699. UseSysLogForOperatorMessages();
  700. }
  701. #else
  702. setupContainerizedLogMsgHandler();
  703. #endif
  704. roxieMetrics.setown(createRoxieMetricsManager());
  705. Owned<IPropertyTreeIterator> userMetrics = topology->getElements("./UserMetric");
  706. ForEach(*userMetrics)
  707. {
  708. IPropertyTree &metric = userMetrics->query();
  709. const char *name = metric.queryProp("@name");
  710. const char *regex= metric.queryProp("@regex");
  711. if (name && regex)
  712. roxieMetrics->addUserMetric(name, regex);
  713. else
  714. throw MakeStringException(ROXIE_INTERNAL_ERROR, "Invalid UserMetric element in topology file - name or regex missing");
  715. }
  716. restarts = topology->getPropInt("@restarts", 0);
  717. const char *preferredSubnet = topology->queryProp("@preferredSubnet");
  718. if (preferredSubnet)
  719. {
  720. const char *preferredSubnetMask = topology->queryProp("@preferredSubnetMask");
  721. if (!preferredSubnetMask) preferredSubnetMask = "255.255.255.0";
  722. if (!setPreferredSubnet(preferredSubnet, preferredSubnetMask))
  723. throw MakeStringException(ROXIE_INTERNAL_ERROR, "Error setting preferred subnet %s mask %s", preferredSubnet, preferredSubnetMask);
  724. }
  725. if (restarts)
  726. {
  727. if (traceLevel)
  728. DBGLOG("Roxie restarting: restarts = %d build = %s", restarts.load(), BUILD_TAG);
  729. setStartRuid(restarts);
  730. }
  731. else
  732. {
  733. if (traceLevel)
  734. {
  735. DBGLOG("Roxie starting, build = %s", BUILD_TAG);
  736. }
  737. }
  738. headRegionSize = topology->getPropInt("@headRegionSize", 50);
  739. ccdMulticastPort = topology->getPropInt("@multicastPort", CCD_MULTICAST_PORT);
  740. statsExpiryTime = topology->getPropInt("@statsExpiryTime", 3600);
  741. roxiemem::setMemTraceSizeLimit((memsize_t) topology->getPropInt64("@memTraceSizeLimit", 0));
  742. callbackRetries = topology->getPropInt("@callbackRetries", 3);
  743. callbackTimeout = topology->getPropInt("@callbackTimeout", 5000);
  744. lowTimeout = topology->getPropInt("@lowTimeout", 10000);
  745. highTimeout = topology->getPropInt("@highTimeout", 2000);
  746. slaTimeout = topology->getPropInt("@slaTimeout", 2000);
  747. parallelLoopFlowLimit = topology->getPropInt("@parallelLoopFlowLimit", 100);
  748. perChannelFlowLimit = topology->getPropInt("@perChannelFlowLimit", 10);
  749. copyResources = topology->getPropBool("@copyResources", true);
  750. useRemoteResources = topology->getPropBool("@useRemoteResources", true);
  751. checkFileDate = topology->getPropBool("@checkFileDate", true);
  752. const char *lazyOpenMode = topology->queryProp("@lazyOpen");
  753. if (!lazyOpenMode || stricmp(lazyOpenMode, "smart")==0)
  754. lazyOpen = (restarts > 0);
  755. else
  756. lazyOpen = topology->getPropBool("@lazyOpen", false);
  757. bool useNasTranslation = topology->getPropBool("@useNASTranslation", true);
  758. if (useNasTranslation)
  759. {
  760. Owned<IPropertyTree> nas = envGetNASConfiguration(topology);
  761. envInstallNASHooks(nas);
  762. }
  763. useDynamicServers = topology->getPropBool("@useDynamicServers", !useOldTopology);
  764. useAeron = topology->getPropBool("@useAeron", false);
  765. localSlave = topology->getPropBool("@localSlave", false);
  766. numChannels = topology->getPropInt("@numChannels", 0);
  767. doIbytiDelay = topology->getPropBool("@doIbytiDelay", true);
  768. minIbytiDelay = topology->getPropInt("@minIbytiDelay", 2);
  769. initIbytiDelay = topology->getPropInt("@initIbytiDelay", 50);
  770. alwaysTrustFormatCrcs = topology->getPropBool("@alwaysTrustFormatCrcs", true);
  771. allFilesDynamic = topology->getPropBool("@allFilesDynamic", false);
  772. lockSuperFiles = topology->getPropBool("@lockSuperFiles", false);
  773. ignoreOrphans = topology->getPropBool("@ignoreOrphans", true);
  774. chunkingHeap = topology->getPropBool("@chunkingHeap", true);
  775. readTimeout = topology->getPropInt("@readTimeout", 300);
  776. logFullQueries = topology->getPropBool("@logFullQueries", false);
  777. debugPermitted = topology->getPropBool("@debugPermitted", true);
  778. blindLogging = topology->getPropBool("@blindLogging", false);
  779. preloadOnceData = topology->getPropBool("@preloadOnceData", true);
  780. reloadRetriesFailed = topology->getPropBool("@reloadRetriesSuspended", true);
  781. #if defined(__linux__) && defined(SYS_ioprio_set)
  782. const char *backgroundCopyClassString = topology->queryProp("@backgroundCopyClass");
  783. if (!isEmptyString(backgroundCopyClassString))
  784. {
  785. if (strieq(backgroundCopyClassString, "best-effort"))
  786. backgroundCopyClass = IOPRIO_CLASS_BE;
  787. else if (strieq(backgroundCopyClassString, "idle"))
  788. backgroundCopyClass = IOPRIO_CLASS_IDLE;
  789. else if (strieq(backgroundCopyClassString, "none"))
  790. backgroundCopyClass = IOPRIO_CLASS_NONE;
  791. else
  792. DBGLOG("Invalid backgroundCopyClass %s specified - ignored", backgroundCopyClassString);
  793. }
  794. backgroundCopyPrio = topology->getPropInt("@backgroundCopyPrio", 0);
  795. if (backgroundCopyPrio >= IOPRIO_BE_NR)
  796. {
  797. DBGLOG("Invalid backgroundCopyPrio %d specified - using %d", backgroundCopyPrio, (int) (IOPRIO_BE_NR-1));
  798. backgroundCopyPrio = IOPRIO_BE_NR-1;
  799. }
  800. else if (backgroundCopyPrio < 0)
  801. {
  802. DBGLOG("Invalid backgroundCopyPrio %d specified - using 0", backgroundCopyPrio);
  803. backgroundCopyPrio = 0;
  804. }
  805. #endif
  806. linuxYield = topology->getPropBool("@linuxYield", false);
  807. traceSmartStepping = topology->getPropBool("@traceSmartStepping", false);
  808. useMemoryMappedIndexes = topology->getPropBool("@useMemoryMappedIndexes", false);
  809. flushJHtreeCacheOnOOM = topology->getPropBool("@flushJHtreeCacheOnOOM", true);
  810. fastLaneQueue = topology->getPropBool("@fastLaneQueue", true);
  811. udpOutQsPriority = topology->getPropInt("@udpOutQsPriority", 0);
  812. udpSnifferEnabled = topology->getPropBool("@udpSnifferEnabled", true);
  813. udpRetryBusySenders = topology->getPropInt("@udpRetryBusySenders", 0);
  814. // Historically, this was specified in seconds. Assume any value <= 10 is a legacy value specified in seconds!
  815. udpMaxRetryTimedoutReqs = topology->getPropInt("@udpMaxRetryTimedoutReqs", 0);
  816. udpRequestToSendTimeout = topology->getPropInt("@udpRequestToSendTimeout", 0);
  817. if (udpRequestToSendTimeout<=10)
  818. udpRequestToSendTimeout *= 1000;
  819. if (udpRequestToSendTimeout == 0)
  820. {
  821. if (slaTimeout)
  822. {
  823. udpRequestToSendTimeout = (slaTimeout*3) / 4;
  824. if (udpRequestToSendTimeout < 10)
  825. udpRequestToSendTimeout = 10;
  826. }
  827. else
  828. udpRequestToSendTimeout = 5000;
  829. }
  830. udpRequestToSendAckTimeout = topology->getPropInt("@udpRequestToSendAckTimeout", 100);
  831. // MORE: might want to check socket buffer sizes against sys max here instead of udp threads ?
  832. udpSnifferReadThreadPriority = topology->getPropInt("@udpSnifferReadThreadPriority", 3);
  833. udpSnifferSendThreadPriority = topology->getPropInt("@udpSnifferSendThreadPriority", 3);
  834. udpMulticastBufferSize = topology->getPropInt("@udpMulticastBufferSize", 262142);
  835. udpFlowSocketsSize = topology->getPropInt("@udpFlowSocketsSize", 131072);
  836. udpLocalWriteSocketSize = topology->getPropInt("@udpLocalWriteSocketSize", 1024000);
  837. roxieMulticastEnabled = topology->getPropBool("@roxieMulticastEnabled", true) && !useAeron; // enable use of multicast for sending requests to slaves
  838. if (udpSnifferEnabled && !roxieMulticastEnabled)
  839. {
  840. DBGLOG("WARNING: ignoring udpSnifferEnabled setting as multicast not enabled");
  841. udpSnifferEnabled = false;
  842. }
  843. int ttlTmp = topology->getPropInt("@multicastTTL", 1);
  844. if (ttlTmp < 0)
  845. {
  846. multicastTTL = 1;
  847. IWARNLOG("multicastTTL value (%d) invalid, must be >=0, resetting to %u", ttlTmp, multicastTTL);
  848. }
  849. else if (ttlTmp > 255)
  850. {
  851. multicastTTL = 255;
  852. IWARNLOG("multicastTTL value (%d) invalid, must be <=%u, resetting to maximum", ttlTmp, multicastTTL);
  853. }
  854. else
  855. multicastTTL = ttlTmp;
  856. indexReadChunkSize = topology->getPropInt("@indexReadChunkSize", 60000);
  857. numSlaveThreads = topology->getPropInt("@slaveThreads", 30);
  858. numServerThreads = topology->getPropInt("@serverThreads", 30);
  859. numRequestArrayThreads = topology->getPropInt("@requestArrayThreads", 5);
  860. maxBlockSize = topology->getPropInt("@maxBlockSize", 10000000);
  861. maxLockAttempts = topology->getPropInt("@maxLockAttempts", 5);
  862. enableHeartBeat = topology->getPropBool("@enableHeartBeat", true);
  863. checkCompleted = topology->getPropBool("@checkCompleted", true);
  864. prestartSlaveThreads = topology->getPropBool("@prestartSlaveThreads", false);
  865. preabortKeyedJoinsThreshold = topology->getPropInt("@preabortKeyedJoinsThreshold", 100);
  866. preabortIndexReadsThreshold = topology->getPropInt("@preabortIndexReadsThreshold", 100);
  867. defaultMemoryLimit = (memsize_t) topology->getPropInt64("@defaultMemoryLimit", 0);
  868. defaultTimeLimit[0] = (unsigned) topology->getPropInt64("@defaultLowPriorityTimeLimit", 0);
  869. defaultTimeLimit[1] = (unsigned) topology->getPropInt64("@defaultHighPriorityTimeLimit", 0);
  870. defaultTimeLimit[2] = (unsigned) topology->getPropInt64("@defaultSLAPriorityTimeLimit", 0);
  871. defaultWarnTimeLimit[0] = (unsigned) topology->getPropInt64("@defaultLowPriorityTimeWarning", 0);
  872. defaultWarnTimeLimit[1] = (unsigned) topology->getPropInt64("@defaultHighPriorityTimeWarning", 0);
  873. defaultWarnTimeLimit[2] = (unsigned) topology->getPropInt64("@defaultSLAPriorityTimeWarning", 0);
  874. defaultThorConnectTimeout = (unsigned) topology->getPropInt64("@defaultThorConnectTimeout", 60);
  875. defaultXmlReadFlags = topology->getPropBool("@defaultStripLeadingWhitespace", true) ? ptr_ignoreWhiteSpace : ptr_none;
  876. defaultParallelJoinPreload = topology->getPropInt("@defaultParallelJoinPreload", 0);
  877. defaultConcatPreload = topology->getPropInt("@defaultConcatPreload", 0);
  878. defaultFetchPreload = topology->getPropInt("@defaultFetchPreload", 0);
  879. defaultFullKeyedJoinPreload = topology->getPropInt("@defaultFullKeyedJoinPreload", 0);
  880. defaultKeyedJoinPreload = topology->getPropInt("@defaultKeyedJoinPreload", 0);
  881. defaultPrefetchProjectPreload = topology->getPropInt("@defaultPrefetchProjectPreload", 10);
  882. defaultStrandBlockSize = topology->getPropInt("@defaultStrandBlockSize", 512);
  883. defaultForceNumStrands = topology->getPropInt("@defaultForceNumStrands", 0);
  884. defaultCheckingHeap = topology->getPropBool("@checkingHeap", false); // NOTE - not in configmgr - too dangerous!
  885. defaultDisableLocalOptimizations = topology->getPropBool("@disableLocalOptimizations", false); // NOTE - not in configmgr - too dangerous!
  886. slaveQueryReleaseDelaySeconds = topology->getPropInt("@slaveQueryReleaseDelaySeconds", 60);
  887. coresPerQuery = topology->getPropInt("@coresPerQuery", 0);
  888. diskReadBufferSize = topology->getPropInt("@diskReadBufferSize", 0x10000);
  889. fieldTranslationEnabled = RecordTranslationMode::Payload;
  890. const char *val = topology->queryProp("@fieldTranslationEnabled");
  891. if (val)
  892. fieldTranslationEnabled = getTranslationMode(val);
  893. pretendAllOpt = topology->getPropBool("@ignoreMissingFiles", false);
  894. memoryStatsInterval = topology->getPropInt("@memoryStatsInterval", 60);
  895. roxiemem::setMemoryStatsInterval(memoryStatsInterval);
  896. pingInterval = topology->getPropInt("@pingInterval", 0);
  897. socketCheckInterval = topology->getPropInt("@socketCheckInterval", runOnce ? 0 : 5000);
  898. memsize_t totalMemoryLimit = (memsize_t) topology->getPropInt64("@totalMemoryLimit", 0);
  899. bool allowHugePages = topology->getPropBool("@heapUseHugePages", false);
  900. bool allowTransparentHugePages = topology->getPropBool("@heapUseTransparentHugePages", true);
  901. bool retainMemory = topology->getPropBool("@heapRetainMemory", false);
  902. if (!totalMemoryLimit)
  903. totalMemoryLimit = 1024 * 0x100000; // 1 Gb;
  904. roxiemem::setTotalMemoryLimit(allowHugePages, allowTransparentHugePages, retainMemory, totalMemoryLimit, 0, NULL, NULL);
  905. traceStartStop = topology->getPropBool("@traceStartStop", false);
  906. traceServerSideCache = topology->getPropBool("@traceServerSideCache", false);
  907. traceTranslations = topology->getPropBool("@traceTranslations", true);
  908. defaultTimeActivities = topology->getPropBool("@timeActivities", true);
  909. defaultTraceEnabled = topology->getPropBool("@traceEnabled", false);
  910. defaultTraceLimit = topology->getPropInt("@traceLimit", 10);
  911. clientCert.certificate.set(topology->queryProp("@certificateFileName"));
  912. clientCert.privateKey.set(topology->queryProp("@privateKeyFileName"));
  913. clientCert.passphrase.set(topology->queryProp("@passphrase"));
  914. useHardLink = topology->getPropBool("@useHardLink", false);
  915. maxFileAge[false] = topology->getPropInt("@localFilesExpire", (unsigned) -1);
  916. maxFileAge[true] = topology->getPropInt("@remoteFilesExpire", 60*60*1000);
  917. minFilesOpen[false] = topology->getPropInt("@minLocalFilesOpen", 2000);
  918. minFilesOpen[true] = topology->getPropInt("@minRemoteFilesOpen", 500);
  919. maxFilesOpen[false] = topology->getPropInt("@maxLocalFilesOpen", 4000);
  920. maxFilesOpen[true] = topology->getPropInt("@maxRemoteFilesOpen", 1000);
  921. dafilesrvLookupTimeout = topology->getPropInt("@dafilesrvLookupTimeout", 10000);
  922. setRemoteFileTimeouts(dafilesrvLookupTimeout, 0);
  923. topology->getProp("@daliServers", fileNameServiceDali);
  924. trapTooManyActiveQueries = topology->getPropBool("@trapTooManyActiveQueries", true);
  925. maxEmptyLoopIterations = topology->getPropInt("@maxEmptyLoopIterations", 1000);
  926. maxGraphLoopIterations = topology->getPropInt("@maxGraphLoopIterations", 1000);
  927. mergeSlaveStatistics = topology->getPropBool("@mergeSlaveStatistics", true);
  928. defaultCollectFactoryStatistics = topology->getPropBool("@collectFactoryStatistics", true);
  929. enableKeyDiff = topology->getPropBool("@enableKeyDiff", true);
  930. // NB: these directories will have been setup by topology earlier
  931. const char *primaryDirectory = queryBaseDirectory(grp_unknown, 0);
  932. const char *secondaryDirectory = queryBaseDirectory(grp_unknown, 1);
  933. // MORE: Get parms from topology after it is populated from Hardware/computer types section in configenv
  934. // Then if does not match and based on desired action in topolgy, either warn, or fatal exit or .... etc
  935. getHardwareInfo(hdwInfo, primaryDirectory, secondaryDirectory);
  936. if (traceLevel)
  937. {
  938. DBGLOG("Current Hardware Info: CPUs=%i, speed=%i MHz, Mem=%i MB , primDisk=%i GB, primFree=%i GB, secDisk=%i GB, secFree=%i GB, NIC=%i",
  939. hdwInfo.numCPUs, hdwInfo.CPUSpeed, hdwInfo.totalMemory,
  940. hdwInfo.primDiskSize, hdwInfo.primFreeSize, hdwInfo.secDiskSize, hdwInfo.secFreeSize, hdwInfo.NICSpeed);
  941. }
  942. parallelAggregate = topology->getPropInt("@parallelAggregate", 0);
  943. if (!parallelAggregate)
  944. parallelAggregate = hdwInfo.numCPUs;
  945. if (!parallelAggregate)
  946. parallelAggregate = 1;
  947. simpleLocalKeyedJoins = topology->getPropBool("@simpleLocalKeyedJoins", true);
  948. inMemoryKeysEnabled = topology->getPropBool("@inMemoryKeysEnabled", true);
  949. serverSideCacheSize = topology->getPropInt("@serverSideCacheSize", 0);
  950. setKeyIndexCacheSize((unsigned)-1); // unbound
  951. nodeCachePreload = topology->getPropBool("@nodeCachePreload", false);
  952. setNodeCachePreload(nodeCachePreload);
  953. nodeCacheMB = topology->getPropInt("@nodeCacheMem", 100);
  954. setNodeCacheMem(nodeCacheMB * 0x100000);
  955. leafCacheMB = topology->getPropInt("@leafCacheMem", 50);
  956. setLeafCacheMem(leafCacheMB * 0x100000);
  957. blobCacheMB = topology->getPropInt("@blobCacheMem", 0);
  958. setBlobCacheMem(blobCacheMB * 0x100000);
  959. unsigned __int64 affinity = topology->getPropInt64("@affinity", 0);
  960. updateAffinity(affinity);
  961. minFreeDiskSpace = topology->getPropInt64("@minFreeDiskSpace", (1024 * 0x100000)); // default to 1 GB
  962. if (topology->getPropBool("@jumboFrames", false))
  963. {
  964. mtu_size = 9000; // upper limit on outbound buffer size - allow some header room too
  965. roxiemem::setDataAlignmentSize(0x2000);
  966. }
  967. else
  968. {
  969. mtu_size = 1400; // upper limit on outbound buffer size - allow some header room too
  970. roxiemem::setDataAlignmentSize(0x400);
  971. }
  972. unsigned pinterval = topology->getPropInt("@systemMonitorInterval",1000*60);
  973. perfMonHook.setown(roxiemem::createRoxieMemStatsPerfMonHook()); // Note - we create even if pinterval is 0, as can be enabled via control message
  974. if (pinterval)
  975. startPerformanceMonitor(pinterval, PerfMonStandard, perfMonHook);
  976. topology->getProp("@pluginDirectory", pluginDirectory);
  977. StringBuffer packageDirectory;
  978. getPackageFolder(packageDirectory);
  979. if (pluginDirectory.length() == 0 && packageDirectory.length() != 0)
  980. {
  981. pluginDirectory.append(packageDirectory).append("plugins");
  982. }
  983. getAdditionalPluginsPath(pluginDirectory, packageDirectory);
  984. if (queryDirectory.length() == 0)
  985. {
  986. topology->getProp("@queryDir", queryDirectory);
  987. if (queryDirectory.length() == 0)
  988. queryDirectory.append(codeDirectory).append("queries");
  989. }
  990. addNonEmptyPathSepChar(queryDirectory);
  991. queryFileCache().start();
  992. getTempFilePath(tempDirectory, "roxie", topology);
  993. #ifdef _WIN32
  994. topology->addPropBool("@linuxOS", false);
  995. #else
  996. topology->addPropBool("@linuxOS", true);
  997. #endif
  998. #ifdef _CONTAINERIZED
  999. allQuerySetNames.append(roxieName);
  1000. #else
  1001. allQuerySetNames.appendListUniq(topology->queryProp("@querySets"), ",");
  1002. #endif
  1003. // Set multicast base addresses - must be done before generating slave channels
  1004. if (roxieMulticastEnabled && !localSlave)
  1005. {
  1006. if (topology->queryProp("@multicastBase"))
  1007. multicastBase.ipset(topology->queryProp("@multicastBase"));
  1008. else
  1009. throw MakeStringException(MSGAUD_operator, ROXIE_INVALID_TOPOLOGY, "Invalid topology file - multicastBase not set");
  1010. if (topology->queryProp("@multicastLast"))
  1011. multicastLast.ipset(topology->queryProp("@multicastLast"));
  1012. else
  1013. throw MakeStringException(MSGAUD_operator, ROXIE_INVALID_TOPOLOGY, "Invalid topology file - multicastLast not set");
  1014. }
  1015. if (useAeron)
  1016. setAeronProperties(topology);
  1017. if (useDynamicServers)
  1018. {
  1019. if (!numChannels)
  1020. throw makeStringException(MSGAUD_operator, ROXIE_INVALID_TOPOLOGY, "Invalid topology file - numChannels not set");
  1021. IpAddress myIP(".");
  1022. myNode.setIp(myIP);
  1023. for (unsigned port: farmerPorts)
  1024. {
  1025. VStringBuffer xpath("RoxieFarmProcess[@port='%u']", port);
  1026. if (!topology->hasProp(xpath))
  1027. topology->addPropTree("RoxieFarmProcess")->setPropInt("@port", port);
  1028. RoxieEndpointInfo me = {RoxieEndpointInfo::RoxieServer, 0, { (unsigned short) port, myIP }, 0};
  1029. myRoles.push_back(me);
  1030. }
  1031. for (std::pair<unsigned, unsigned> channel: slaveChannels)
  1032. {
  1033. mySlaveEP.set(ccdMulticastPort, myIP);
  1034. RoxieEndpointInfo me = { RoxieEndpointInfo::RoxieSlave, channel.first, mySlaveEP, channel.second };
  1035. myRoles.push_back(me);
  1036. }
  1037. }
  1038. else
  1039. {
  1040. readStaticTopology();
  1041. }
  1042. // Now we know all the channels, we can open and subscribe the multicast channels
  1043. if (!localSlave)
  1044. {
  1045. openMulticastSocket();
  1046. if (roxieMulticastEnabled)
  1047. setMulticastEndpoints(numChannels);
  1048. }
  1049. setDaliServixSocketCaching(true); // enable daliservix caching
  1050. enableForceRemoteReads(); // forces file reads to be remote reads if they match environment setting 'forceRemotePattern' pattern.
  1051. loadPlugins();
  1052. createDelayedReleaser();
  1053. globalPackageSetManager = createRoxiePackageSetManager(standAloneDll.getClear());
  1054. globalPackageSetManager->load();
  1055. unsigned snifferChannel = numChannels+2; // MORE - why +2 not +1??
  1056. if (useDynamicServers && topoValues.length())
  1057. {
  1058. startTopoThread(topoValues, myRoles, traceLevel);
  1059. }
  1060. ROQ = createOutputQueueManager(snifferChannel, numSlaveThreads);
  1061. ROQ->setHeadRegionSize(headRegionSize);
  1062. ROQ->start();
  1063. Owned<IPacketDiscarder> packetDiscarder = createPacketDiscarder();
  1064. #if defined(WIN32) && defined(_DEBUG) && defined(_DEBUG_HEAP_FULL)
  1065. int tmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );
  1066. tmpFlag |= _CRTDBG_CHECK_ALWAYS_DF;
  1067. _CrtSetDbgFlag( tmpFlag );
  1068. #endif
  1069. EnableSEHtoExceptionMapping();
  1070. setSEHtoExceptionHandler(&abortHandler);
  1071. Owned<IHpccProtocolPluginContext> protocolCtx = new CHpccProtocolPluginCtx();
  1072. if (runOnce)
  1073. {
  1074. if (wuid)
  1075. {
  1076. Owned<IHpccProtocolListener> roxieServer = createRoxieWorkUnitListener(1, false);
  1077. try
  1078. {
  1079. roxieServer->runOnce(wuid);
  1080. }
  1081. catch (IException *E)
  1082. {
  1083. EXCLOG(E);
  1084. E->Release();
  1085. }
  1086. }
  1087. else
  1088. {
  1089. Owned<IHpccProtocolPlugin> protocolPlugin = loadHpccProtocolPlugin(protocolCtx, NULL);
  1090. Owned<IHpccProtocolListener> roxieServer = protocolPlugin->createListener("runOnce", createRoxieProtocolMsgSink(myNode.getNodeAddress(), 0, 1, false), 0, 0, NULL);
  1091. try
  1092. {
  1093. const char *format = topology->queryProp("@format");
  1094. if (!format)
  1095. {
  1096. if (topology->getPropBool("@xml", false))
  1097. format = "xml";
  1098. else if (topology->getPropBool("@csv", false))
  1099. format = "csv";
  1100. else if (topology->getPropBool("@raw", false))
  1101. format = "raw";
  1102. else
  1103. format = "ascii";
  1104. }
  1105. StringBuffer query;
  1106. query.appendf("<roxie format='%s'/>", format);
  1107. roxieServer->runOnce(query.str()); // MORE - should use the wu listener instead I suspect
  1108. fflush(stdout); // in windows if output is redirected results don't appear without flushing
  1109. }
  1110. catch (IException *E)
  1111. {
  1112. EXCLOG(E);
  1113. E->Release();
  1114. }
  1115. }
  1116. }
  1117. else
  1118. {
  1119. try
  1120. {
  1121. Owned<IPropertyTreeIterator> roxieFarms = topology->getElements("./RoxieFarmProcess");
  1122. ForEach(*roxieFarms)
  1123. {
  1124. IPropertyTree &roxieFarm = roxieFarms->query();
  1125. unsigned listenQueue = roxieFarm.getPropInt("@listenQueue", DEFAULT_LISTEN_QUEUE_SIZE);
  1126. unsigned numThreads = roxieFarm.getPropInt("@numThreads", 0);
  1127. if (!numThreads)
  1128. numThreads = numServerThreads;
  1129. unsigned port = roxieFarm.getPropInt("@port", ROXIE_SERVER_PORT);
  1130. if (useDynamicServers)
  1131. {
  1132. if (std::find(std::begin(farmerPorts), std::end(farmerPorts), port) == std::end(farmerPorts))
  1133. continue;
  1134. }
  1135. //unsigned requestArrayThreads = roxieFarm.getPropInt("@requestArrayThreads", 5);
  1136. // NOTE: farmer name [@name=] is not copied into topology
  1137. const IpAddress &ip = myNode.getNodeAddress();
  1138. if (!roxiePort)
  1139. {
  1140. roxiePort = port;
  1141. debugEndpoint.set(roxiePort, ip);
  1142. }
  1143. bool suspended = roxieFarm.getPropBool("@suspended", false);
  1144. Owned <IHpccProtocolListener> roxieServer;
  1145. if (port)
  1146. {
  1147. const char *protocol = roxieFarm.queryProp("@protocol");
  1148. StringBuffer certFileName;
  1149. StringBuffer keyFileName;
  1150. StringBuffer passPhraseStr;
  1151. if (protocol && streq(protocol, "ssl"))
  1152. {
  1153. #ifdef _USE_OPENSSL
  1154. const char *certFile = roxieFarm.queryProp("@certificateFileName");
  1155. if (!certFile)
  1156. throw MakeStringException(ROXIE_FILE_ERROR, "Roxie SSL Farm Listener on port %d missing certificateFileName tag", port);
  1157. if (isAbsolutePath(certFile))
  1158. certFileName.append(certFile);
  1159. else
  1160. certFileName.append(codeDirectory.str()).append(certFile);
  1161. if (!checkFileExists(certFileName.str()))
  1162. throw MakeStringException(ROXIE_FILE_ERROR, "Roxie SSL Farm Listener on port %d missing certificateFile (%s)", port, certFileName.str());
  1163. const char *keyFile = roxieFarm.queryProp("@privateKeyFileName");
  1164. if (!keyFile)
  1165. throw MakeStringException(ROXIE_FILE_ERROR, "Roxie SSL Farm Listener on port %d missing privateKeyFileName tag", port);
  1166. if (isAbsolutePath(keyFile))
  1167. keyFileName.append(keyFile);
  1168. else
  1169. keyFileName.append(codeDirectory.str()).append(keyFile);
  1170. if (!checkFileExists(keyFileName.str()))
  1171. throw MakeStringException(ROXIE_FILE_ERROR, "Roxie SSL Farm Listener on port %d missing privateKeyFile (%s)", port, keyFileName.str());
  1172. const char *passPhrase = roxieFarm.queryProp("@passphrase");
  1173. if (!isEmptyString(passPhrase))
  1174. decrypt(passPhraseStr, passPhrase);
  1175. #else
  1176. OWARNLOG("Skipping Roxie SSL Farm Listener on port %d : OpenSSL disabled in build", port);
  1177. continue;
  1178. #endif
  1179. }
  1180. const char *soname = roxieFarm.queryProp("@so");
  1181. const char *config = roxieFarm.queryProp("@config");
  1182. Owned<IHpccProtocolPlugin> protocolPlugin = ensureProtocolPlugin(*protocolCtx, soname);
  1183. roxieServer.setown(protocolPlugin->createListener(protocol ? protocol : "native", createRoxieProtocolMsgSink(ip, port, numThreads, suspended), port, listenQueue, config, certFileName.str(), keyFileName.str(), passPhraseStr.str()));
  1184. }
  1185. else
  1186. roxieServer.setown(createRoxieWorkUnitListener(numThreads, suspended));
  1187. IHpccProtocolMsgSink *sink = roxieServer->queryMsgSink();
  1188. const char *aclName = roxieFarm.queryProp("@aclName");
  1189. if (aclName && *aclName)
  1190. {
  1191. Owned<IPropertyTree> aclInfo = createPTree("AccessInfo", ipt_lowmem);
  1192. getAccessList(aclName, topology, aclInfo);
  1193. Owned<IPropertyTreeIterator> accesses = aclInfo->getElements("Access");
  1194. ForEach(*accesses)
  1195. {
  1196. IPropertyTree &access = accesses->query();
  1197. try
  1198. {
  1199. sink->addAccess(access.getPropBool("@allow", true), access.getPropBool("@allowBlind", true), access.queryProp("@ip"), access.queryProp("@mask"), access.queryProp("@query"), access.queryProp("@error"), access.getPropInt("@errorCode"));
  1200. }
  1201. catch (IException *E)
  1202. {
  1203. StringBuffer s, x;
  1204. E->errorMessage(s);
  1205. E->Release();
  1206. toXML(&access, x, 0, 0);
  1207. throw MakeStringException(ROXIE_ACL_ERROR, "Error in access statement %s: %s", x.str(), s.str());
  1208. }
  1209. }
  1210. }
  1211. socketListeners.append(*roxieServer.getLink());
  1212. time(&startupTime);
  1213. roxieServer->start();
  1214. }
  1215. writeSentinelFile(sentinelFile);
  1216. DBGLOG("Startup completed - LPT=%u APT=%u", queryNumLocalTrees(), queryNumAtomTrees());
  1217. DBGLOG("Waiting for queries");
  1218. if (pingInterval)
  1219. startPingTimer();
  1220. LocalIAbortHandler abortHandler(waiter);
  1221. waiter.wait();
  1222. }
  1223. catch (IException *E)
  1224. {
  1225. StringBuffer x;
  1226. IERRLOG("EXCEPTION: (%d): %s", E->errorCode(), E->errorMessage(x).str());
  1227. E->Release();
  1228. }
  1229. }
  1230. shuttingDown = true;
  1231. if (pingInterval)
  1232. stopPingTimer();
  1233. setSEHtoExceptionHandler(NULL);
  1234. while (socketListeners.isItem(0))
  1235. {
  1236. socketListeners.item(0).stop(1000);
  1237. socketListeners.remove(0);
  1238. }
  1239. packetDiscarder->stop();
  1240. packetDiscarder.clear();
  1241. ROQ->stop();
  1242. ROQ->join();
  1243. ROQ->Release();
  1244. ROQ = NULL;
  1245. }
  1246. catch (IException *E)
  1247. {
  1248. StringBuffer x;
  1249. IERRLOG("EXCEPTION: (%d): %s", E->errorCode(), E->errorMessage(x).str());
  1250. E->Release();
  1251. }
  1252. roxieMetrics.clear();
  1253. stopPerformanceMonitor();
  1254. ::Release(globalPackageSetManager);
  1255. globalPackageSetManager = NULL;
  1256. stopDelayedReleaser();
  1257. cleanupPlugins();
  1258. unloadHpccProtocolPlugin();
  1259. closeMulticastSockets();
  1260. releaseSlaveDynamicFileCache();
  1261. releaseRoxieStateCache();
  1262. setDaliServixSocketCaching(false); // make sure it cleans up or you get bogus memleak reports
  1263. setNodeCaching(false); // ditto
  1264. perfMonHook.clear();
  1265. stopAeronDriver();
  1266. strdup("Make sure leak checking is working");
  1267. roxiemem::releaseRoxieHeap();
  1268. UseSysLogForOperatorMessages(false);
  1269. ExitModuleObjects();
  1270. releaseAtoms();
  1271. strdup("Make sure leak checking is working");
  1272. #ifdef _WIN32
  1273. #ifdef _DEBUG
  1274. #if 1
  1275. StringBuffer leakFileDir(logDirectory.str());
  1276. leakFileDir.append("roxieleaks.log");
  1277. HANDLE h = CreateFile(leakFileDir.str(), GENERIC_READ|GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, 0);
  1278. _CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE|_CRTDBG_MODE_DEBUG);
  1279. _CrtSetReportFile( _CRT_WARN, h);
  1280. _CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_FILE|_CRTDBG_MODE_DEBUG);
  1281. _CrtSetReportFile( _CRT_ERROR, h);
  1282. _CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_FILE|_CRTDBG_MODE_DEBUG);
  1283. _CrtSetReportFile( _CRT_ASSERT, h);
  1284. // _CrtDumpMemoryLeaks(); if you uncomment these lines you get to see the leaks sooner (so can look in debugger at full memory)
  1285. // CloseHandle(h); but there will be additional leaks reported that are not really leaks
  1286. #endif
  1287. #endif
  1288. #endif
  1289. return 0;
  1290. }
  1291. static constexpr const char * standaloneDefaultYaml = R"!!(
  1292. version: "1.0"
  1293. roxie:
  1294. allFilesDynamic: true
  1295. localSlave: true
  1296. numChannels: 1
  1297. numServerThreads: 30
  1298. queueNames: roxie.roxie
  1299. roxieMulticastEnabled: false
  1300. traceLevel: 0
  1301. useAeron: false
  1302. RoxieFarmProcess:
  1303. - name: default
  1304. port: 9876
  1305. listenQueue: 200
  1306. numThreads: 0
  1307. - name: workunit
  1308. port: 0
  1309. numThreads: 0
  1310. logging:
  1311. disabled: true
  1312. )!!";
  1313. int STARTQUERY_API start_query(int argc, const char *argv[])
  1314. {
  1315. return roxie_main(argc, argv, standaloneDefaultYaml);
  1316. }