thorcommon.cpp 70 KB

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