ccdmain.cpp 53 KB

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