thorcommon.cpp 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854
  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 "jexcept.hpp"
  14. #include "jmisc.hpp"
  15. #include "jthread.hpp"
  16. #include "jsocket.hpp"
  17. #include "jprop.hpp"
  18. #include "jdebug.hpp"
  19. #include "jlzw.hpp"
  20. #include "junicode.hpp"
  21. #include "eclhelper.hpp"
  22. #include "thorcommon.ipp"
  23. #include "eclrtl.hpp"
  24. #include "rtlread_imp.hpp"
  25. #include "rtlcommon.hpp"
  26. #include "eclhelper_dyn.hpp"
  27. #include "hqlexpr.hpp"
  28. #include <algorithm>
  29. #ifdef _USE_NUMA
  30. #include <numa.h>
  31. #endif
  32. #include "thorstep.hpp"
  33. #include "roxiemem.hpp"
  34. #define ROWAGG_PERROWOVERHEAD (sizeof(AggregateRowBuilder))
  35. void AggregateRowBuilder::Link() const { LinkRoxieRow(this); }
  36. bool AggregateRowBuilder::Release() const { ReleaseRoxieRow(this); return false; } // MORE - return value is iffy
  37. RowAggregator::RowAggregator(IHThorHashAggregateExtra &_extra, IHThorRowAggregator & _helper) : helper(_helper)
  38. {
  39. comparer = _extra.queryCompareRowElement();
  40. hasher = _extra.queryHash();
  41. elementHasher = _extra.queryHashElement();
  42. elementComparer = _extra.queryCompareElements();
  43. cursor = NULL;
  44. eof = false;
  45. totalSize = overhead = 0;
  46. }
  47. RowAggregator::~RowAggregator()
  48. {
  49. reset();
  50. }
  51. static CClassMeta<AggregateRowBuilder> AggregateRowBuilderMeta;
  52. void RowAggregator::start(IEngineRowAllocator *_rowAllocator, ICodeContext *ctx, unsigned activityId)
  53. {
  54. rowAllocator.set(_rowAllocator);
  55. rowBuilderAllocator.setown(ctx->getRowAllocatorEx(&AggregateRowBuilderMeta, activityId, roxiemem::RHFunique|roxiemem::RHFscanning|roxiemem::RHFdelayrelease));
  56. }
  57. void RowAggregator::reset()
  58. {
  59. while (!eof)
  60. {
  61. AggregateRowBuilder *n = nextResult();
  62. if (n)
  63. ReleaseRoxieRow(n);
  64. }
  65. _releaseAll();
  66. eof = false;
  67. cursor = NULL;
  68. rowAllocator.clear();
  69. totalSize = overhead = 0;
  70. }
  71. AggregateRowBuilder &RowAggregator::addRow(const void * row)
  72. {
  73. AggregateRowBuilder *result;
  74. unsigned hash = hasher->hash(row);
  75. void * match = find(hash, row);
  76. if (match)
  77. {
  78. result = static_cast<AggregateRowBuilder *>(match);
  79. totalSize -= result->querySize();
  80. size32_t sz = helper.processNext(*result, row);
  81. result->setSize(sz);
  82. totalSize += sz;
  83. }
  84. else
  85. {
  86. Owned<AggregateRowBuilder> rowBuilder = new (rowBuilderAllocator->createRow()) AggregateRowBuilder(rowAllocator, hash);
  87. helper.clearAggregate(*rowBuilder);
  88. size32_t sz = helper.processFirst(*rowBuilder, row);
  89. rowBuilder->setSize(sz);
  90. result = rowBuilder.getClear();
  91. addNew(result, hash);
  92. totalSize += sz;
  93. overhead += ROWAGG_PERROWOVERHEAD;
  94. }
  95. return *result;
  96. }
  97. void RowAggregator::mergeElement(const void * otherElement)
  98. {
  99. unsigned hash = elementHasher->hash(otherElement);
  100. void * match = findElement(hash, otherElement);
  101. if (match)
  102. {
  103. AggregateRowBuilder *rowBuilder = static_cast<AggregateRowBuilder *>(match);
  104. totalSize -= rowBuilder->querySize();
  105. size32_t sz = helper.mergeAggregate(*rowBuilder, otherElement);
  106. rowBuilder->setSize(sz);
  107. totalSize += sz;
  108. }
  109. else
  110. {
  111. Owned<AggregateRowBuilder> rowBuilder = new (rowBuilderAllocator->createRow()) AggregateRowBuilder(rowAllocator, hash);
  112. rowBuilder->setSize(cloneRow(*rowBuilder, otherElement, rowAllocator->queryOutputMeta()));
  113. addNew(rowBuilder.getClear(), hash);
  114. }
  115. }
  116. const void * RowAggregator::getFindParam(const void *et) const
  117. {
  118. // Slightly odd name for this function... it actually gets the comparable element
  119. const AggregateRowBuilder *rb = static_cast<const AggregateRowBuilder*>(et);
  120. return rb->row();
  121. }
  122. bool RowAggregator::matchesFindParam(const void *et, const void *key, unsigned fphash) const
  123. {
  124. if (fphash != hashFromElement(et))
  125. return false;
  126. // et = element in the table (an AggregateRowBuilder) key = new row (in input row layout).
  127. return comparer->docompare(key, getFindParam(et)) == 0;
  128. }
  129. bool RowAggregator::matchesElement(const void *et, const void * searchET) const
  130. {
  131. return elementComparer->docompare(getFindParam(et), searchET) == 0;
  132. }
  133. AggregateRowBuilder *RowAggregator::nextResult()
  134. {
  135. void *ret = next(cursor);
  136. if (!ret)
  137. {
  138. eof = true;
  139. return NULL;
  140. }
  141. cursor = ret;
  142. return static_cast<AggregateRowBuilder *>(ret);
  143. }
  144. //=====================================================================================================
  145. void CStreamMerger::fillheap(const void * seek, unsigned numFields, const SmartStepExtra * stepExtra)
  146. {
  147. assertex(activeInputs == 0);
  148. for(unsigned i = 0; i < numInputs; i++)
  149. if(pullInput(i, seek, numFields, stepExtra))
  150. mergeheap[activeInputs++] = i;
  151. }
  152. void CStreamMerger::permute(const void * seek, unsigned numFields, const SmartStepExtra * stepExtra)
  153. {
  154. // the tree structure: element p has children p*2+1 and p*2+2, or element c has parent (unsigned)(c-1)/2
  155. // the heap property: no element should be smaller than its parent
  156. // the dedup variant: if(dedup), the top of the heap should also not be equal to either child
  157. // the method: establish this by starting with the parent of the bottom element and working up to the top element, sifting each down to its correct place
  158. if (activeInputs >= 2)
  159. for(unsigned p = (activeInputs-2)/2; p > 0; --p)
  160. siftDown(p);
  161. if(dedup)
  162. siftDownDedupTop(seek, numFields, stepExtra);
  163. else
  164. siftDown(0);
  165. }
  166. const void * CStreamMerger::consumeTop()
  167. {
  168. unsigned top = mergeheap[0];
  169. if (!pullConsumes)
  170. consumeInput(top);
  171. const void *next = pending[top];
  172. pending[top] = NULL;
  173. return next;
  174. }
  175. bool CStreamMerger::ensureNext(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra * stepExtra)
  176. {
  177. //wasCompleteMatch must be initialised from the actual row returned. (See bug #30388)
  178. if (first)
  179. {
  180. fillheap(seek, numFields, stepExtra);
  181. permute(seek, numFields, stepExtra);
  182. first = false;
  183. if (activeInputs == 0)
  184. return false;
  185. unsigned top = mergeheap[0];
  186. wasCompleteMatch = pendingMatches[top];
  187. return true;
  188. }
  189. while (activeInputs)
  190. {
  191. unsigned top = mergeheap[0];
  192. const void *next = pending[top];
  193. if (next)
  194. {
  195. if (seek)
  196. {
  197. int c = rangeCompare->docompare(next, seek, numFields);
  198. if (c >= 0)
  199. {
  200. if (stepExtra->returnMismatches() && (c > 0))
  201. {
  202. wasCompleteMatch = pendingMatches[top];
  203. return true;
  204. }
  205. else
  206. {
  207. if (pendingMatches[top])
  208. return true;
  209. }
  210. }
  211. }
  212. else
  213. {
  214. if (pendingMatches[top])
  215. return true;
  216. }
  217. skipInput(top);
  218. }
  219. if(!pullInput(top, seek, numFields, stepExtra))
  220. if(!promote(0))
  221. return false;
  222. // we have changed the element at the top of the heap, so need to sift it down to maintain the heap property
  223. if(dedup)
  224. siftDownDedupTop(seek, numFields, stepExtra);
  225. else
  226. siftDown(0);
  227. }
  228. return false;
  229. }
  230. bool CStreamMerger::ensureNext()
  231. {
  232. bool isCompleteMatch = true;
  233. return ensureNext(NULL, 0, isCompleteMatch, NULL);
  234. }
  235. void CStreamMerger::permute()
  236. {
  237. permute(NULL, 0, NULL);
  238. }
  239. bool CStreamMerger::promote(unsigned p)
  240. {
  241. activeInputs--;
  242. if(activeInputs == p)
  243. return false;
  244. mergeheap[p] = mergeheap[activeInputs];
  245. return true;
  246. }
  247. void CStreamMerger::siftDownDedupTop(const void * seek, unsigned numFields, const SmartStepExtra * stepExtra)
  248. {
  249. // same as siftDown(0), except that it also ensures that the top of the heap is not equal to either of its children
  250. if(activeInputs < 2)
  251. return;
  252. unsigned c = 1;
  253. int childcmp = 1;
  254. if(activeInputs >= 3)
  255. {
  256. childcmp = compare->docompare(pending[mergeheap[2]], pending[mergeheap[1]]);
  257. if(childcmp < 0)
  258. c = 2;
  259. }
  260. int cmp = compare->docompare(pending[mergeheap[c]], pending[mergeheap[0]]);
  261. if(cmp > 0)
  262. return;
  263. // the following loop ensures the correct property holds on the smaller branch, and that childcmp==0 iff the top matches the other branch
  264. while(cmp <= 0)
  265. {
  266. if(cmp == 0)
  267. {
  268. if(mergeheap[c] < mergeheap[0])
  269. {
  270. unsigned r = mergeheap[c];
  271. mergeheap[c] = mergeheap[0];
  272. mergeheap[0] = r;
  273. }
  274. unsigned top = mergeheap[c];
  275. skipInput(top);
  276. if(!pullInput(top, seek, numFields, stepExtra))
  277. if(!promote(c))
  278. break;
  279. siftDown(c);
  280. }
  281. else
  282. {
  283. unsigned r = mergeheap[c];
  284. mergeheap[c] = mergeheap[0];
  285. mergeheap[0] = r;
  286. if(siftDown(c))
  287. break;
  288. }
  289. cmp = compare->docompare(pending[mergeheap[c]], pending[mergeheap[0]]);
  290. }
  291. // the following loop ensures the uniqueness property holds on the other branch too
  292. c = 3-c;
  293. if(activeInputs <= c)
  294. return;
  295. while(childcmp == 0)
  296. {
  297. if(mergeheap[c] < mergeheap[0])
  298. {
  299. unsigned r = mergeheap[c];
  300. mergeheap[c] = mergeheap[0];
  301. mergeheap[0] = r;
  302. }
  303. unsigned top = mergeheap[c];
  304. skipInput(top);
  305. if(!pullInput(top, seek, numFields, stepExtra))
  306. if(!promote(c))
  307. break;
  308. siftDown(c);
  309. childcmp = compare->docompare(pending[mergeheap[c]], pending[mergeheap[0]]);
  310. }
  311. }
  312. void CStreamMerger::cleanup()
  313. {
  314. clearPending();
  315. delete [] pending;
  316. pending = NULL;
  317. delete [] pendingMatches;
  318. pendingMatches = NULL;
  319. delete [] mergeheap;
  320. mergeheap = NULL;
  321. }
  322. void CStreamMerger::clearPending()
  323. {
  324. if (pending && activeInputs)
  325. {
  326. for(unsigned i = 0; i < numInputs; i++)
  327. {
  328. if (pullConsumes)
  329. releaseRow(pending[i]);
  330. pending[i] = NULL;
  331. }
  332. activeInputs = 0;
  333. }
  334. first = true;
  335. }
  336. CStreamMerger::CStreamMerger(bool _pullConsumes)
  337. {
  338. pending = NULL;
  339. pendingMatches = NULL;
  340. mergeheap = NULL;
  341. compare = NULL;
  342. rangeCompare = NULL;
  343. dedup = false;
  344. activeInputs = 0;
  345. pullConsumes = _pullConsumes;
  346. numInputs = 0;
  347. first = true;
  348. }
  349. CStreamMerger::~CStreamMerger()
  350. {
  351. //can't call cleanup() because virtual releaseRow() won't be defined.
  352. // NOTE: use assert rather than assertex as exceptions from within destructors are not handled well.
  353. assert(!pending && !mergeheap);
  354. }
  355. void CStreamMerger::init(ICompare * _compare, bool _dedup, IRangeCompare * _rangeCompare)
  356. {
  357. compare = _compare;
  358. dedup = _dedup;
  359. rangeCompare = _rangeCompare;
  360. }
  361. void CStreamMerger::initInputs(unsigned _numInputs)
  362. {
  363. assertex(!pending); // cleanup should have been called before reinitializing
  364. numInputs = _numInputs;
  365. mergeheap = new unsigned[numInputs];
  366. pending = new const void *[numInputs];
  367. pendingMatches = new bool [numInputs];
  368. for (unsigned i = 0; i < numInputs; i++)
  369. pending[i] = NULL;
  370. activeInputs = 0;
  371. first = true;
  372. }
  373. void CStreamMerger::consumeInput(unsigned i)
  374. {
  375. //should be over-ridden if pullConsumes is false;
  376. throwUnexpected();
  377. }
  378. void CStreamMerger::skipInput(unsigned i)
  379. {
  380. if (!pullConsumes)
  381. consumeInput(i);
  382. releaseRow(pending[i]);
  383. pending[i] = NULL;
  384. }
  385. void CStreamMerger::primeRows(const void * * rows)
  386. {
  387. assertex(first && (activeInputs == 0));
  388. first = false;
  389. for(unsigned i = 0; i < numInputs; i++)
  390. {
  391. if ((pending[i] = rows[i]) != NULL)
  392. {
  393. mergeheap[activeInputs++] = i;
  394. pendingMatches[i] = true;
  395. }
  396. }
  397. permute();
  398. }
  399. const void * CStreamMerger::nextRow()
  400. {
  401. if (ensureNext())
  402. return consumeTop();
  403. return NULL;
  404. }
  405. const void * CStreamMerger::queryNextRow()
  406. {
  407. if (ensureNext())
  408. return pending[mergeheap[0]];
  409. return NULL;
  410. }
  411. unsigned CStreamMerger::queryNextInput()
  412. {
  413. if (ensureNext())
  414. return mergeheap[0];
  415. return NotFound;
  416. }
  417. const void * CStreamMerger::nextRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  418. {
  419. if (ensureNext(seek, numFields, wasCompleteMatch, &stepExtra))
  420. return consumeTop();
  421. return NULL;
  422. }
  423. void CStreamMerger::skipRow()
  424. {
  425. assertex(!first);
  426. skipInput(mergeheap[0]);
  427. }
  428. //=====================================================================================================
  429. CThorDemoRowSerializer::CThorDemoRowSerializer(MemoryBuffer & _buffer) : buffer(_buffer)
  430. {
  431. nesting = 0;
  432. }
  433. void CThorDemoRowSerializer::put(size32_t len, const void * ptr)
  434. {
  435. buffer.append(len, ptr);
  436. //ok to flush if nesting == 0;
  437. }
  438. size32_t CThorDemoRowSerializer::beginNested(size32_t count)
  439. {
  440. nesting++;
  441. unsigned pos = buffer.length();
  442. buffer.append((size32_t)0);
  443. return pos;
  444. }
  445. void CThorDemoRowSerializer::endNested(size32_t sizePos)
  446. {
  447. unsigned pos = buffer.length();
  448. buffer.rewrite(sizePos);
  449. buffer.append((size32_t)(pos - (sizePos + sizeof(size32_t))));
  450. buffer.rewrite(pos);
  451. nesting--;
  452. }
  453. IOutputRowSerializer * CachedOutputMetaData::createDiskSerializer(ICodeContext * ctx, unsigned activityId) const
  454. {
  455. if (metaFlags & (MDFhasserialize|MDFneedserializedisk))
  456. return meta->createDiskSerializer(ctx, activityId);
  457. if (isFixedSize())
  458. return new CSimpleFixedRowSerializer(getFixedSize());
  459. return new CSimpleVariableRowSerializer(this);
  460. }
  461. IOutputRowDeserializer * CachedOutputMetaData::createDiskDeserializer(ICodeContext * ctx, unsigned activityId) const
  462. {
  463. if (metaFlags & (MDFhasserialize|MDFneedserializedisk))
  464. return meta->createDiskDeserializer(ctx, activityId);
  465. if (isFixedSize())
  466. return new CSimpleFixedRowDeserializer(getFixedSize());
  467. throwUnexpectedX("createDiskDeserializer variable meta has no serializer");
  468. }
  469. IOutputRowSerializer * CachedOutputMetaData::createInternalSerializer(ICodeContext * ctx, unsigned activityId) const
  470. {
  471. if (metaFlags & (MDFhasserialize|MDFneedserializeinternal))
  472. return meta->createInternalSerializer(ctx, activityId);
  473. if (isFixedSize())
  474. return new CSimpleFixedRowSerializer(getFixedSize());
  475. return new CSimpleVariableRowSerializer(this);
  476. }
  477. IOutputRowDeserializer * CachedOutputMetaData::createInternalDeserializer(ICodeContext * ctx, unsigned activityId) const
  478. {
  479. if (metaFlags & (MDFhasserialize|MDFneedserializeinternal))
  480. return meta->createInternalDeserializer(ctx, activityId);
  481. if (isFixedSize())
  482. return new CSimpleFixedRowDeserializer(getFixedSize());
  483. throwUnexpectedX("createInternalDeserializer variable meta has no serializer");
  484. }
  485. void CSizingSerializer::put(size32_t len, const void * ptr)
  486. {
  487. totalsize += len;
  488. }
  489. size32_t CSizingSerializer::beginNested(size32_t count)
  490. {
  491. totalsize += sizeof(size32_t);
  492. return totalsize;
  493. }
  494. void CSizingSerializer::endNested(size32_t position)
  495. {
  496. }
  497. void CMemoryRowSerializer::put(size32_t len, const void * ptr)
  498. {
  499. buffer.append(len, ptr);
  500. }
  501. size32_t CMemoryRowSerializer::beginNested(size32_t count)
  502. {
  503. nesting++;
  504. unsigned pos = buffer.length();
  505. buffer.append((size32_t)0);
  506. return pos;
  507. }
  508. void CMemoryRowSerializer::endNested(size32_t sizePos)
  509. {
  510. size32_t sz = buffer.length()-(sizePos + sizeof(size32_t));
  511. buffer.writeDirect(sizePos,sizeof(sz),&sz);
  512. nesting--;
  513. }
  514. static void ensureClassesAreNotAbstract()
  515. {
  516. MemoryBuffer temp;
  517. CThorStreamDeserializerSource x1(NULL);
  518. CThorContiguousRowBuffer x2(NULL);
  519. CSizingSerializer x3;
  520. CMemoryRowSerializer x4(temp);
  521. }
  522. //=====================================================================================================
  523. //the visitor callback is used to ensure link counts for children are updated.
  524. size32_t cloneRow(ARowBuilder & rowBuilder, const void * row, IOutputMetaData * meta)
  525. {
  526. size32_t rowSize = meta->getRecordSize(row); // TBD could be better?
  527. byte * self = rowBuilder.ensureCapacity(rowSize, NULL);
  528. memcpy(self, row, rowSize);
  529. if (meta->getMetaFlags() & MDFneeddestruct)
  530. {
  531. ChildRowLinkerWalker walker;
  532. meta->walkIndirectMembers(self, walker);
  533. }
  534. return rowSize;
  535. }
  536. //---------------------------------------------------------------------------------------------------
  537. extern const char * getActivityText(ThorActivityKind kind)
  538. {
  539. switch (kind)
  540. {
  541. case TAKnone: return "None";
  542. case TAKdiskwrite: return "Disk Write";
  543. case TAKsort: return "Sort";
  544. case TAKdedup: return "Dedup";
  545. case TAKfilter: return "Filter";
  546. case TAKsplit: return "Split";
  547. case TAKproject: return "Project";
  548. case TAKrollup: return "Rollup";
  549. case TAKiterate: return "Iterate";
  550. case TAKaggregate: return "Aggregate";
  551. case TAKhashaggregate: return "Hash Aggregate";
  552. case TAKfirstn: return "Firstn";
  553. case TAKsample: return "Sample";
  554. case TAKdegroup: return "Degroup";
  555. case TAKjoin: return "Join";
  556. case TAKhashjoin: return "Hash Join";
  557. case TAKlookupjoin: return "Lookup Join";
  558. case TAKselfjoin: return "Self Join";
  559. case TAKkeyedjoin: return "Keyed Join";
  560. case TAKgroup: return "Group";
  561. case TAKworkunitwrite: return "Output";
  562. case TAKfunnel: return "Funnel";
  563. case TAKapply: return "Apply";
  564. case TAKinlinetable: return "Inline Dataset";
  565. case TAKhashdistribute: return "Hash Distribute";
  566. case TAKhashdedup: return "Hash Dedup";
  567. case TAKnormalize: return "Normalize";
  568. case TAKremoteresult: return "Remote Result";
  569. case TAKpull: return "Pull";
  570. case TAKdenormalize: return "Denormalize";
  571. case TAKnormalizechild: return "Normalize Child";
  572. case TAKchilddataset: return "Child Dataset";
  573. case TAKselectn: return "Select Nth";
  574. case TAKenth: return "Enth";
  575. case TAKif: return "If";
  576. case TAKnull: return "Null";
  577. case TAKdistribution: return "Distribution";
  578. case TAKcountproject: return "Count Project";
  579. case TAKchoosesets: return "Choose Sets";
  580. case TAKpiperead: return "Pipe Read";
  581. case TAKpipewrite: return "Pipe Write";
  582. case TAKcsvwrite: return "Csv Write";
  583. case TAKpipethrough: return "Pipe Through";
  584. case TAKindexwrite: return "Index Write";
  585. case TAKchoosesetsenth: return "Choose Sets Enth";
  586. case TAKchoosesetslast: return "Choose Sets Last";
  587. case TAKfetch: return "Fetch";
  588. case TAKhashdenormalize: return "Hash Denormalize";
  589. case TAKworkunitread: return "Read";
  590. case TAKthroughaggregate: return "Through Aggregate";
  591. case TAKspill: return "Spill";
  592. case TAKcase: return "Case";
  593. case TAKlimit: return "Limit";
  594. case TAKcsvfetch: return "Csv Fetch";
  595. case TAKxmlwrite: return "Xml Write";
  596. case TAKjsonwrite: return "Json Write";
  597. case TAKparse: return "Parse";
  598. case TAKsideeffect: return "Simple Action";
  599. case TAKtopn: return "Top N";
  600. case TAKmerge: return "Merge";
  601. case TAKxmlfetch: return "Xml Fetch";
  602. case TAKjsonfetch: return "Json Fetch";
  603. case TAKxmlparse: return "Parse Xml";
  604. case TAKkeyeddistribute: return "Keyed Distribute";
  605. case TAKjoinlight: return "Lightweight Join";
  606. case TAKalljoin: return "All Join";
  607. case TAKsoap_rowdataset: return "SOAP dataset";
  608. case TAKsoap_rowaction: return "SOAP action";
  609. case TAKsoap_datasetdataset: return "SOAP dataset";
  610. case TAKsoap_datasetaction: return "SOAP action";
  611. case TAKkeydiff: return "Key Difference";
  612. case TAKkeypatch: return "Key Patch";
  613. case TAKkeyeddenormalize: return "Keyed Denormalize";
  614. case TAKsequential: return "Sequential";
  615. case TAKparallel: return "Parallel";
  616. case TAKchilditerator: return "Child Dataset";
  617. case TAKdatasetresult: return "Dataset Result";
  618. case TAKrowresult: return "Row Result";
  619. case TAKchildif: return "If";
  620. case TAKpartition: return "Partition Distribute";
  621. case TAKsubgraph: return "Sub Graph";
  622. case TAKlocalgraph: return "Local Graph";
  623. case TAKifaction: return "If Action";
  624. case TAKemptyaction: return "Empty Action";
  625. case TAKskiplimit: return "Skip Limit";
  626. case TAKdiskread: return "Disk Read";
  627. case TAKdisknormalize: return "Disk Normalize";
  628. case TAKdiskaggregate: return "Disk Aggregate";
  629. case TAKdiskcount: return "Disk Count";
  630. case TAKdiskgroupaggregate: return "Disk Grouped Aggregate";
  631. case TAKindexread: return "Index Read";
  632. case TAKindexnormalize: return "Index Normalize";
  633. case TAKindexaggregate: return "Index Aggregate";
  634. case TAKindexcount: return "Index Count";
  635. case TAKindexgroupaggregate: return "Index Grouped Aggregate";
  636. case TAKchildnormalize: return "Child Normalize";
  637. case TAKchildaggregate: return "Child Aggregate";
  638. case TAKchildgroupaggregate: return "Child Grouped Aggregate";
  639. case TAKchildthroughnormalize: return "Normalize";
  640. case TAKcsvread: return "Csv Read";
  641. case TAKxmlread: return "Xml Read";
  642. case TAKjsonread: return "Json Read";
  643. case TAKlocalresultread: return "Read Local Result";
  644. case TAKlocalresultwrite: return "Local Result";
  645. case TAKcombine: return "Combine";
  646. case TAKregroup: return "Regroup";
  647. case TAKrollupgroup: return "Rollup Group";
  648. case TAKcombinegroup: return "Combine Group";
  649. case TAKlookupdenormalize: return "Lookup Denormalize";
  650. case TAKalldenormalize: return "All Denormalize";
  651. case TAKdenormalizegroup: return "Denormalize Group";
  652. case TAKhashdenormalizegroup: return "Hash Denormalize Group";
  653. case TAKlookupdenormalizegroup: return "Lookup Denormalize Group";
  654. case TAKkeyeddenormalizegroup: return "Keyed Denormalize Group";
  655. case TAKalldenormalizegroup: return "All Denormalize Group";
  656. case TAKlocalresultspill: return "Spill Local Result";
  657. case TAKsimpleaction: return "Action";
  658. case TAKloopcount: return "Loop";
  659. case TAKlooprow: return "Loop";
  660. case TAKloopdataset: return "Loop";
  661. case TAKchildcase: return "Case";
  662. case TAKremotegraph: return "Remote";
  663. case TAKlibrarycall: return "Library Call";
  664. case TAKlocalstreamread: return "Read Input";
  665. case TAKprocess: return "Process";
  666. case TAKgraphloop: return "Graph";
  667. case TAKparallelgraphloop: return "Graph";
  668. case TAKgraphloopresultread: return "Graph Input";
  669. case TAKgraphloopresultwrite: return "Graph Result";
  670. case TAKgrouped: return "Grouped";
  671. case TAKsorted: return "Sorted";
  672. case TAKdistributed: return "Distributed";
  673. case TAKnwayjoin: return "Join";
  674. case TAKnwaymerge: return "Merge";
  675. case TAKnwaymergejoin: return "Merge Join";
  676. case TAKnwayinput: return "Nway Input";
  677. case TAKnwaygraphloopresultread: return "Nway Graph Input";
  678. case TAKnwayselect: return "Select Nway Input";
  679. case TAKnonempty: return "Non Empty";
  680. case TAKcreaterowlimit: return "OnFail Limit";
  681. case TAKexistsaggregate: return "Exists";
  682. case TAKcountaggregate: return "Count";
  683. case TAKprefetchproject: return "Prefetch Project";
  684. case TAKprefetchcountproject: return "Prefetch Count Project";
  685. case TAKfiltergroup: return "Filter Group";
  686. case TAKmemoryspillread: return "Read Spill";
  687. case TAKmemoryspillwrite: return "Write Spill";
  688. case TAKmemoryspillsplit: return "Spill";
  689. case TAKsection: return "Section";
  690. case TAKlinkedrawiterator: return "Child Dataset";
  691. case TAKnormalizelinkedchild: return "Normalize";
  692. case TAKfilterproject: return "Filtered Project";
  693. case TAKcatch: return "Catch";
  694. case TAKskipcatch: return "Skip Catch";
  695. case TAKcreaterowcatch: return "OnFail Catch";
  696. case TAKsectioninput: return "Section Input";
  697. case TAKindexgroupcount: return "Index Grouped Count";
  698. case TAKindexgroupexists: return "Index Grouped Exists";
  699. case TAKhashdistributemerge: return "Distribute Merge";
  700. case TAKselfjoinlight: return "Lightweight Self Join";
  701. case TAKwhen_dataset: return "When";
  702. case TAKhttp_rowdataset: return "HTTP dataset";
  703. case TAKstreamediterator: return "Streamed Dataset";
  704. case TAKexternalsource: return "User Source";
  705. case TAKexternalsink: return "User Output";
  706. case TAKexternalprocess: return "User Proceess";
  707. case TAKwhen_action: return "When";
  708. case TAKsubsort: return "Sub Sort";
  709. case TAKdictionaryworkunitwrite:return "Dictionary Write";
  710. case TAKdictionaryresultwrite: return "Dictionary Result";
  711. case TAKsmartjoin: return "Smart Join";
  712. case TAKsmartdenormalize: return "Smart Denormalize";
  713. case TAKsmartdenormalizegroup: return "Smart Denormalize Group";
  714. case TAKselfdenormalize: return "Self Denormalize";
  715. case TAKselfdenormalizegroup: return "Self Denormalize Group";
  716. case TAKtrace: return "Trace";
  717. case TAKquantile: return "Quantile";
  718. }
  719. throwUnexpected();
  720. }
  721. extern bool isActivitySource(ThorActivityKind kind)
  722. {
  723. switch (kind)
  724. {
  725. case TAKpiperead:
  726. case TAKinlinetable:
  727. case TAKworkunitread:
  728. case TAKnull:
  729. case TAKsideeffect:
  730. case TAKsoap_rowdataset:
  731. case TAKsoap_rowaction:
  732. case TAKkeydiff:
  733. case TAKkeypatch:
  734. case TAKchilditerator:
  735. case TAKlocalgraph:
  736. case TAKemptyaction:
  737. case TAKdiskread:
  738. case TAKdisknormalize:
  739. case TAKdiskaggregate:
  740. case TAKdiskcount:
  741. case TAKdiskgroupaggregate:
  742. case TAKindexread:
  743. case TAKindexnormalize:
  744. case TAKindexaggregate:
  745. case TAKindexcount:
  746. case TAKindexgroupaggregate:
  747. case TAKchildnormalize:
  748. case TAKchildaggregate:
  749. case TAKchildgroupaggregate:
  750. case TAKcsvread:
  751. case TAKxmlread:
  752. case TAKjsonread:
  753. case TAKlocalresultread:
  754. case TAKsimpleaction:
  755. case TAKlocalstreamread:
  756. case TAKgraphloopresultread:
  757. case TAKnwaygraphloopresultread:
  758. case TAKlinkedrawiterator:
  759. case TAKindexgroupexists:
  760. case TAKindexgroupcount:
  761. case TAKstreamediterator:
  762. case TAKexternalsource:
  763. return true;
  764. }
  765. return false;
  766. }
  767. extern bool isActivitySink(ThorActivityKind kind)
  768. {
  769. switch (kind)
  770. {
  771. case TAKdiskwrite:
  772. case TAKworkunitwrite:
  773. case TAKapply:
  774. case TAKremoteresult:
  775. case TAKdistribution:
  776. case TAKpipewrite:
  777. case TAKcsvwrite:
  778. case TAKindexwrite:
  779. case TAKxmlwrite:
  780. case TAKjsonwrite:
  781. case TAKsoap_rowaction:
  782. case TAKsoap_datasetaction:
  783. case TAKkeydiff:
  784. case TAKkeypatch:
  785. case TAKdatasetresult:
  786. case TAKrowresult:
  787. case TAKemptyaction:
  788. case TAKlocalresultwrite:
  789. case TAKgraphloopresultwrite:
  790. case TAKsimpleaction:
  791. case TAKexternalsink:
  792. case TAKifaction:
  793. case TAKparallel:
  794. case TAKsequential:
  795. case TAKwhen_action:
  796. case TAKdictionaryworkunitwrite:
  797. case TAKdictionaryresultwrite:
  798. return true;
  799. }
  800. return false;
  801. }
  802. //=====================================================================================================
  803. // ===========================================
  804. IRowInterfaces *createRowInterfaces(IOutputMetaData *meta, unsigned actid, unsigned heapFlags, ICodeContext *context)
  805. {
  806. class cRowInterfaces: implements IRowInterfaces, public CSimpleInterface
  807. {
  808. unsigned actid;
  809. Linked<IOutputMetaData> meta;
  810. ICodeContext* context;
  811. Linked<IEngineRowAllocator> allocator;
  812. Linked<IOutputRowSerializer> serializer;
  813. Linked<IOutputRowDeserializer> deserializer;
  814. CSingletonLock allocatorlock;
  815. CSingletonLock serializerlock;
  816. CSingletonLock deserializerlock;
  817. unsigned heapFlags;
  818. public:
  819. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  820. cRowInterfaces(IOutputMetaData *_meta,unsigned _actid, unsigned _heapFlags, ICodeContext *_context)
  821. : meta(_meta), heapFlags(_heapFlags)
  822. {
  823. context = _context;
  824. actid = _actid;
  825. }
  826. IEngineRowAllocator * queryRowAllocator()
  827. {
  828. if (allocatorlock.lock()) {
  829. if (!allocator&&meta)
  830. allocator.setown(context->getRowAllocatorEx(meta, actid, heapFlags));
  831. allocatorlock.unlock();
  832. }
  833. return allocator;
  834. }
  835. IOutputRowSerializer * queryRowSerializer()
  836. {
  837. if (serializerlock.lock()) {
  838. if (!serializer&&meta)
  839. serializer.setown(meta->createDiskSerializer(context,actid));
  840. serializerlock.unlock();
  841. }
  842. return serializer;
  843. }
  844. IOutputRowDeserializer * queryRowDeserializer()
  845. {
  846. if (deserializerlock.lock()) {
  847. if (!deserializer&&meta)
  848. deserializer.setown(meta->createDiskDeserializer(context,actid));
  849. deserializerlock.unlock();
  850. }
  851. return deserializer;
  852. }
  853. IOutputMetaData *queryRowMetaData()
  854. {
  855. return meta;
  856. }
  857. unsigned queryActivityId() const
  858. {
  859. return actid;
  860. }
  861. ICodeContext *queryCodeContext()
  862. {
  863. return context;
  864. }
  865. };
  866. return new cRowInterfaces(meta,actid,heapFlags,context);
  867. };
  868. class CRowStreamReader : implements IExtRowStream, public CSimpleInterface
  869. {
  870. protected:
  871. Linked<IFileIO> fileio;
  872. Linked<IMemoryMappedFile> mmfile;
  873. Linked<IOutputRowDeserializer> deserializer;
  874. Linked<IEngineRowAllocator> allocator;
  875. Owned<ISerialStream> strm;
  876. CThorStreamDeserializerSource source;
  877. Owned<ISourceRowPrefetcher> prefetcher;
  878. CThorContiguousRowBuffer prefetchBuffer; // used if prefetcher set
  879. EmptyRowSemantics emptyRowSemantics;
  880. bool eoi;
  881. bool eos;
  882. bool eog;
  883. offset_t bufofs;
  884. #ifdef TRACE_CREATE
  885. static unsigned rdnum;
  886. #endif
  887. class : implements IFileSerialStreamCallback
  888. {
  889. public:
  890. CRC32 crc;
  891. void process(offset_t ofs, size32_t sz, const void *buf)
  892. {
  893. crc.tally(sz,buf);
  894. }
  895. } crccb;
  896. public:
  897. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  898. CRowStreamReader(IFileIO *_fileio, IMemoryMappedFile *_mmfile, IRowInterfaces *rowif, offset_t _ofs, offset_t _len, bool _tallycrc, EmptyRowSemantics _emptyRowSemantics)
  899. : fileio(_fileio), mmfile(_mmfile), allocator(rowif->queryRowAllocator()), prefetchBuffer(NULL), emptyRowSemantics(_emptyRowSemantics)
  900. {
  901. #ifdef TRACE_CREATE
  902. PROGLOG("CRowStreamReader %d = %p",++rdnum,this);
  903. #endif
  904. eoi = false;
  905. eos = false;
  906. eog = false;
  907. bufofs = 0;
  908. if (fileio)
  909. strm.setown(createFileSerialStream(fileio,_ofs,_len,(size32_t)-1, _tallycrc?&crccb:NULL));
  910. else
  911. strm.setown(createFileSerialStream(mmfile,_ofs,_len,_tallycrc?&crccb:NULL));
  912. prefetcher.setown(rowif->queryRowMetaData()->createDiskPrefetcher());
  913. if (prefetcher)
  914. prefetchBuffer.setStream(strm);
  915. source.setStream(strm);
  916. deserializer.set(rowif->queryRowDeserializer());
  917. }
  918. ~CRowStreamReader()
  919. {
  920. #ifdef TRACE_CREATE
  921. PROGLOG("~CRowStreamReader %d = %p",rdnum--,this);
  922. #endif
  923. }
  924. void reinit(offset_t _ofs,offset_t _len,unsigned __int64 _maxrows)
  925. {
  926. assertex(_maxrows == 0);
  927. eoi = false;
  928. eos = (_len==0);
  929. eog = false;
  930. bufofs = 0;
  931. strm->reset(_ofs,_len);
  932. }
  933. const void *nextRow()
  934. {
  935. if (eog)
  936. {
  937. eog = false;
  938. return nullptr;
  939. }
  940. if (eos)
  941. return nullptr;
  942. if (source.eos())
  943. {
  944. eos = true;
  945. return nullptr;
  946. }
  947. if (ers_allow == emptyRowSemantics)
  948. {
  949. byte b;
  950. source.read(sizeof(b), &b);
  951. if (1==b)
  952. return nullptr;
  953. RtlDynamicRowBuilder rowBuilder(*allocator);
  954. size_t size = deserializer->deserialize(rowBuilder, source);
  955. return rowBuilder.finalizeRowClear(size);
  956. }
  957. else
  958. {
  959. RtlDynamicRowBuilder rowBuilder(*allocator);
  960. size_t size = deserializer->deserialize(rowBuilder, source);
  961. if (ers_eogonly == emptyRowSemantics)
  962. {
  963. byte b;
  964. source.read(sizeof(b), &b);
  965. eog = (b==1);
  966. }
  967. return rowBuilder.finalizeRowClear(size);
  968. }
  969. }
  970. const void *prefetchRow(size32_t *sz)
  971. {
  972. if (eog)
  973. eog = false;
  974. else if (!eos)
  975. {
  976. if (source.eos())
  977. eos = true;
  978. else
  979. {
  980. assertex(prefetcher);
  981. if (ers_allow == emptyRowSemantics)
  982. {
  983. byte b;
  984. strm->get(sizeof(b),&b);
  985. if (1==b)
  986. return nullptr;
  987. }
  988. prefetcher->readAhead(prefetchBuffer);
  989. const byte * ret = prefetchBuffer.queryRow();
  990. if (sz)
  991. *sz = prefetchBuffer.queryRowSize();
  992. return ret;
  993. }
  994. }
  995. if (sz)
  996. sz = 0;
  997. return NULL;
  998. }
  999. void prefetchDone()
  1000. {
  1001. prefetchBuffer.finishedRow();
  1002. if (ers_eogonly == emptyRowSemantics)
  1003. {
  1004. byte b;
  1005. strm->get(sizeof(b),&b);
  1006. eog = (b==1);
  1007. }
  1008. }
  1009. virtual void stop()
  1010. {
  1011. stop(NULL);
  1012. }
  1013. void clear()
  1014. {
  1015. strm.clear();
  1016. source.clearStream();
  1017. fileio.clear();
  1018. }
  1019. void stop(CRC32 *crcout)
  1020. {
  1021. if (!eos) {
  1022. eos = true;
  1023. clear();
  1024. }
  1025. // NB CRC will only be right if stopped at eos
  1026. if (crcout)
  1027. *crcout = crccb.crc;
  1028. }
  1029. offset_t getOffset()
  1030. {
  1031. return source.tell();
  1032. }
  1033. virtual unsigned __int64 getStatistic(StatisticKind kind)
  1034. {
  1035. if (fileio)
  1036. return fileio->getStatistic(kind);
  1037. return 0;
  1038. }
  1039. };
  1040. class CLimitedRowStreamReader : public CRowStreamReader
  1041. {
  1042. unsigned __int64 maxrows;
  1043. unsigned __int64 rownum;
  1044. public:
  1045. CLimitedRowStreamReader(IFileIO *_fileio, IMemoryMappedFile *_mmfile, IRowInterfaces *rowif, offset_t _ofs, offset_t _len, unsigned __int64 _maxrows, bool _tallycrc, EmptyRowSemantics _emptyRowSemantics)
  1046. : CRowStreamReader(_fileio, _mmfile, rowif, _ofs, _len, _tallycrc, _emptyRowSemantics)
  1047. {
  1048. maxrows = _maxrows;
  1049. rownum = 0;
  1050. eos = maxrows==0;
  1051. }
  1052. void reinit(offset_t _ofs,offset_t _len,unsigned __int64 _maxrows)
  1053. {
  1054. CRowStreamReader::reinit(_ofs, _len, 0);
  1055. if (_maxrows==0)
  1056. eos = true;
  1057. maxrows = _maxrows;
  1058. rownum = 0;
  1059. }
  1060. const void *nextRow()
  1061. {
  1062. const void * ret = CRowStreamReader::nextRow();
  1063. if (++rownum==maxrows)
  1064. eos = true;
  1065. return ret;
  1066. }
  1067. };
  1068. #ifdef TRACE_CREATE
  1069. unsigned CRowStreamReader::rdnum;
  1070. #endif
  1071. bool UseMemoryMappedRead = false;
  1072. IExtRowStream *createRowStreamEx(IFile *file, IRowInterfaces *rowIf, offset_t offset, offset_t len, unsigned __int64 maxrows, unsigned rwFlags, IExpander *eexp)
  1073. {
  1074. bool compressed = TestRwFlag(rwFlags, rw_compress);
  1075. EmptyRowSemantics emptyRowSemantics = extractESRFromRWFlags(rwFlags);
  1076. if (UseMemoryMappedRead && !compressed)
  1077. {
  1078. PROGLOG("Memory Mapped read of %s",file->queryFilename());
  1079. Owned<IMemoryMappedFile> mmfile = file->openMemoryMapped();
  1080. if (!mmfile)
  1081. return NULL;
  1082. if (maxrows == (unsigned __int64)-1)
  1083. return new CRowStreamReader(NULL, mmfile, rowIf, offset, len, TestRwFlag(rwFlags, rw_crc), emptyRowSemantics);
  1084. else
  1085. return new CLimitedRowStreamReader(NULL, mmfile, rowIf, offset, len, maxrows, TestRwFlag(rwFlags, rw_crc), emptyRowSemantics);
  1086. }
  1087. else
  1088. {
  1089. Owned<IFileIO> fileio;
  1090. if (compressed)
  1091. {
  1092. // JCSMORE should pass in a flag for rw_compressblkcrc I think, doesn't look like it (or anywhere else)
  1093. // checks the block crc's at the moment.
  1094. fileio.setown(createCompressedFileReader(file, eexp, UseMemoryMappedRead));
  1095. }
  1096. else
  1097. fileio.setown(file->open(IFOread));
  1098. if (!fileio)
  1099. return NULL;
  1100. if (maxrows == (unsigned __int64)-1)
  1101. return new CRowStreamReader(fileio, NULL, rowIf, offset, len, TestRwFlag(rwFlags, rw_crc), emptyRowSemantics);
  1102. else
  1103. return new CLimitedRowStreamReader(fileio, NULL, rowIf, offset, len, maxrows, TestRwFlag(rwFlags, rw_crc), emptyRowSemantics);
  1104. }
  1105. }
  1106. IExtRowStream *createRowStream(IFile *file, IRowInterfaces *rowIf, unsigned rwFlags, IExpander *eexp)
  1107. {
  1108. return createRowStreamEx(file, rowIf, 0, (offset_t)-1, (unsigned __int64)-1, rwFlags, eexp);
  1109. }
  1110. // Memory map sizes can be big, restrict to 64-bit platforms.
  1111. void useMemoryMappedRead(bool on)
  1112. {
  1113. #if defined(_DEBUG) || defined(__64BIT__)
  1114. UseMemoryMappedRead = on;
  1115. #endif
  1116. }
  1117. #define ROW_WRITER_BUFFERSIZE (0x100000)
  1118. class CRowStreamWriter : private IRowSerializerTarget, implements IExtRowWriter, public CSimpleInterface
  1119. {
  1120. Linked<IFileIOStream> stream;
  1121. Linked<IOutputRowSerializer> serializer;
  1122. Linked<IEngineRowAllocator> allocator;
  1123. CRC32 crc;
  1124. EmptyRowSemantics emptyRowSemantics;
  1125. bool tallycrc;
  1126. unsigned nested;
  1127. MemoryAttr ma;
  1128. MemoryBuffer extbuf; // may need to spill to disk at some point
  1129. byte *buf;
  1130. size32_t bufpos;
  1131. bool autoflush;
  1132. #ifdef TRACE_CREATE
  1133. static unsigned wrnum;
  1134. #endif
  1135. void flushBuffer(bool final)
  1136. {
  1137. try
  1138. {
  1139. if (bufpos) {
  1140. stream->write(bufpos,buf);
  1141. if (tallycrc)
  1142. crc.tally(bufpos,buf);
  1143. bufpos = 0;
  1144. }
  1145. size32_t extpos = extbuf.length();
  1146. if (!extpos)
  1147. return;
  1148. if (!final)
  1149. extpos = (extpos/ROW_WRITER_BUFFERSIZE)*ROW_WRITER_BUFFERSIZE;
  1150. if (extpos) {
  1151. stream->write(extpos,extbuf.toByteArray());
  1152. if (tallycrc)
  1153. crc.tally(extpos,extbuf.toByteArray());
  1154. }
  1155. if (extpos<extbuf.length()) {
  1156. bufpos = extbuf.length()-extpos;
  1157. memcpy(buf,extbuf.toByteArray()+extpos,bufpos);
  1158. }
  1159. extbuf.clear();
  1160. }
  1161. catch (IException *e)
  1162. {
  1163. autoflush = false; // avoid follow-on errors
  1164. EXCLOG(e, "flushBuffer");
  1165. throw;
  1166. }
  1167. }
  1168. void streamFlush()
  1169. {
  1170. try
  1171. {
  1172. stream->flush();
  1173. }
  1174. catch (IException *e)
  1175. {
  1176. autoflush = false; // avoid follow-on errors
  1177. EXCLOG(e, "streamFlush");
  1178. throw;
  1179. }
  1180. }
  1181. public:
  1182. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  1183. CRowStreamWriter(IFileIOStream *_stream, IOutputRowSerializer *_serializer, IEngineRowAllocator *_allocator, EmptyRowSemantics _emptyRowSemantics, bool _tallycrc, bool _autoflush)
  1184. : stream(_stream), serializer(_serializer), allocator(_allocator), emptyRowSemantics(_emptyRowSemantics)
  1185. {
  1186. #ifdef TRACE_CREATE
  1187. PROGLOG("createRowWriter %d = %p",++wrnum,this);
  1188. #endif
  1189. tallycrc = _tallycrc;
  1190. nested = 0;
  1191. buf = (byte *)ma.allocate(ROW_WRITER_BUFFERSIZE);
  1192. bufpos = 0;
  1193. autoflush = _autoflush;
  1194. }
  1195. ~CRowStreamWriter()
  1196. {
  1197. #ifdef TRACE_CREATE
  1198. PROGLOG("~createRowWriter %d = %p",wrnum--,this);
  1199. #endif
  1200. if (autoflush)
  1201. flush();
  1202. else if (bufpos+extbuf.length()) {
  1203. #ifdef _DEBUG
  1204. PrintStackReport();
  1205. #endif
  1206. WARNLOG("CRowStreamWriter closed with %d bytes unflushed",bufpos+extbuf.length());
  1207. }
  1208. }
  1209. void putRow(const void *row)
  1210. {
  1211. if (row)
  1212. {
  1213. if (ers_allow == emptyRowSemantics)
  1214. {
  1215. byte b = 0;
  1216. put(1, &b);
  1217. serializer->serialize(*this, (const byte *)row);
  1218. }
  1219. else
  1220. {
  1221. serializer->serialize(*this, (const byte *)row);
  1222. if (ers_eogonly == emptyRowSemantics)
  1223. {
  1224. byte b = 0;
  1225. if (bufpos<ROW_WRITER_BUFFERSIZE)
  1226. buf[bufpos++] = b;
  1227. else
  1228. extbuf.append(b);
  1229. }
  1230. }
  1231. allocator->releaseRow(row);
  1232. }
  1233. else if (ers_eogonly == emptyRowSemantics) // backpatch
  1234. {
  1235. byte b = 1;
  1236. if (extbuf.length())
  1237. extbuf.writeDirect(extbuf.length()-1, sizeof(b), &b);
  1238. else
  1239. {
  1240. assertex(bufpos);
  1241. buf[bufpos-1] = b;
  1242. }
  1243. }
  1244. else if (ers_allow == emptyRowSemantics)
  1245. {
  1246. byte b = 1;
  1247. put(1, &b);
  1248. }
  1249. }
  1250. void flush()
  1251. {
  1252. flushBuffer(true);
  1253. streamFlush();
  1254. }
  1255. void flush(CRC32 *crcout)
  1256. {
  1257. flushBuffer(true);
  1258. streamFlush();
  1259. if (crcout)
  1260. *crcout = crc;
  1261. }
  1262. offset_t getPosition()
  1263. {
  1264. return stream->tell()+bufpos+extbuf.length();
  1265. }
  1266. void put(size32_t len, const void * ptr)
  1267. {
  1268. // first fill buf
  1269. for (;;) {
  1270. if (bufpos<ROW_WRITER_BUFFERSIZE) {
  1271. size32_t wr = ROW_WRITER_BUFFERSIZE-bufpos;
  1272. if (wr>len)
  1273. wr = len;
  1274. memcpy(buf+bufpos,ptr,wr);
  1275. bufpos += wr;
  1276. len -= wr;
  1277. if (len==0)
  1278. break; // quick exit
  1279. ptr = (const byte *)ptr + wr;
  1280. }
  1281. if (nested) {
  1282. // have to append to ext buffer (will need to spill to disk here if gets *too* big)
  1283. extbuf.append(len,ptr);
  1284. break;
  1285. }
  1286. else
  1287. flushBuffer(false);
  1288. }
  1289. }
  1290. size32_t beginNested(size32_t count)
  1291. {
  1292. if (nested++==0)
  1293. if (bufpos==ROW_WRITER_BUFFERSIZE)
  1294. flushBuffer(false);
  1295. size32_t ret = bufpos+extbuf.length();
  1296. size32_t sz = 0;
  1297. put(sizeof(sz),&sz);
  1298. return ret;
  1299. }
  1300. void endNested(size32_t pos)
  1301. {
  1302. size32_t sz = bufpos+extbuf.length()-(pos + sizeof(size32_t));
  1303. size32_t wr = sizeof(size32_t);
  1304. byte *out = (byte *)&sz;
  1305. if (pos<ROW_WRITER_BUFFERSIZE) {
  1306. size32_t space = ROW_WRITER_BUFFERSIZE-pos;
  1307. if (space>wr)
  1308. space = wr;
  1309. memcpy(buf+pos,out,space);
  1310. wr -= space;
  1311. if (wr==0) {
  1312. --nested;
  1313. return; // quick exit
  1314. }
  1315. out += space;
  1316. pos += space;
  1317. }
  1318. extbuf.writeDirect(pos-ROW_WRITER_BUFFERSIZE,wr,out);
  1319. --nested;
  1320. }
  1321. };
  1322. #ifdef TRACE_CREATE
  1323. unsigned CRowStreamWriter::wrnum=0;
  1324. #endif
  1325. IExtRowWriter *createRowWriter(IFile *iFile, IRowInterfaces *rowIf, unsigned flags, ICompressor *compressor, size32_t compressorBlkSz)
  1326. {
  1327. OwnedIFileIO iFileIO;
  1328. if (TestRwFlag(flags, rw_compress))
  1329. {
  1330. size32_t fixedSize = rowIf->queryRowMetaData()->querySerializedDiskMeta()->getFixedSize();
  1331. if (fixedSize && TestRwFlag(flags, rw_grouped))
  1332. ++fixedSize; // row writer will include a grouping byte
  1333. ICompressedFileIO *compressedFileIO = createCompressedFileWriter(iFile, fixedSize, TestRwFlag(flags, rw_extend), TestRwFlag(flags, rw_compressblkcrc), compressor, getCompMethod(flags));
  1334. if (compressorBlkSz)
  1335. compressedFileIO->setBlockSize(compressorBlkSz);
  1336. iFileIO.setown(compressedFileIO);
  1337. }
  1338. else
  1339. iFileIO.setown(iFile->open((flags & rw_extend)?IFOwrite:IFOcreate));
  1340. if (!iFileIO)
  1341. return NULL;
  1342. flags &= ~COMP_MASK;
  1343. return createRowWriter(iFileIO, rowIf, flags);
  1344. }
  1345. IExtRowWriter *createRowWriter(IFileIO *iFileIO, IRowInterfaces *rowIf, unsigned flags, size32_t compressorBlkSz)
  1346. {
  1347. if (TestRwFlag(flags, rw_compress))
  1348. throw MakeStringException(0, "Unsupported createRowWriter flags");
  1349. Owned<IFileIOStream> stream;
  1350. if (TestRwFlag(flags, rw_buffered))
  1351. stream.setown(createBufferedIOStream(iFileIO));
  1352. else
  1353. stream.setown(createIOStream(iFileIO));
  1354. if (flags & rw_extend)
  1355. stream->seek(0, IFSend);
  1356. flags &= ~((unsigned)(rw_extend|rw_buffered));
  1357. return createRowWriter(stream, rowIf, flags);
  1358. }
  1359. IExtRowWriter *createRowWriter(IFileIOStream *strm, IRowInterfaces *rowIf, unsigned flags)
  1360. {
  1361. if (0 != (flags & (rw_extend|rw_buffered|COMP_MASK)))
  1362. throw MakeStringException(0, "Unsupported createRowWriter flags");
  1363. EmptyRowSemantics emptyRowSemantics = extractESRFromRWFlags(flags);
  1364. Owned<CRowStreamWriter> writer = new CRowStreamWriter(strm, rowIf->queryRowSerializer(), rowIf->queryRowAllocator(), emptyRowSemantics, TestRwFlag(flags, rw_crc), TestRwFlag(flags, rw_autoflush));
  1365. return writer.getClear();
  1366. }
  1367. class CDiskMerger : implements IDiskMerger, public CInterface
  1368. {
  1369. IArrayOf<IFile> tempfiles;
  1370. IRowStream **strms;
  1371. Linked<IRecordSize> irecsize;
  1372. StringAttr tempnamebase;
  1373. Linked<IRowLinkCounter> linker;
  1374. Linked<IRowInterfaces> rowInterfaces;
  1375. public:
  1376. IMPLEMENT_IINTERFACE;
  1377. CDiskMerger(IRowInterfaces *_rowInterfaces, IRowLinkCounter *_linker, const char *_tempnamebase)
  1378. : rowInterfaces(_rowInterfaces), linker(_linker), tempnamebase(_tempnamebase)
  1379. {
  1380. strms = NULL;
  1381. }
  1382. ~CDiskMerger()
  1383. {
  1384. for (unsigned i=0;i<tempfiles.ordinality();i++) {
  1385. if (strms&&strms[i])
  1386. strms[i]->Release();
  1387. try
  1388. {
  1389. tempfiles.item(i).remove();
  1390. }
  1391. catch (IException * e)
  1392. {
  1393. //Exceptions inside destructors are bad.
  1394. EXCLOG(e);
  1395. e->Release();
  1396. }
  1397. }
  1398. free(strms);
  1399. }
  1400. IRowWriter *createWriteBlock()
  1401. {
  1402. StringBuffer tempname(tempnamebase);
  1403. tempname.append('.').append(tempfiles.ordinality()).append('_').append((__int64)GetCurrentThreadId()).append('_').append((unsigned)GetCurrentProcessId());
  1404. IFile *file = createIFile(tempname.str());
  1405. tempfiles.append(*file);
  1406. return createRowWriter(file, rowInterfaces);
  1407. }
  1408. void put(const void **rows,unsigned numrows)
  1409. {
  1410. Owned<IRowWriter> out = createWriteBlock();
  1411. for (unsigned i=0;i<numrows;i++)
  1412. out->putRow(rows[i]);
  1413. }
  1414. void putIndirect(const void ***rowptrs,unsigned numrows)
  1415. {
  1416. Owned<IRowWriter> out = createWriteBlock();
  1417. for (unsigned i=0;i<numrows;i++)
  1418. out->putRow(*(rowptrs[i]));
  1419. }
  1420. virtual void put(ISortedRowProvider *rows)
  1421. {
  1422. Owned<IRowWriter> out = createWriteBlock();
  1423. void * row;
  1424. while((row = rows->getNextSorted()) != NULL)
  1425. out->putRow(row);
  1426. }
  1427. IRowStream *merge(ICompare *icompare, bool partdedup)
  1428. {
  1429. unsigned numstrms = tempfiles.ordinality();
  1430. strms = (IRowStream **)calloc(numstrms,sizeof(IRowStream *));
  1431. unsigned i;
  1432. for (i=0;i<numstrms;i++) {
  1433. strms[i] = createRowStream(&tempfiles.item(i), rowInterfaces);
  1434. }
  1435. if (numstrms==1)
  1436. return LINK(strms[0]);
  1437. if (icompare)
  1438. return createRowStreamMerger(numstrms, strms, icompare, partdedup, linker);
  1439. return createConcatRowStream(numstrms,strms);
  1440. }
  1441. virtual count_t mergeTo(IRowWriter *dest, ICompare *icompare, bool partdedup)
  1442. {
  1443. count_t count = 0;
  1444. Owned<IRowStream> mergedStream = merge(icompare, partdedup);
  1445. for (;;)
  1446. {
  1447. const void *row = mergedStream->nextRow();
  1448. if (!row)
  1449. return count;
  1450. dest->putRow(row); // takes ownership
  1451. ++count;
  1452. }
  1453. return count;
  1454. }
  1455. };
  1456. IDiskMerger *createDiskMerger(IRowInterfaces *rowInterfaces, IRowLinkCounter *linker, const char *tempnamebase)
  1457. {
  1458. return new CDiskMerger(rowInterfaces, linker, tempnamebase);
  1459. }
  1460. //---------------------------------------------------------------------------------------------------------------------
  1461. void ActivityTimeAccumulator::addStatistics(IStatisticGatherer & builder) const
  1462. {
  1463. if (totalCycles)
  1464. {
  1465. builder.addStatistic(StWhenFirstRow, firstRow);
  1466. builder.addStatistic(StTimeElapsed, elapsed());
  1467. builder.addStatistic(StTimeTotalExecute, cycle_to_nanosec(totalCycles));
  1468. builder.addStatistic(StTimeFirstExecute, latency());
  1469. }
  1470. }
  1471. void ActivityTimeAccumulator::addStatistics(CRuntimeStatisticCollection & merged) const
  1472. {
  1473. if (totalCycles)
  1474. {
  1475. merged.mergeStatistic(StWhenFirstRow, firstRow);
  1476. merged.mergeStatistic(StTimeElapsed, elapsed());
  1477. merged.mergeStatistic(StTimeTotalExecute, cycle_to_nanosec(totalCycles));
  1478. merged.mergeStatistic(StTimeFirstExecute, latency());
  1479. }
  1480. }
  1481. void ActivityTimeAccumulator::merge(const ActivityTimeAccumulator & other)
  1482. {
  1483. if (other.totalCycles)
  1484. {
  1485. if (totalCycles)
  1486. {
  1487. //Record the earliest start, the latest end, the longest latencies
  1488. cycle_t thisLatency = latencyCycles();
  1489. cycle_t otherLatency = other.latencyCycles();
  1490. cycle_t maxLatency = std::max(thisLatency, otherLatency);
  1491. if (startCycles > other.startCycles)
  1492. {
  1493. startCycles = other.startCycles;
  1494. firstRow =other.firstRow;
  1495. }
  1496. firstExitCycles = startCycles + maxLatency;
  1497. if (endCycles < other.endCycles)
  1498. endCycles = other.endCycles;
  1499. totalCycles += other.totalCycles;
  1500. }
  1501. else
  1502. *this = other;
  1503. }
  1504. }
  1505. //---------------------------------------------------------------------------------------------------------------------
  1506. //MORE: Not currently implemented for windows.
  1507. #ifdef CPU_SETSIZE
  1508. static unsigned getCpuId(const char * text, char * * next)
  1509. {
  1510. unsigned cpu = (unsigned)strtoul(text, next, 10);
  1511. if (*next == text)
  1512. throw makeStringExceptionV(1, "Invalid CPU: %s", text);
  1513. else if (cpu >= CPU_SETSIZE)
  1514. throw makeStringExceptionV(1, "CPU %u is out of range 0..%u", cpu, CPU_SETSIZE);
  1515. return cpu;
  1516. }
  1517. #endif
  1518. void setProcessAffinity(const char * cpuList)
  1519. {
  1520. assertex(cpuList);
  1521. #ifdef CPU_ZERO
  1522. cpu_set_t cpus;
  1523. CPU_ZERO(&cpus);
  1524. const char * cur = cpuList;
  1525. for (;;)
  1526. {
  1527. char * next;
  1528. unsigned cpu1 = getCpuId(cur, &next);
  1529. if (*next == '-')
  1530. {
  1531. const char * range = next+1;
  1532. unsigned cpu2 = getCpuId(range, &next);
  1533. for (unsigned cpu= cpu1; cpu <= cpu2; cpu++)
  1534. CPU_SET(cpu, &cpus);
  1535. }
  1536. else
  1537. CPU_SET(cpu1, &cpus);
  1538. if (*next == '\0')
  1539. break;
  1540. if (*next != ',')
  1541. throw makeStringExceptionV(1, "Invalid cpu affinity list %s", cur);
  1542. cur = next+1;
  1543. }
  1544. if (sched_setaffinity(0, sizeof(cpu_set_t), &cpus))
  1545. throw makeStringException(errno, "Failed to set affinity");
  1546. DBGLOG("Process affinity set to %s", cpuList);
  1547. #endif
  1548. clearAffinityCache();
  1549. }
  1550. void setAutoAffinity(unsigned curProcess, unsigned processPerMachine, const char * optNodes)
  1551. {
  1552. #if defined(CPU_ZERO) && defined(_USE_NUMA)
  1553. if (processPerMachine <= 1)
  1554. return;
  1555. if (numa_available() == -1)
  1556. {
  1557. DBGLOG("Numa functions not available");
  1558. return;
  1559. }
  1560. if (optNodes)
  1561. throw makeStringException(1, "Numa node list not yet supported");
  1562. unsigned numaMap[NUMA_NUM_NODES];
  1563. unsigned numNumaNodes = 0;
  1564. #if defined(LIBNUMA_API_VERSION) && (LIBNUMA_API_VERSION>=2)
  1565. //Create a bit mask to record which nodes are available to the system
  1566. //num_all_nodes_ptr contains only nodes with associated memory - which causes issues on misconfigured systems
  1567. struct bitmask * available_nodes = numa_allocate_nodemask();
  1568. numa_bitmask_clearall(available_nodes);
  1569. unsigned maxcpus = numa_num_configured_cpus();
  1570. for (unsigned cpu=0; cpu < maxcpus; cpu++)
  1571. {
  1572. //Check the cpu can be used by this process.
  1573. if (numa_bitmask_isbitset(numa_all_cpus_ptr, cpu))
  1574. {
  1575. int node = numa_node_of_cpu(cpu);
  1576. if (node != -1)
  1577. numa_bitmask_setbit(available_nodes, node);
  1578. }
  1579. }
  1580. for (unsigned i=0; i<=numa_max_node(); i++)
  1581. {
  1582. if (numa_bitmask_isbitset(available_nodes, i))
  1583. {
  1584. numaMap[numNumaNodes] = i;
  1585. numNumaNodes++;
  1586. if (!numa_bitmask_isbitset(numa_all_nodes_ptr, i))
  1587. DBGLOG("Numa: Potential inefficiency - node %u does not have any associated memory", i);
  1588. }
  1589. }
  1590. numa_bitmask_free(available_nodes);
  1591. DBGLOG("Affinity: Max cpus(%u) nodes(%u) actual nodes(%u), processes(%u)", maxcpus, numa_max_node()+1, numNumaNodes, processPerMachine);
  1592. #else
  1593. //On very old versions of numa assume that all nodes are present
  1594. for (unsigned i=0; i<=numa_max_node(); i++)
  1595. {
  1596. numaMap[numNumaNodes] = i;
  1597. numNumaNodes++;
  1598. }
  1599. #endif
  1600. if (numNumaNodes <= 1)
  1601. return;
  1602. unsigned firstNode = 0;
  1603. unsigned numNodes = 1;
  1604. if (processPerMachine >= numNumaNodes)
  1605. {
  1606. firstNode = curProcess % numNumaNodes;
  1607. }
  1608. else
  1609. {
  1610. firstNode = (curProcess * numNumaNodes) / processPerMachine;
  1611. unsigned nextNode = ((curProcess+1) * numNumaNodes) / processPerMachine;
  1612. numNodes = nextNode - firstNode;
  1613. }
  1614. if ((processPerMachine % numNumaNodes) != 0)
  1615. DBGLOG("Affinity: %u processes will not be evenly balanced over %u numa nodes", processPerMachine, numNumaNodes);
  1616. #if defined(LIBNUMA_API_VERSION) && (LIBNUMA_API_VERSION>=2)
  1617. //This code assumes the nodes are sensibly ordered (e.g., nodes on the same socket are next to each other), and
  1618. //only works well when number of processes is a multiple of the number of numa nodes. A full solution would look
  1619. //at distances.
  1620. struct bitmask * cpus = numa_allocate_cpumask();
  1621. struct bitmask * nodeMask = numa_allocate_cpumask();
  1622. for (unsigned node=0; node < numNodes; node++)
  1623. {
  1624. numa_node_to_cpus(numaMap[firstNode+node], nodeMask);
  1625. //Shame there is no inbuilt union operation.
  1626. for (unsigned cpu=0; cpu < maxcpus; cpu++)
  1627. {
  1628. if (numa_bitmask_isbitset(nodeMask, cpu))
  1629. numa_bitmask_setbit(cpus, cpu);
  1630. }
  1631. }
  1632. bool ok = (numa_sched_setaffinity(0, cpus) == 0);
  1633. numa_bitmask_free(nodeMask);
  1634. numa_bitmask_free(cpus);
  1635. #else
  1636. cpu_set_t cpus;
  1637. CPU_ZERO(&cpus);
  1638. numa_node_to_cpus(numaMap[firstNode], (unsigned long *) &cpus, sizeof (cpus));
  1639. bool ok = sched_setaffinity (0, sizeof(cpus), &cpus) != 0;
  1640. #endif
  1641. if (!ok)
  1642. throw makeStringExceptionV(1, "Failed to set affinity to numa node %u (id:%u)", firstNode, numaMap[firstNode]);
  1643. DBGLOG("Process bound to numa node %u..%u (id:%u) of %u", firstNode, firstNode + numNodes - 1, numaMap[firstNode], numNumaNodes);
  1644. #endif
  1645. clearAffinityCache();
  1646. }
  1647. void bindMemoryToLocalNodes()
  1648. {
  1649. #if defined(LIBNUMA_API_VERSION) && (LIBNUMA_API_VERSION>=2)
  1650. numa_set_bind_policy(1);
  1651. unsigned numNumaNodes = 0;
  1652. for (unsigned i=0; i<=numa_max_node(); i++)
  1653. {
  1654. if (numa_bitmask_isbitset(numa_all_nodes_ptr, i))
  1655. numNumaNodes++;
  1656. }
  1657. if (numNumaNodes <= 1)
  1658. return;
  1659. struct bitmask *nodes = numa_get_run_node_mask();
  1660. numa_set_membind(nodes);
  1661. DBGLOG("Process memory bound to numa nodemask 0x%x (of %u nodes total)", (unsigned)(*(nodes->maskp)), numNumaNodes);
  1662. numa_bitmask_free(nodes);
  1663. #endif
  1664. }
  1665. extern THORHELPER_API IOutputMetaData *getDaliLayoutInfo(IPropertyTree const &props)
  1666. {
  1667. bool isGrouped = props.getPropBool("@grouped", false);
  1668. if (props.hasProp("_rtlType"))
  1669. {
  1670. MemoryBuffer layoutBin;
  1671. props.getPropBin("_rtlType", layoutBin);
  1672. return createTypeInfoOutputMetaData(layoutBin, isGrouped, nullptr);
  1673. }
  1674. else if (props.hasProp("ECL"))
  1675. {
  1676. StringBuffer layoutECL;
  1677. props.getProp("ECL", layoutECL);
  1678. MultiErrorReceiver errs;
  1679. Owned<IHqlExpression> expr = parseQuery(layoutECL.str(), &errs);
  1680. if (errs.errCount() == 0)
  1681. {
  1682. MemoryBuffer layoutBin;
  1683. if (exportBinaryType(layoutBin, expr))
  1684. return createTypeInfoOutputMetaData(layoutBin, isGrouped, nullptr);
  1685. }
  1686. }
  1687. return nullptr;
  1688. }