ccdmain.cpp 46 KB

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