ccdmain.cpp 48 KB

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