thorcommon.cpp 58 KB

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