ccdmain.cpp 53 KB

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