thorcommon.cpp 55 KB

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