thorcommon.cpp 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923
  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. for (;;)
  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. for (;;)
  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, unsigned heapFlags, ICodeContext *context)
  947. {
  948. class cRowInterfaces: implements IRowInterfaces, public CSimpleInterface
  949. {
  950. unsigned actid;
  951. Linked<IOutputMetaData> meta;
  952. ICodeContext* context;
  953. Linked<IEngineRowAllocator> allocator;
  954. Linked<IOutputRowSerializer> serializer;
  955. Linked<IOutputRowDeserializer> deserializer;
  956. CSingletonLock allocatorlock;
  957. CSingletonLock serializerlock;
  958. CSingletonLock deserializerlock;
  959. unsigned heapFlags;
  960. public:
  961. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  962. cRowInterfaces(IOutputMetaData *_meta,unsigned _actid, unsigned _heapFlags, ICodeContext *_context)
  963. : meta(_meta), heapFlags(_heapFlags)
  964. {
  965. context = _context;
  966. actid = _actid;
  967. }
  968. IEngineRowAllocator * queryRowAllocator()
  969. {
  970. if (allocatorlock.lock()) {
  971. if (!allocator&&meta)
  972. allocator.setown(context->getRowAllocatorEx(meta, actid, heapFlags));
  973. allocatorlock.unlock();
  974. }
  975. return allocator;
  976. }
  977. IOutputRowSerializer * queryRowSerializer()
  978. {
  979. if (serializerlock.lock()) {
  980. if (!serializer&&meta)
  981. serializer.setown(meta->createDiskSerializer(context,actid));
  982. serializerlock.unlock();
  983. }
  984. return serializer;
  985. }
  986. IOutputRowDeserializer * queryRowDeserializer()
  987. {
  988. if (deserializerlock.lock()) {
  989. if (!deserializer&&meta)
  990. deserializer.setown(meta->createDiskDeserializer(context,actid));
  991. deserializerlock.unlock();
  992. }
  993. return deserializer;
  994. }
  995. IOutputMetaData *queryRowMetaData()
  996. {
  997. return meta;
  998. }
  999. unsigned queryActivityId() const
  1000. {
  1001. return actid;
  1002. }
  1003. ICodeContext *queryCodeContext()
  1004. {
  1005. return context;
  1006. }
  1007. };
  1008. return new cRowInterfaces(meta,actid,heapFlags,context);
  1009. };
  1010. class CRowStreamReader : implements IExtRowStream, public CSimpleInterface
  1011. {
  1012. protected:
  1013. Linked<IFileIO> fileio;
  1014. Linked<IMemoryMappedFile> mmfile;
  1015. Linked<IOutputRowDeserializer> deserializer;
  1016. Linked<IEngineRowAllocator> allocator;
  1017. Owned<ISerialStream> strm;
  1018. CThorStreamDeserializerSource source;
  1019. Owned<ISourceRowPrefetcher> prefetcher;
  1020. CThorContiguousRowBuffer prefetchBuffer; // used if prefetcher set
  1021. bool grouped;
  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, 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. grouped = _grouped;
  1047. eoi = false;
  1048. eos = false;
  1049. eog = false;
  1050. bufofs = 0;
  1051. if (fileio)
  1052. strm.setown(createFileSerialStream(fileio,_ofs,_len,(size32_t)-1, _tallycrc?&crccb:NULL));
  1053. else
  1054. strm.setown(createFileSerialStream(mmfile,_ofs,_len,_tallycrc?&crccb:NULL));
  1055. prefetcher.setown(rowif->queryRowMetaData()->createDiskPrefetcher(rowif->queryCodeContext(), rowif->queryActivityId()));
  1056. if (prefetcher)
  1057. prefetchBuffer.setStream(strm);
  1058. source.setStream(strm);
  1059. deserializer.set(rowif->queryRowDeserializer());
  1060. }
  1061. ~CRowStreamReader()
  1062. {
  1063. #ifdef TRACE_CREATE
  1064. PROGLOG("~CRowStreamReader %d = %p",rdnum--,this);
  1065. #endif
  1066. }
  1067. void reinit(offset_t _ofs,offset_t _len,unsigned __int64 _maxrows)
  1068. {
  1069. assertex(_maxrows == 0);
  1070. eoi = false;
  1071. eos = (_len==0);
  1072. eog = false;
  1073. bufofs = 0;
  1074. strm->reset(_ofs,_len);
  1075. }
  1076. const void *nextRow()
  1077. {
  1078. if (eog) {
  1079. eog = false;
  1080. return NULL;
  1081. }
  1082. if (eos)
  1083. return NULL;
  1084. if (source.eos()) {
  1085. eos = true;
  1086. return NULL;
  1087. }
  1088. RtlDynamicRowBuilder rowBuilder(*allocator);
  1089. size_t size = deserializer->deserialize(rowBuilder,source);
  1090. if (grouped) {
  1091. byte b;
  1092. source.read(sizeof(b),&b);
  1093. eog = (b==1);
  1094. }
  1095. return rowBuilder.finalizeRowClear(size);
  1096. }
  1097. const void *prefetchRow(size32_t *sz)
  1098. {
  1099. if (eog)
  1100. eog = false;
  1101. else if (!eos) {
  1102. if (source.eos())
  1103. eos = true;
  1104. else {
  1105. assertex(prefetcher);
  1106. prefetcher->readAhead(prefetchBuffer);
  1107. const byte * ret = prefetchBuffer.queryRow();
  1108. if (sz)
  1109. *sz = prefetchBuffer.queryRowSize();
  1110. return ret;
  1111. }
  1112. }
  1113. if (sz)
  1114. sz = 0;
  1115. return NULL;
  1116. }
  1117. void prefetchDone()
  1118. {
  1119. prefetchBuffer.finishedRow();
  1120. if (grouped) {
  1121. byte b;
  1122. strm->get(sizeof(b),&b);
  1123. eog = (b==1);
  1124. }
  1125. }
  1126. virtual void stop()
  1127. {
  1128. stop(NULL);
  1129. }
  1130. void clear()
  1131. {
  1132. strm.clear();
  1133. source.clearStream();
  1134. fileio.clear();
  1135. }
  1136. void stop(CRC32 *crcout)
  1137. {
  1138. if (!eos) {
  1139. eos = true;
  1140. clear();
  1141. }
  1142. // NB CRC will only be right if stopped at eos
  1143. if (crcout)
  1144. *crcout = crccb.crc;
  1145. }
  1146. offset_t getOffset()
  1147. {
  1148. return source.tell();
  1149. }
  1150. virtual unsigned __int64 getStatistic(StatisticKind kind)
  1151. {
  1152. if (fileio)
  1153. return fileio->getStatistic(kind);
  1154. return 0;
  1155. }
  1156. };
  1157. class CLimitedRowStreamReader : public CRowStreamReader
  1158. {
  1159. unsigned __int64 maxrows;
  1160. unsigned __int64 rownum;
  1161. public:
  1162. CLimitedRowStreamReader(IFileIO *_fileio, IMemoryMappedFile *_mmfile, IRowInterfaces *rowif, offset_t _ofs, offset_t _len, unsigned __int64 _maxrows, bool _tallycrc, bool _grouped)
  1163. : CRowStreamReader(_fileio, _mmfile, rowif, _ofs, _len, _tallycrc, _grouped)
  1164. {
  1165. maxrows = _maxrows;
  1166. rownum = 0;
  1167. eos = maxrows==0;
  1168. }
  1169. void reinit(offset_t _ofs,offset_t _len,unsigned __int64 _maxrows)
  1170. {
  1171. CRowStreamReader::reinit(_ofs, _len, 0);
  1172. if (_maxrows==0)
  1173. eos = true;
  1174. maxrows = _maxrows;
  1175. rownum = 0;
  1176. }
  1177. const void *nextRow()
  1178. {
  1179. const void * ret = CRowStreamReader::nextRow();
  1180. if (++rownum==maxrows)
  1181. eos = true;
  1182. return ret;
  1183. }
  1184. };
  1185. #ifdef TRACE_CREATE
  1186. unsigned CRowStreamReader::rdnum;
  1187. #endif
  1188. bool UseMemoryMappedRead = false;
  1189. IExtRowStream *createRowStreamEx(IFile *file, IRowInterfaces *rowIf, offset_t offset, offset_t len, unsigned __int64 maxrows, unsigned rwFlags, IExpander *eexp)
  1190. {
  1191. bool compressed = TestRwFlag(rwFlags, rw_compress);
  1192. if (UseMemoryMappedRead && !compressed)
  1193. {
  1194. PROGLOG("Memory Mapped read of %s",file->queryFilename());
  1195. Owned<IMemoryMappedFile> mmfile = file->openMemoryMapped();
  1196. if (!mmfile)
  1197. return NULL;
  1198. if (maxrows == (unsigned __int64)-1)
  1199. return new CRowStreamReader(NULL, mmfile, rowIf, offset, len, TestRwFlag(rwFlags, rw_crc), TestRwFlag(rwFlags, rw_grouped));
  1200. else
  1201. return new CLimitedRowStreamReader(NULL, mmfile, rowIf, offset, len, maxrows, TestRwFlag(rwFlags, rw_crc), TestRwFlag(rwFlags, rw_grouped));
  1202. }
  1203. else
  1204. {
  1205. Owned<IFileIO> fileio;
  1206. if (compressed)
  1207. {
  1208. // JCSMORE should pass in a flag for rw_compressblkcrc I think, doesn't look like it (or anywhere else)
  1209. // checks the block crc's at the moment.
  1210. fileio.setown(createCompressedFileReader(file, eexp, UseMemoryMappedRead));
  1211. }
  1212. else
  1213. fileio.setown(file->open(IFOread));
  1214. if (!fileio)
  1215. return NULL;
  1216. if (maxrows == (unsigned __int64)-1)
  1217. return new CRowStreamReader(fileio, NULL, rowIf, offset, len, TestRwFlag(rwFlags, rw_crc), TestRwFlag(rwFlags, rw_grouped));
  1218. else
  1219. return new CLimitedRowStreamReader(fileio, NULL, rowIf, offset, len, maxrows, TestRwFlag(rwFlags, rw_crc), TestRwFlag(rwFlags, rw_grouped));
  1220. }
  1221. }
  1222. IExtRowStream *createRowStream(IFile *file, IRowInterfaces *rowIf, unsigned rwFlags, IExpander *eexp)
  1223. {
  1224. return createRowStreamEx(file, rowIf, 0, (offset_t)-1, (unsigned __int64)-1, rwFlags, eexp);
  1225. }
  1226. // Memory map sizes can be big, restrict to 64-bit platforms.
  1227. void useMemoryMappedRead(bool on)
  1228. {
  1229. #if defined(_DEBUG) || defined(__64BIT__)
  1230. UseMemoryMappedRead = on;
  1231. #endif
  1232. }
  1233. #define ROW_WRITER_BUFFERSIZE (0x100000)
  1234. class CRowStreamWriter : private IRowSerializerTarget, implements IExtRowWriter, public CSimpleInterface
  1235. {
  1236. Linked<IFileIOStream> stream;
  1237. Linked<IOutputRowSerializer> serializer;
  1238. Linked<IEngineRowAllocator> allocator;
  1239. CRC32 crc;
  1240. bool grouped;
  1241. bool tallycrc;
  1242. unsigned nested;
  1243. MemoryAttr ma;
  1244. MemoryBuffer extbuf; // may need to spill to disk at some point
  1245. byte *buf;
  1246. size32_t bufpos;
  1247. bool autoflush;
  1248. #ifdef TRACE_CREATE
  1249. static unsigned wrnum;
  1250. #endif
  1251. void flushBuffer(bool final)
  1252. {
  1253. try
  1254. {
  1255. if (bufpos) {
  1256. stream->write(bufpos,buf);
  1257. if (tallycrc)
  1258. crc.tally(bufpos,buf);
  1259. bufpos = 0;
  1260. }
  1261. size32_t extpos = extbuf.length();
  1262. if (!extpos)
  1263. return;
  1264. if (!final)
  1265. extpos = (extpos/ROW_WRITER_BUFFERSIZE)*ROW_WRITER_BUFFERSIZE;
  1266. if (extpos) {
  1267. stream->write(extpos,extbuf.toByteArray());
  1268. if (tallycrc)
  1269. crc.tally(extpos,extbuf.toByteArray());
  1270. }
  1271. if (extpos<extbuf.length()) {
  1272. bufpos = extbuf.length()-extpos;
  1273. memcpy(buf,extbuf.toByteArray()+extpos,bufpos);
  1274. }
  1275. extbuf.clear();
  1276. }
  1277. catch (IException *e)
  1278. {
  1279. autoflush = false; // avoid follow-on errors
  1280. EXCLOG(e, "flushBuffer");
  1281. throw;
  1282. }
  1283. }
  1284. void streamFlush()
  1285. {
  1286. try
  1287. {
  1288. stream->flush();
  1289. }
  1290. catch (IException *e)
  1291. {
  1292. autoflush = false; // avoid follow-on errors
  1293. EXCLOG(e, "streamFlush");
  1294. throw;
  1295. }
  1296. }
  1297. public:
  1298. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  1299. CRowStreamWriter(IFileIOStream *_stream,IOutputRowSerializer *_serializer,IEngineRowAllocator *_allocator,bool _grouped, bool _tallycrc, bool _autoflush)
  1300. : stream(_stream), serializer(_serializer), allocator(_allocator)
  1301. {
  1302. #ifdef TRACE_CREATE
  1303. PROGLOG("createRowWriter %d = %p",++wrnum,this);
  1304. #endif
  1305. grouped = _grouped;
  1306. tallycrc = _tallycrc;
  1307. nested = 0;
  1308. buf = (byte *)ma.allocate(ROW_WRITER_BUFFERSIZE);
  1309. bufpos = 0;
  1310. autoflush = _autoflush;
  1311. }
  1312. ~CRowStreamWriter()
  1313. {
  1314. #ifdef TRACE_CREATE
  1315. PROGLOG("~createRowWriter %d = %p",wrnum--,this);
  1316. #endif
  1317. if (autoflush)
  1318. flush();
  1319. else if (bufpos+extbuf.length()) {
  1320. #ifdef _DEBUG
  1321. PrintStackReport();
  1322. #endif
  1323. WARNLOG("CRowStreamWriter closed with %d bytes unflushed",bufpos+extbuf.length());
  1324. }
  1325. }
  1326. void putRow(const void *row)
  1327. {
  1328. if (row) {
  1329. serializer->serialize(*this,(const byte *)row);
  1330. if (grouped) {
  1331. byte b = 0;
  1332. if (bufpos<ROW_WRITER_BUFFERSIZE)
  1333. buf[bufpos++] = b;
  1334. else
  1335. extbuf.append(b);
  1336. }
  1337. allocator->releaseRow(row);
  1338. }
  1339. else if (grouped) { // backpatch
  1340. byte b = 1;
  1341. if (extbuf.length())
  1342. extbuf.writeDirect(extbuf.length()-1,sizeof(b),&b);
  1343. else {
  1344. assertex(bufpos);
  1345. buf[bufpos-1] = b;
  1346. }
  1347. }
  1348. }
  1349. void flush()
  1350. {
  1351. flushBuffer(true);
  1352. streamFlush();
  1353. }
  1354. void flush(CRC32 *crcout)
  1355. {
  1356. flushBuffer(true);
  1357. streamFlush();
  1358. if (crcout)
  1359. *crcout = crc;
  1360. }
  1361. offset_t getPosition()
  1362. {
  1363. return stream->tell()+bufpos+extbuf.length();
  1364. }
  1365. void put(size32_t len, const void * ptr)
  1366. {
  1367. // first fill buf
  1368. for (;;) {
  1369. if (bufpos<ROW_WRITER_BUFFERSIZE) {
  1370. size32_t wr = ROW_WRITER_BUFFERSIZE-bufpos;
  1371. if (wr>len)
  1372. wr = len;
  1373. memcpy(buf+bufpos,ptr,wr);
  1374. bufpos += wr;
  1375. len -= wr;
  1376. if (len==0)
  1377. break; // quick exit
  1378. ptr = (const byte *)ptr + wr;
  1379. }
  1380. if (nested) {
  1381. // have to append to ext buffer (will need to spill to disk here if gets *too* big)
  1382. extbuf.append(len,ptr);
  1383. break;
  1384. }
  1385. else
  1386. flushBuffer(false);
  1387. }
  1388. }
  1389. size32_t beginNested(size32_t count)
  1390. {
  1391. if (nested++==0)
  1392. if (bufpos==ROW_WRITER_BUFFERSIZE)
  1393. flushBuffer(false);
  1394. size32_t ret = bufpos+extbuf.length();
  1395. size32_t sz = 0;
  1396. put(sizeof(sz),&sz);
  1397. return ret;
  1398. }
  1399. void endNested(size32_t pos)
  1400. {
  1401. size32_t sz = bufpos+extbuf.length()-(pos + sizeof(size32_t));
  1402. size32_t wr = sizeof(size32_t);
  1403. byte *out = (byte *)&sz;
  1404. if (pos<ROW_WRITER_BUFFERSIZE) {
  1405. size32_t space = ROW_WRITER_BUFFERSIZE-pos;
  1406. if (space>wr)
  1407. space = wr;
  1408. memcpy(buf+pos,out,space);
  1409. wr -= space;
  1410. if (wr==0) {
  1411. --nested;
  1412. return; // quick exit
  1413. }
  1414. out += space;
  1415. pos += space;
  1416. }
  1417. extbuf.writeDirect(pos-ROW_WRITER_BUFFERSIZE,wr,out);
  1418. --nested;
  1419. }
  1420. };
  1421. #ifdef TRACE_CREATE
  1422. unsigned CRowStreamWriter::wrnum=0;
  1423. #endif
  1424. IExtRowWriter *createRowWriter(IFile *iFile, IRowInterfaces *rowIf, unsigned flags, ICompressor *compressor)
  1425. {
  1426. OwnedIFileIO iFileIO;
  1427. if (TestRwFlag(flags, rw_compress))
  1428. {
  1429. size32_t fixedSize = rowIf->queryRowMetaData()->querySerializedDiskMeta()->getFixedSize();
  1430. if (fixedSize && TestRwFlag(flags, rw_grouped))
  1431. ++fixedSize; // row writer will include a grouping byte
  1432. iFileIO.setown(createCompressedFileWriter(iFile, fixedSize, TestRwFlag(flags, rw_extend), TestRwFlag(flags, rw_compressblkcrc), compressor, getCompMethod(flags)));
  1433. }
  1434. else
  1435. iFileIO.setown(iFile->open((flags & rw_extend)?IFOwrite:IFOcreate));
  1436. if (!iFileIO)
  1437. return NULL;
  1438. flags &= ~COMP_MASK;
  1439. return createRowWriter(iFileIO, rowIf, flags);
  1440. }
  1441. IExtRowWriter *createRowWriter(IFileIO *iFileIO, IRowInterfaces *rowIf, unsigned flags)
  1442. {
  1443. if (TestRwFlag(flags, rw_compress))
  1444. throw MakeStringException(0, "Unsupported createRowWriter flags");
  1445. Owned<IFileIOStream> stream;
  1446. if (TestRwFlag(flags, rw_buffered))
  1447. stream.setown(createBufferedIOStream(iFileIO));
  1448. else
  1449. stream.setown(createIOStream(iFileIO));
  1450. if (flags & rw_extend)
  1451. stream->seek(0, IFSend);
  1452. flags &= ~((unsigned)(rw_extend|rw_buffered));
  1453. return createRowWriter(stream, rowIf, flags);
  1454. }
  1455. IExtRowWriter *createRowWriter(IFileIOStream *strm, IRowInterfaces *rowIf, unsigned flags)
  1456. {
  1457. if (0 != (flags & (rw_extend|rw_buffered|COMP_MASK)))
  1458. throw MakeStringException(0, "Unsupported createRowWriter flags");
  1459. Owned<CRowStreamWriter> writer = new CRowStreamWriter(strm, rowIf->queryRowSerializer(), rowIf->queryRowAllocator(), TestRwFlag(flags, rw_grouped), TestRwFlag(flags, rw_crc), TestRwFlag(flags, rw_autoflush));
  1460. return writer.getClear();
  1461. }
  1462. class CDiskMerger : implements IDiskMerger, public CInterface
  1463. {
  1464. IArrayOf<IFile> tempfiles;
  1465. IRowStream **strms;
  1466. Linked<IRecordSize> irecsize;
  1467. StringAttr tempnamebase;
  1468. Linked<IRowLinkCounter> linker;
  1469. Linked<IRowInterfaces> rowInterfaces;
  1470. public:
  1471. IMPLEMENT_IINTERFACE;
  1472. CDiskMerger(IRowInterfaces *_rowInterfaces, IRowLinkCounter *_linker, const char *_tempnamebase)
  1473. : rowInterfaces(_rowInterfaces), linker(_linker), tempnamebase(_tempnamebase)
  1474. {
  1475. strms = NULL;
  1476. }
  1477. ~CDiskMerger()
  1478. {
  1479. for (unsigned i=0;i<tempfiles.ordinality();i++) {
  1480. if (strms&&strms[i])
  1481. strms[i]->Release();
  1482. try
  1483. {
  1484. tempfiles.item(i).remove();
  1485. }
  1486. catch (IException * e)
  1487. {
  1488. //Exceptions inside destructors are bad.
  1489. EXCLOG(e);
  1490. e->Release();
  1491. }
  1492. }
  1493. free(strms);
  1494. }
  1495. IRowWriter *createWriteBlock()
  1496. {
  1497. StringBuffer tempname(tempnamebase);
  1498. tempname.append('.').append(tempfiles.ordinality()).append('_').append((__int64)GetCurrentThreadId()).append('_').append((unsigned)GetCurrentProcessId());
  1499. IFile *file = createIFile(tempname.str());
  1500. tempfiles.append(*file);
  1501. return createRowWriter(file, rowInterfaces);
  1502. }
  1503. void put(const void **rows,unsigned numrows)
  1504. {
  1505. Owned<IRowWriter> out = createWriteBlock();
  1506. for (unsigned i=0;i<numrows;i++)
  1507. out->putRow(rows[i]);
  1508. }
  1509. void putIndirect(const void ***rowptrs,unsigned numrows)
  1510. {
  1511. Owned<IRowWriter> out = createWriteBlock();
  1512. for (unsigned i=0;i<numrows;i++)
  1513. out->putRow(*(rowptrs[i]));
  1514. }
  1515. virtual void put(ISortedRowProvider *rows)
  1516. {
  1517. Owned<IRowWriter> out = createWriteBlock();
  1518. void * row;
  1519. while((row = rows->getNextSorted()) != NULL)
  1520. out->putRow(row);
  1521. }
  1522. IRowStream *merge(ICompare *icompare, bool partdedup)
  1523. {
  1524. unsigned numstrms = tempfiles.ordinality();
  1525. strms = (IRowStream **)calloc(numstrms,sizeof(IRowStream *));
  1526. unsigned i;
  1527. for (i=0;i<numstrms;i++) {
  1528. strms[i] = createRowStream(&tempfiles.item(i), rowInterfaces);
  1529. }
  1530. if (numstrms==1)
  1531. return LINK(strms[0]);
  1532. if (icompare)
  1533. return createRowStreamMerger(numstrms, strms, icompare, partdedup, linker);
  1534. return createConcatRowStream(numstrms,strms);
  1535. }
  1536. virtual count_t mergeTo(IRowWriter *dest, ICompare *icompare, bool partdedup)
  1537. {
  1538. count_t count = 0;
  1539. Owned<IRowStream> mergedStream = merge(icompare, partdedup);
  1540. for (;;)
  1541. {
  1542. const void *row = mergedStream->nextRow();
  1543. if (!row)
  1544. return count;
  1545. dest->putRow(row); // takes ownership
  1546. ++count;
  1547. }
  1548. return count;
  1549. }
  1550. };
  1551. IDiskMerger *createDiskMerger(IRowInterfaces *rowInterfaces, IRowLinkCounter *linker, const char *tempnamebase)
  1552. {
  1553. return new CDiskMerger(rowInterfaces, linker, tempnamebase);
  1554. }
  1555. //---------------------------------------------------------------------------------------------------------------------
  1556. void ActivityTimeAccumulator::addStatistics(IStatisticGatherer & builder) const
  1557. {
  1558. if (totalCycles)
  1559. {
  1560. builder.addStatistic(StWhenFirstRow, firstRow);
  1561. builder.addStatistic(StTimeElapsed, elapsed());
  1562. builder.addStatistic(StTimeTotalExecute, cycle_to_nanosec(totalCycles));
  1563. builder.addStatistic(StTimeFirstExecute, latency());
  1564. }
  1565. }
  1566. void ActivityTimeAccumulator::addStatistics(CRuntimeStatisticCollection & merged) const
  1567. {
  1568. if (totalCycles)
  1569. {
  1570. merged.mergeStatistic(StWhenFirstRow, firstRow);
  1571. merged.mergeStatistic(StTimeElapsed, elapsed());
  1572. merged.mergeStatistic(StTimeTotalExecute, cycle_to_nanosec(totalCycles));
  1573. merged.mergeStatistic(StTimeFirstExecute, latency());
  1574. }
  1575. }
  1576. void ActivityTimeAccumulator::merge(const ActivityTimeAccumulator & other)
  1577. {
  1578. if (other.totalCycles)
  1579. {
  1580. if (totalCycles)
  1581. {
  1582. //Record the earliest start, the latest end, the longest latencies
  1583. cycle_t thisLatency = latencyCycles();
  1584. cycle_t otherLatency = other.latencyCycles();
  1585. cycle_t maxLatency = std::max(thisLatency, otherLatency);
  1586. if (startCycles > other.startCycles)
  1587. {
  1588. startCycles = other.startCycles;
  1589. firstRow =other.firstRow;
  1590. }
  1591. firstExitCycles = startCycles + maxLatency;
  1592. if (endCycles < other.endCycles)
  1593. endCycles = other.endCycles;
  1594. totalCycles += other.totalCycles;
  1595. }
  1596. else
  1597. *this = other;
  1598. }
  1599. }
  1600. //---------------------------------------------------------------------------------------------------------------------
  1601. //MORE: Not currently implemented for windows.
  1602. #ifdef CPU_SETSIZE
  1603. static unsigned getCpuId(const char * text, char * * next)
  1604. {
  1605. unsigned cpu = (unsigned)strtoul(text, next, 10);
  1606. if (*next == text)
  1607. throw makeStringExceptionV(1, "Invalid CPU: %s", text);
  1608. else if (cpu >= CPU_SETSIZE)
  1609. throw makeStringExceptionV(1, "CPU %u is out of range 0..%u", cpu, CPU_SETSIZE);
  1610. return cpu;
  1611. }
  1612. #endif
  1613. void setProcessAffinity(const char * cpuList)
  1614. {
  1615. assertex(cpuList);
  1616. #ifdef CPU_ZERO
  1617. cpu_set_t cpus;
  1618. CPU_ZERO(&cpus);
  1619. const char * cur = cpuList;
  1620. for (;;)
  1621. {
  1622. char * next;
  1623. unsigned cpu1 = getCpuId(cur, &next);
  1624. if (*next == '-')
  1625. {
  1626. const char * range = next+1;
  1627. unsigned cpu2 = getCpuId(range, &next);
  1628. for (unsigned cpu= cpu1; cpu <= cpu2; cpu++)
  1629. CPU_SET(cpu, &cpus);
  1630. }
  1631. else
  1632. CPU_SET(cpu1, &cpus);
  1633. if (*next == '\0')
  1634. break;
  1635. if (*next != ',')
  1636. throw makeStringExceptionV(1, "Invalid cpu affinity list %s", cur);
  1637. cur = next+1;
  1638. }
  1639. if (sched_setaffinity(0, sizeof(cpu_set_t), &cpus))
  1640. throw makeStringException(errno, "Failed to set affinity");
  1641. DBGLOG("Process affinity set to %s", cpuList);
  1642. #endif
  1643. clearAffinityCache();
  1644. }
  1645. void setAutoAffinity(unsigned curProcess, unsigned processPerMachine, const char * optNodes)
  1646. {
  1647. #if defined(CPU_ZERO) && defined(_USE_NUMA)
  1648. if (processPerMachine <= 1)
  1649. return;
  1650. if (numa_available() == -1)
  1651. {
  1652. DBGLOG("Numa functions not available");
  1653. return;
  1654. }
  1655. if (optNodes)
  1656. throw makeStringException(1, "Numa node list not yet supported");
  1657. unsigned numaMap[NUMA_NUM_NODES];
  1658. unsigned numNumaNodes = 0;
  1659. #if defined(LIBNUMA_API_VERSION) && (LIBNUMA_API_VERSION>=2)
  1660. //Create a bit mask to record which nodes are available to the system
  1661. //num_all_nodes_ptr contains only nodes with associated memory - which causes issues on misconfigured systems
  1662. struct bitmask * available_nodes = numa_allocate_nodemask();
  1663. numa_bitmask_clearall(available_nodes);
  1664. unsigned maxcpus = numa_num_configured_cpus();
  1665. for (unsigned cpu=0; cpu < maxcpus; cpu++)
  1666. {
  1667. //Check the cpu can be used by this process.
  1668. if (numa_bitmask_isbitset(numa_all_cpus_ptr, cpu))
  1669. {
  1670. int node = numa_node_of_cpu(cpu);
  1671. if (node != -1)
  1672. numa_bitmask_setbit(available_nodes, node);
  1673. }
  1674. }
  1675. for (unsigned i=0; i<=numa_max_node(); i++)
  1676. {
  1677. if (numa_bitmask_isbitset(available_nodes, i))
  1678. {
  1679. numaMap[numNumaNodes] = i;
  1680. numNumaNodes++;
  1681. if (!numa_bitmask_isbitset(numa_all_nodes_ptr, i))
  1682. DBGLOG("Numa: Potential inefficiency - node %u does not have any associated memory", i);
  1683. }
  1684. }
  1685. numa_bitmask_free(available_nodes);
  1686. DBGLOG("Affinity: Max cpus(%u) nodes(%u) actual nodes(%u)", maxcpus, numa_max_node()+1, numNumaNodes);
  1687. #else
  1688. //On very old versions of numa assume that all nodes are present
  1689. for (unsigned i=0; i<=numa_max_node(); i++)
  1690. {
  1691. numaMap[numNumaNodes] = i;
  1692. numNumaNodes++;
  1693. }
  1694. #endif
  1695. if (numNumaNodes <= 1)
  1696. return;
  1697. //MORE: If processPerMachine < numNumaNodes we may want to associate with > 1 node.
  1698. unsigned curNode = curProcess % numNumaNodes;
  1699. #if defined(LIBNUMA_API_VERSION) && (LIBNUMA_API_VERSION>=2)
  1700. struct bitmask * cpus = numa_allocate_cpumask();
  1701. numa_node_to_cpus(numaMap[curNode], cpus);
  1702. bool ok = (numa_sched_setaffinity(0, cpus) == 0);
  1703. numa_bitmask_free(cpus);
  1704. #else
  1705. cpu_set_t cpus;
  1706. CPU_ZERO(&cpus);
  1707. numa_node_to_cpus(numaMap[curNode], (unsigned long *) &cpus, sizeof (cpus));
  1708. bool ok = sched_setaffinity (0, sizeof(cpus), &cpus) != 0;
  1709. #endif
  1710. if (!ok)
  1711. throw makeStringExceptionV(1, "Failed to set affinity to numa node %u (id:%u)", curNode, numaMap[curNode]);
  1712. DBGLOG("Process bound to numa node %u (id:%u) of %u", curNode, numaMap[curNode], numNumaNodes);
  1713. #endif
  1714. clearAffinityCache();
  1715. }
  1716. void bindMemoryToLocalNodes()
  1717. {
  1718. #if defined(LIBNUMA_API_VERSION) && (LIBNUMA_API_VERSION>=2)
  1719. numa_set_bind_policy(1);
  1720. unsigned numNumaNodes = 0;
  1721. for (unsigned i=0; i<=numa_max_node(); i++)
  1722. {
  1723. if (numa_bitmask_isbitset(numa_all_nodes_ptr, i))
  1724. numNumaNodes++;
  1725. }
  1726. if (numNumaNodes <= 1)
  1727. return;
  1728. struct bitmask *nodes = numa_get_run_node_mask();
  1729. numa_set_membind(nodes);
  1730. DBGLOG("Process memory bound to numa nodemask 0x%x (of %u nodes total)", (unsigned)(*(nodes->maskp)), numNumaNodes);
  1731. numa_bitmask_free(nodes);
  1732. #endif
  1733. }