roxiehelper.cpp 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798
  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 "thorsort.hpp"
  15. #include "roxiehelper.hpp"
  16. #include "roxielmj.hpp"
  17. #include "roxierow.hpp"
  18. #include "roxierowbuff.hpp"
  19. #include "jmisc.hpp"
  20. #include "jfile.hpp"
  21. #include "mpbase.hpp"
  22. #include "dafdesc.hpp"
  23. #include "dadfs.hpp"
  24. #include "zcrypt.hpp"
  25. unsigned traceLevel = 0;
  26. const void * IEngineRowStream::nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra &stepExtra)
  27. {
  28. // can only be called on stepping fields.
  29. throwUnexpected();
  30. }
  31. //=========================================================================================
  32. //OwnedRowArray
  33. void OwnedRowArray::clear()
  34. {
  35. roxiemem::ReleaseRoxieRowArray(buff.ordinality(), buff.getArray());
  36. buff.kill();
  37. }
  38. void OwnedRowArray::clearPart(aindex_t from, aindex_t to)
  39. {
  40. roxiemem::ReleaseRoxieRowRange(buff.getArray(), from, to);
  41. buff.removen(from, to-from);
  42. }
  43. void OwnedRowArray::replace(const void * row, aindex_t pos)
  44. {
  45. ReleaseRoxieRow(buff.item(pos));
  46. buff.replace(row, pos);
  47. }
  48. //=========================================================================================
  49. //CRHRollingCacheElem copied/modified from THOR
  50. CRHRollingCacheElem::CRHRollingCacheElem()
  51. {
  52. row = NULL;
  53. cmp = INT_MIN;
  54. }
  55. CRHRollingCacheElem::~CRHRollingCacheElem()
  56. {
  57. if (row)
  58. ReleaseRoxieRow(row);
  59. }
  60. void CRHRollingCacheElem::set(const void *_row)
  61. {
  62. if (row)
  63. ReleaseRoxieRow(row);
  64. row = _row;
  65. }
  66. //CRHRollingCache copied/modified from THOR CRollingCache
  67. CRHRollingCache::~CRHRollingCache()
  68. {
  69. while (cache.ordinality())
  70. {
  71. CRHRollingCacheElem *e = cache.dequeue();
  72. delete e;
  73. }
  74. }
  75. void CRHRollingCache::init(IRowStream *_in, unsigned _max)
  76. {
  77. max = _max;
  78. in =_in;
  79. cache.clear();
  80. cache.reserve(max);
  81. eos = false;
  82. while (cache.ordinality()<max/2)
  83. cache.enqueue(NULL);
  84. while (!eos && (cache.ordinality()<max))
  85. advance();
  86. }
  87. #ifdef TRACEROLLING
  88. void CRHRollingCache::PrintCache()
  89. {
  90. for (unsigned i = 0;i<max;i++) {
  91. CRHRollingCacheElem *e = cache.item(i);
  92. if (i==0)
  93. DBGLOG("RC==============================");
  94. int ii = 0;
  95. if (e && e->row)
  96. ii = isalpha(*((char*)e->row)) ? 0 : 4;
  97. chas sz[100];
  98. sprintf(sz,"%c%d: %s",(i==max/2)?'>':' ',i,e?(const char *)e->row+ii:"-----");
  99. for (int xx=0; sz[xx] != NULL; xx++)
  100. {
  101. if (!isprint(sz[xx]))
  102. {
  103. sz[xx] = NULL;
  104. break;
  105. }
  106. }
  107. DBGLOG(sz);
  108. if (i == max-1)
  109. DBGLOG("RC==============================");
  110. }
  111. }
  112. #endif
  113. CRHRollingCacheElem * CRHRollingCache::mid(int rel)
  114. {
  115. return cache.item((max/2)+rel); // relies on unsigned wrap
  116. }
  117. void CRHRollingCache::advance()
  118. {
  119. CRHRollingCacheElem *e = (cache.ordinality()==max)?cache.dequeue():NULL; //cache full, remove head element
  120. if (!eos) {
  121. if (!e)
  122. e = new CRHRollingCacheElem();
  123. const void * nextrec = in->nextRow();//get row from CRHCRHDualCache::cOut, which gets from CRHCRHDualCache, which gets from input
  124. if (!nextrec)
  125. nextrec = in->nextRow();
  126. if (nextrec) {
  127. e->set(nextrec);
  128. cache.enqueue(e);
  129. #ifdef TRACEROLLING
  130. PrintCache();
  131. #endif
  132. return;
  133. }
  134. else
  135. eos = true;
  136. }
  137. delete e;
  138. cache.enqueue(NULL);
  139. #ifdef TRACEROLLING
  140. PrintCache();
  141. #endif
  142. }
  143. //=========================================================================================
  144. //CRHDualCache copied from THOR, and modified to get input from IInputBase instead
  145. //of IReadSeqVar and to manage rows as OwnedRoxieRow types
  146. CRHDualCache::CRHDualCache()
  147. {
  148. strm1 = NULL;
  149. strm2 = NULL;
  150. }
  151. CRHDualCache::~CRHDualCache()
  152. {
  153. ::Release(strm1);
  154. ::Release(strm2);
  155. for (;;)
  156. {
  157. CRHRollingCacheElem *e = cache.dequeue();
  158. if (!e)
  159. break;
  160. delete e;
  161. }
  162. }
  163. void CRHDualCache::init(IRowStream * _in)
  164. {
  165. in = _in;
  166. cache.clear();
  167. eos = false;
  168. base = 0;
  169. posL = 0;
  170. posR = 0;
  171. strm1 = new cOut(this,posL);
  172. strm2 = new cOut(this,posR) ;
  173. }
  174. #ifdef TRACEROLLING
  175. void CRHDualCache::PrintCache()
  176. {
  177. for (unsigned i = 0;i<cache.ordinality();i++) {
  178. CRHRollingCacheElem *e = cache.item(i);
  179. if (i==0)
  180. {
  181. DBGLOG("DC=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-BASE:%d,posL=%d,posR=%d %s", base, posL,posR, eos?"EOS":"");
  182. }
  183. DBGLOG("%c%d: %s",(i==cache.ordinality()/2)?'>':' ',i,e?(const char *)e->row:"-----");
  184. if (i == cache.ordinality()-1)
  185. DBGLOG("DC=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-");
  186. }
  187. }
  188. #endif
  189. bool CRHDualCache::get(unsigned n, CRHRollingCacheElem *&out)
  190. {
  191. // take off any no longer needed
  192. CRHRollingCacheElem *e=NULL;
  193. while ((base<posL) && (base<posR)) {
  194. delete e;
  195. e = cache.dequeue();
  196. base++;
  197. }
  198. assertex(n>=base);
  199. while (!eos && (n-base>=cache.ordinality())) //element already in cache?
  200. {
  201. if (!e)
  202. e = new CRHRollingCacheElem;
  203. const void * nextrec = in->nextRow(); //get from activity
  204. if (!nextrec)
  205. nextrec = in->nextRow();
  206. if (!nextrec) {
  207. eos = true;
  208. break;
  209. }
  210. e->set(nextrec);
  211. cache.enqueue(e);
  212. e = NULL;
  213. #ifdef TRACEROLLING
  214. PrintCache();
  215. #endif
  216. }
  217. delete e;
  218. if (n-base>=cache.ordinality())
  219. return false;
  220. out = cache.item(n-base);
  221. return true;
  222. }
  223. CRHDualCache::cOut::cOut(CRHDualCache *_parent, unsigned &_pos)
  224. : pos(_pos)
  225. {
  226. parent = _parent;
  227. stopped = false;
  228. }
  229. const void * CRHDualCache::cOut::nextRow()
  230. {
  231. CRHRollingCacheElem *e;
  232. if (stopped || !parent->get(pos,e))
  233. return NULL; //no more data
  234. LinkRoxieRow(e->row);
  235. pos++;
  236. return e->row;
  237. }
  238. void CRHDualCache::cOut::stop()
  239. {
  240. pos = (unsigned)-1;
  241. stopped = true;
  242. }
  243. //=========================================================================================
  244. IRHLimitedCompareHelper *createRHLimitedCompareHelper()
  245. {
  246. return new CRHLimitedCompareHelper();
  247. }
  248. //CRHLimitedCompareHelper
  249. void CRHLimitedCompareHelper::init( unsigned _atmost,
  250. IRowStream *_in,
  251. ICompare * _cmp,
  252. ICompare * _limitedcmp )
  253. {
  254. atmost = _atmost;
  255. cache.setown(new CRHRollingCache());
  256. cache->init(_in,(atmost+1)*2);
  257. cmp = _cmp;
  258. limitedcmp = _limitedcmp;
  259. }
  260. bool CRHLimitedCompareHelper::getGroup(OwnedRowArray &group, const void *left)
  261. {
  262. // this could be improved!
  263. // first move 'mid' forwards until mid>=left
  264. int low = 0;
  265. for (;;)
  266. {
  267. CRHRollingCacheElem * r = cache->mid(0);
  268. if (!r)
  269. break; // hit eos
  270. int c = cmp->docompare(left,r->row);
  271. if (c == 0)
  272. {
  273. r->cmp = limitedcmp->docompare(left,r->row);
  274. if (r->cmp <= 0)
  275. break;
  276. }
  277. else if (c < 0)
  278. {
  279. r->cmp = -1;
  280. break;
  281. }
  282. else
  283. r->cmp = 1;
  284. cache->advance();
  285. if (cache->mid(low-1)) // only if haven't hit start
  286. low--;
  287. }
  288. // now scan back (note low should be filled even at eos)
  289. for (;;)
  290. {
  291. CRHRollingCacheElem * pr = cache->mid(low-1);
  292. if (!pr)
  293. break; // hit start
  294. int c = cmp->docompare(left,pr->row);
  295. if (c == 0)
  296. {
  297. pr->cmp = limitedcmp->docompare(left,pr->row);
  298. if (pr->cmp==1)
  299. break;
  300. }
  301. else
  302. {
  303. pr->cmp = 1;
  304. break;
  305. }
  306. low--;
  307. }
  308. int high = 0;
  309. if (cache->mid(0)) // check haven't already hit end
  310. {
  311. // now scan fwd
  312. for (;;)
  313. {
  314. high++;
  315. CRHRollingCacheElem * nr = cache->mid(high);
  316. if (!nr)
  317. break;
  318. int c = cmp->docompare(left,nr->row);
  319. if (c==0)
  320. {
  321. nr->cmp = limitedcmp->docompare(left,nr->row);
  322. if (nr->cmp==-1)
  323. break;
  324. }
  325. else
  326. {
  327. nr->cmp = -1;
  328. break;
  329. }
  330. }
  331. }
  332. while (high-low>(int)atmost)
  333. {
  334. int vl = iabs(cache->mid(low)->cmp);
  335. int vh = iabs(cache->mid(high-1)->cmp);
  336. int v;
  337. if (vl==0)
  338. {
  339. if (vh==0) // both ends equal
  340. return false;
  341. v = vh;
  342. }
  343. else if (vh==0)
  344. v = vl;
  345. else
  346. v = imin(vl,vh);
  347. // remove worst match from either end
  348. while ((low<high)&&(iabs(cache->mid(low)->cmp)==v))
  349. low++;
  350. while ((low<high)&&(iabs(cache->mid(high-1)->cmp)==v))
  351. high--;
  352. if (low>=high)
  353. return true; // couldn't make group;
  354. }
  355. for (int i=low;i<high;i++)
  356. {
  357. CRHRollingCacheElem *r = cache->mid(i);
  358. LinkRoxieRow(r->row);
  359. group.append(r->row);
  360. }
  361. return group.ordinality()>0;
  362. }
  363. //=========================================================================================
  364. // default implementations - can be overridden for efficiency...
  365. bool IEngineRowStream::nextGroup(ConstPointerArray & group)
  366. {
  367. // MORE - this should be replaced with a version that reads to a builder
  368. const void * next;
  369. while ((next = nextRow()) != NULL)
  370. group.append(next);
  371. if (group.ordinality())
  372. return true;
  373. return false;
  374. }
  375. void IEngineRowStream::readAll(RtlLinkedDatasetBuilder &builder)
  376. {
  377. for (;;)
  378. {
  379. const void *nextrec = nextRow();
  380. if (!nextrec)
  381. {
  382. nextrec = nextRow();
  383. if (!nextrec)
  384. break;
  385. builder.appendEOG();
  386. }
  387. builder.appendOwn(nextrec);
  388. }
  389. }
  390. //=========================================================================================
  391. // Ability to read an input stream and group and/or sort it on-the-fly
  392. using roxiemem::OwnedConstRoxieRow;
  393. class InputReaderBase : public CInterfaceOf<IGroupedInput>
  394. {
  395. protected:
  396. IEngineRowStream *input;
  397. public:
  398. InputReaderBase(IEngineRowStream *_input)
  399. : input(_input)
  400. {
  401. }
  402. virtual void stop()
  403. {
  404. input->stop();
  405. }
  406. virtual void resetEOF()
  407. {
  408. input->resetEOF();
  409. }
  410. };
  411. class GroupedInputReader : public InputReaderBase
  412. {
  413. protected:
  414. bool firstRead;
  415. bool eof;
  416. bool endGroupPending;
  417. OwnedConstRoxieRow next;
  418. const ICompare *compare;
  419. public:
  420. GroupedInputReader(IEngineRowStream *_input, const ICompare *_compare)
  421. : InputReaderBase(_input), compare(_compare)
  422. {
  423. firstRead = false;
  424. eof = false;
  425. endGroupPending = false;
  426. }
  427. virtual const void *nextRow()
  428. {
  429. if (!firstRead)
  430. {
  431. firstRead = true;
  432. next.setown(input->nextRow());
  433. }
  434. if (eof || endGroupPending)
  435. {
  436. endGroupPending = false;
  437. return NULL;
  438. }
  439. OwnedConstRoxieRow prev(next.getClear());
  440. next.setown(input->ungroupedNextRow()); // skip incoming grouping if present
  441. if (next)
  442. {
  443. dbgassertex(prev); // If this fails, you have an initial empty group. That is not legal.
  444. if (compare && compare->docompare(prev, next) != 0)
  445. endGroupPending = true;
  446. }
  447. else
  448. eof = true;
  449. return prev.getClear();
  450. }
  451. };
  452. class DegroupedInputReader : public InputReaderBase
  453. {
  454. public:
  455. DegroupedInputReader(IEngineRowStream *_input) : InputReaderBase(_input)
  456. {
  457. }
  458. virtual const void *nextRow()
  459. {
  460. return input->ungroupedNextRow();
  461. }
  462. };
  463. class SortedInputReader : public InputReaderBase
  464. {
  465. protected:
  466. DegroupedInputReader degroupedInput;
  467. Owned<ISortAlgorithm> sorter;
  468. bool firstRead;
  469. public:
  470. SortedInputReader(IEngineRowStream *_input, ISortAlgorithm *_sorter)
  471. : InputReaderBase(_input), degroupedInput(_input), sorter(_sorter), firstRead(false)
  472. {
  473. sorter->reset();
  474. }
  475. ~SortedInputReader()
  476. {
  477. sorter->reset();
  478. }
  479. virtual const void *nextRow()
  480. {
  481. if (!firstRead)
  482. {
  483. firstRead = true;
  484. sorter->prepare(&degroupedInput);
  485. }
  486. return sorter->next();
  487. }
  488. };
  489. class SortedGroupedInputReader : public SortedInputReader
  490. {
  491. protected:
  492. bool eof;
  493. bool endGroupPending;
  494. OwnedConstRoxieRow next;
  495. const ICompare *compare;
  496. public:
  497. SortedGroupedInputReader(IEngineRowStream *_input, const ICompare *_compare, ISortAlgorithm *_sorter)
  498. : SortedInputReader(_input, _sorter), compare(_compare), eof(false), endGroupPending(false)
  499. {
  500. }
  501. virtual const void *nextRow()
  502. {
  503. if (!firstRead)
  504. {
  505. firstRead = true;
  506. sorter->prepare(&degroupedInput);
  507. next.setown(sorter->next());
  508. }
  509. if (eof || endGroupPending)
  510. {
  511. endGroupPending = false;
  512. return NULL;
  513. }
  514. OwnedConstRoxieRow prev(next.getClear());
  515. next.setown(sorter->next());
  516. if (next)
  517. {
  518. dbgassertex(prev); // If this fails, you have an initial empty group. That is not legal.
  519. if (compare->docompare(prev, next) != 0) // MORE - could assert >=0, as input is supposed to be sorted
  520. endGroupPending = true;
  521. }
  522. else
  523. eof = true;
  524. return prev.getClear();
  525. }
  526. };
  527. extern IGroupedInput *createGroupedInputReader(IEngineRowStream *_input, const ICompare *_groupCompare)
  528. {
  529. dbgassertex(_input && _groupCompare);
  530. return new GroupedInputReader(_input, _groupCompare);
  531. }
  532. extern IGroupedInput *createDegroupedInputReader(IEngineRowStream *_input)
  533. {
  534. dbgassertex(_input);
  535. return new DegroupedInputReader(_input);
  536. }
  537. extern IGroupedInput *createSortedInputReader(IEngineRowStream *_input, ISortAlgorithm *_sorter)
  538. {
  539. dbgassertex(_input && _sorter);
  540. return new SortedInputReader(_input, _sorter);
  541. }
  542. extern IGroupedInput *createSortedGroupedInputReader(IEngineRowStream *_input, const ICompare *_groupCompare, ISortAlgorithm *_sorter)
  543. {
  544. dbgassertex(_input && _groupCompare && _sorter);
  545. return new SortedGroupedInputReader(_input, _groupCompare, _sorter);
  546. }
  547. //=========================================================================================
  548. class CSortAlgorithm : implements CInterfaceOf<ISortAlgorithm>
  549. {
  550. public:
  551. CSortAlgorithm() { elapsedCycles = 0; }
  552. virtual void beforeDispose() override
  553. {
  554. reset();
  555. }
  556. virtual void getSortedGroup(ConstPointerArray & result)
  557. {
  558. for (;;)
  559. {
  560. const void * row = next();
  561. if (!row)
  562. return;
  563. result.append(row);
  564. }
  565. }
  566. virtual cycle_t getElapsedCycles(bool reset)
  567. {
  568. cycle_t ret = elapsedCycles;
  569. if (reset)
  570. elapsedCycles = 0;
  571. return ret;
  572. }
  573. protected:
  574. cycle_t elapsedCycles;
  575. };
  576. class CInplaceSortAlgorithm : public CSortAlgorithm
  577. {
  578. protected:
  579. unsigned curIndex;
  580. ConstPointerArray sorted;
  581. ICompare *compare;
  582. public:
  583. CInplaceSortAlgorithm(ICompare *_compare) : compare(_compare)
  584. {
  585. curIndex = 0;
  586. }
  587. virtual const void *next()
  588. {
  589. if (sorted.isItem(curIndex))
  590. return sorted.item(curIndex++);
  591. return NULL;
  592. }
  593. virtual void reset()
  594. {
  595. roxiemem::ReleaseRoxieRowRange(sorted.getArray(), curIndex, sorted.ordinality());
  596. curIndex = 0;
  597. sorted.kill();
  598. }
  599. virtual void getSortedGroup(ConstPointerArray & result)
  600. {
  601. sorted.swapWith(result);
  602. curIndex = 0;
  603. }
  604. };
  605. class CQuickSortAlgorithm : public CInplaceSortAlgorithm
  606. {
  607. public:
  608. CQuickSortAlgorithm(ICompare *_compare) : CInplaceSortAlgorithm(_compare) {}
  609. virtual void prepare(IEngineRowStream *input)
  610. {
  611. curIndex = 0;
  612. if (input->nextGroup(sorted))
  613. {
  614. cycle_t startCycles = get_cycles_now();
  615. qsortvec(const_cast<void * *>(sorted.getArray()), sorted.ordinality(), *compare);
  616. elapsedCycles += (get_cycles_now() - startCycles);
  617. }
  618. }
  619. };
  620. class CParallelQuickSortAlgorithm : public CInplaceSortAlgorithm
  621. {
  622. public:
  623. CParallelQuickSortAlgorithm(ICompare *_compare) : CInplaceSortAlgorithm(_compare) {}
  624. virtual void prepare(IEngineRowStream *input)
  625. {
  626. curIndex = 0;
  627. if (input->nextGroup(sorted))
  628. {
  629. cycle_t startCycles = get_cycles_now();
  630. parqsortvec(const_cast<void * *>(sorted.getArray()), sorted.ordinality(), *compare);
  631. elapsedCycles += (get_cycles_now() - startCycles);
  632. }
  633. }
  634. };
  635. class CTbbQuickSortAlgorithm : public CInplaceSortAlgorithm
  636. {
  637. public:
  638. CTbbQuickSortAlgorithm(ICompare *_compare) : CInplaceSortAlgorithm(_compare) {}
  639. virtual void prepare(IEngineRowStream *input)
  640. {
  641. curIndex = 0;
  642. if (input->nextGroup(sorted))
  643. {
  644. cycle_t startCycles = get_cycles_now();
  645. tbbqsortvec(const_cast<void * *>(sorted.getArray()), sorted.ordinality(), *compare);
  646. elapsedCycles += (get_cycles_now() - startCycles);
  647. }
  648. }
  649. };
  650. class CStableInplaceSortAlgorithm : public CInplaceSortAlgorithm
  651. {
  652. public:
  653. CStableInplaceSortAlgorithm(ICompare *_compare) : CInplaceSortAlgorithm(_compare) {}
  654. virtual void sortRows(void * * rows, size_t numRows, void * * temp) = 0;
  655. virtual void prepare(IEngineRowStream *input)
  656. {
  657. curIndex = 0;
  658. if (input->nextGroup(sorted))
  659. {
  660. unsigned numRows = sorted.ordinality();
  661. void **rows = const_cast<void * *>(sorted.getArray());
  662. MemoryAttr tempAttr(numRows*sizeof(void **)); // Temp storage for stable sort. This should probably be allocated from roxiemem
  663. void **temp = (void **) tempAttr.bufferBase();
  664. cycle_t startCycles = get_cycles_now();
  665. sortRows(rows, numRows, temp);
  666. elapsedCycles += (get_cycles_now() - startCycles);
  667. }
  668. }
  669. };
  670. class CStableQuickSortAlgorithm : public CStableInplaceSortAlgorithm
  671. {
  672. public:
  673. CStableQuickSortAlgorithm(ICompare *_compare) : CStableInplaceSortAlgorithm(_compare) {}
  674. virtual void sortRows(void * * rows, size_t numRows, void * * temp)
  675. {
  676. qsortvecstableinplace(rows, numRows, *compare, temp);
  677. }
  678. };
  679. class CParallelStableQuickSortAlgorithm : public CStableInplaceSortAlgorithm
  680. {
  681. public:
  682. CParallelStableQuickSortAlgorithm(ICompare *_compare) : CStableInplaceSortAlgorithm(_compare) {}
  683. virtual void sortRows(void * * rows, size_t numRows, void * * temp)
  684. {
  685. parqsortvecstableinplace(rows, numRows, *compare, temp);
  686. }
  687. };
  688. class CMergeSortAlgorithm : public CStableInplaceSortAlgorithm
  689. {
  690. public:
  691. CMergeSortAlgorithm(ICompare *_compare) : CStableInplaceSortAlgorithm(_compare) {}
  692. virtual void sortRows(void * * rows, size_t numRows, void * * temp)
  693. {
  694. msortvecstableinplace(rows, numRows, *compare, temp);
  695. }
  696. };
  697. class CParallelMergeSortAlgorithm : public CStableInplaceSortAlgorithm
  698. {
  699. public:
  700. CParallelMergeSortAlgorithm(ICompare *_compare) : CStableInplaceSortAlgorithm(_compare) {}
  701. virtual void sortRows(void * * rows, size_t numRows, void * * temp)
  702. {
  703. parmsortvecstableinplace(rows, numRows, *compare, temp);
  704. }
  705. };
  706. class CTbbStableQuickSortAlgorithm : public CStableInplaceSortAlgorithm
  707. {
  708. public:
  709. CTbbStableQuickSortAlgorithm(ICompare *_compare) : CStableInplaceSortAlgorithm(_compare) {}
  710. virtual void sortRows(void * * rows, size_t numRows, void * * temp)
  711. {
  712. tbbqsortstable(rows, numRows, *compare, temp);
  713. }
  714. };
  715. class CHeapSortAlgorithm : public CSortAlgorithm
  716. {
  717. unsigned curIndex;
  718. ConstPointerArray sorted;
  719. bool inputAlreadySorted;
  720. IntArray sequences;
  721. bool eof;
  722. ICompare *compare;
  723. #ifdef _CHECK_HEAPSORT
  724. void checkHeap() const
  725. {
  726. unsigned n = sorted.ordinality();
  727. if (n)
  728. {
  729. ICompare *_compare = compare;
  730. void **s = sorted.getArray();
  731. int *sq = sequences.getArray();
  732. unsigned p;
  733. #if 0
  734. CTXLOG("------------------------%d entries-----------------", n);
  735. for (p = 0; p < n; p++)
  736. {
  737. CTXLOG("HEAP %d: %d %.10s", p, sq[p], s[p] ? s[p] : "..");
  738. }
  739. #endif
  740. for (p = 0; p < n; p++)
  741. {
  742. unsigned c = p*2+1;
  743. if (c<n)
  744. assertex(!s[c] || (docompare(p, c, _compare, s, sq) <= 0));
  745. c++;
  746. if (c<n)
  747. assertex(!s[c] || (docompare(p, c, _compare, s, sq) <= 0));
  748. }
  749. }
  750. }
  751. #else
  752. inline void checkHeap() const {}
  753. #endif
  754. const void *removeHeap()
  755. {
  756. unsigned n = sorted.ordinality();
  757. if (n)
  758. {
  759. const void *ret = sorted.item(0);
  760. if (n > 1 && ret)
  761. {
  762. ICompare *_compare = compare;
  763. const void **s = sorted.getArray();
  764. int *sq = sequences.getArray();
  765. unsigned v = 0; // vacancy
  766. for (;;)
  767. {
  768. unsigned c = 2*v + 1;
  769. if (c < n)
  770. {
  771. unsigned f = c; // favourite to fill it
  772. c++;
  773. if (c < n && s[c] && (!s[f] || (docompare(f, c, _compare, s, sq) > 0))) // is the smaller of the children
  774. f = c;
  775. sq[v] = sq[f];
  776. if ((s[v] = s[f]) != NULL)
  777. v = f;
  778. else
  779. break;
  780. }
  781. else
  782. {
  783. s[v] = NULL;
  784. break;
  785. }
  786. }
  787. }
  788. checkHeap();
  789. return ret;
  790. }
  791. else
  792. return NULL;
  793. }
  794. static inline int docompare(unsigned l, unsigned r, ICompare *_compare, const void **s, int *sq)
  795. {
  796. int rc = _compare->docompare(s[l], s[r]);
  797. if (!rc)
  798. rc = sq[l] - sq[r];
  799. return rc;
  800. }
  801. void insertHeap(const void *next)
  802. {
  803. // Upside-down heap sort
  804. // Maintain a heap where every parent is lower than each of its children
  805. // Root (at node 0) is lowest record seen, nodes 2n+1, 2n+2 are the children
  806. // To insert a row, add it at end then keep swapping with parent as long as parent is greater
  807. // To remove a row, take row 0, then recreate heap by replacing it with smaller of two children and so on down the tree
  808. // Nice features:
  809. // 1. Deterministic
  810. // 2. Sort time can be overlapped with upstream/downstream processes - there is no delay between receiving last record from input and deliveriing first to output
  811. // 3. Already sorted case can be spotted at zero cost while reading.
  812. // 4. If you don't read all the results, you don't have to complete the sort
  813. // BUT it is NOT stable, so we have to use a parallel array of sequence numbers
  814. unsigned n = sorted.ordinality();
  815. sorted.append(next);
  816. sequences.append(n);
  817. if (!n)
  818. return;
  819. ICompare *_compare = compare;
  820. const void **s = sorted.getArray();
  821. if (inputAlreadySorted)
  822. {
  823. if (_compare->docompare(next, s[n-1]) >= 0)
  824. return;
  825. else
  826. {
  827. // MORE - could delay creating sequences until now...
  828. inputAlreadySorted = false;
  829. }
  830. }
  831. int *sq = sequences.getArray();
  832. unsigned q = n;
  833. while (n)
  834. {
  835. unsigned parent = (n-1) / 2;
  836. const void *p = s[parent];
  837. if (_compare->docompare(p, next) <= 0)
  838. break;
  839. s[n] = p;
  840. sq[n] = sq[parent];
  841. s[parent] = next;
  842. sq[parent] = q;
  843. n = parent;
  844. }
  845. }
  846. public:
  847. CHeapSortAlgorithm(ICompare *_compare) : compare(_compare)
  848. {
  849. inputAlreadySorted = true;
  850. curIndex = 0;
  851. eof = false;
  852. }
  853. virtual void reset()
  854. {
  855. eof = false;
  856. if (inputAlreadySorted)
  857. {
  858. roxiemem::ReleaseRoxieRowRange(sorted.getArray(), curIndex, sorted.ordinality());
  859. sorted.kill();
  860. }
  861. else
  862. {
  863. roxiemem::ReleaseRoxieRows(sorted);
  864. }
  865. curIndex = 0;
  866. inputAlreadySorted = true;
  867. sequences.kill();
  868. }
  869. virtual void prepare(IEngineRowStream *input)
  870. {
  871. inputAlreadySorted = true;
  872. curIndex = 0;
  873. eof = false;
  874. assertex(sorted.ordinality()==0);
  875. const void *next = input->nextRow();
  876. if (!next)
  877. {
  878. eof = true;
  879. return;
  880. }
  881. for (;;)
  882. {
  883. insertHeap(next);
  884. next = input->nextRow();
  885. if (!next)
  886. break;
  887. }
  888. checkHeap();
  889. }
  890. virtual const void * next()
  891. {
  892. if (inputAlreadySorted)
  893. {
  894. if (sorted.isItem(curIndex))
  895. {
  896. return sorted.item(curIndex++);
  897. }
  898. else
  899. return NULL;
  900. }
  901. else
  902. return removeHeap();
  903. }
  904. };
  905. class CSpillingSortAlgorithm : public CSortAlgorithm, implements roxiemem::IBufferedRowCallback
  906. {
  907. enum {
  908. InitialSortElements = 0,
  909. //The number of rows that can be added without entering a critical section, and therefore also the number
  910. //of rows that might not get freed when memory gets tight.
  911. CommitStep=32
  912. };
  913. roxiemem::DynamicRoxieOutputRowArray rowsToSort;
  914. roxiemem::RoxieSimpleInputRowArray sorted;
  915. ICompare *compare;
  916. roxiemem::IRowManager &rowManager;
  917. Owned<IDiskMerger> diskMerger;
  918. Owned<IRowStream> diskReader;
  919. IOutputMetaData *rowMeta;
  920. StringAttr tempDirectory;
  921. ICodeContext *ctx;
  922. unsigned activityId;
  923. bool stable;
  924. public:
  925. CSpillingSortAlgorithm(ICompare *_compare, roxiemem::IRowManager &_rowManager, IOutputMetaData * _rowMeta, ICodeContext *_ctx, const char *_tempDirectory, unsigned _activityId, bool _stable)
  926. : rowsToSort(&_rowManager, InitialSortElements, CommitStep, _activityId),
  927. rowManager(_rowManager), compare(_compare), rowMeta(_rowMeta), ctx(_ctx), tempDirectory(_tempDirectory), activityId(_activityId), stable(_stable)
  928. {
  929. rowManager.addRowBuffer(this);
  930. }
  931. ~CSpillingSortAlgorithm()
  932. {
  933. rowManager.removeRowBuffer(this);
  934. diskReader.clear();
  935. }
  936. virtual void sortRows(void * * rows, size_t numRows, ICompare & compare, void * * stableTemp) = 0;
  937. virtual void prepare(IEngineRowStream *input)
  938. {
  939. for (;;)
  940. {
  941. const void * next = input->nextRow();
  942. if (!next)
  943. break;
  944. if (!rowsToSort.append(next))
  945. {
  946. {
  947. roxiemem::RoxieOutputRowArrayLock block(rowsToSort);
  948. //We should have been called back to free any committed rows, but occasionally it may not (e.g., if
  949. //the problem is global memory is exhausted) - in which case force a spill here (but add any pending
  950. //rows first).
  951. if (rowsToSort.numCommitted() != 0)
  952. {
  953. rowsToSort.flush();
  954. spillRows();
  955. }
  956. //Ensure new rows are written to the head of the array. It needs to be a separate call because
  957. //spillRows() cannot shift active row pointer since it can be called from any thread
  958. rowsToSort.flush();
  959. }
  960. if (!rowsToSort.append(next))
  961. {
  962. ReleaseRoxieRow(next);
  963. throw MakeStringException(ROXIEMM_MEMORY_LIMIT_EXCEEDED, "Insufficient memory to append sort row");
  964. }
  965. }
  966. }
  967. rowsToSort.flush();
  968. roxiemem::RoxieOutputRowArrayLock block(rowsToSort);
  969. if (diskMerger)
  970. {
  971. spillRows();
  972. rowsToSort.kill();
  973. diskReader.setown(diskMerger->merge(compare));
  974. }
  975. else
  976. {
  977. sortCommitted();
  978. sorted.transferFrom(rowsToSort);
  979. }
  980. }
  981. virtual const void *next()
  982. {
  983. if(diskReader)
  984. return diskReader->nextRow();
  985. return sorted.dequeue();
  986. }
  987. virtual void reset()
  988. {
  989. //MORE: This could transfer any row pointer from sorted back to rowsToSort. It would trade
  990. //fewer heap allocations with not freeing up the memory from large group sorts.
  991. rowsToSort.clearRows();
  992. sorted.kill();
  993. //Disk reader must be cleared before the merger - or the files may still be locked.
  994. diskReader.clear();
  995. diskMerger.clear();
  996. }
  997. //interface roxiemem::IBufferedRowCallback
  998. virtual unsigned getSpillCost() const
  999. {
  1000. //Spill global sorts before grouped sorts
  1001. if (rowMeta->isGrouped())
  1002. return 20;
  1003. return 10;
  1004. }
  1005. virtual unsigned getActivityId() const
  1006. {
  1007. return activityId;
  1008. }
  1009. virtual bool freeBufferedRows(bool critical)
  1010. {
  1011. roxiemem::RoxieOutputRowArrayLock block(rowsToSort);
  1012. return spillRows();
  1013. }
  1014. protected:
  1015. void sortCommitted()
  1016. {
  1017. unsigned numRows = rowsToSort.numCommitted();
  1018. if (numRows)
  1019. {
  1020. cycle_t startCycles = get_cycles_now();
  1021. void ** rows = const_cast<void * *>(rowsToSort.getBlock(numRows));
  1022. //MORE: Should this be parallel? Should that be dependent on whether it is grouped? Should be a hint.
  1023. if (stable)
  1024. {
  1025. MemoryAttr tempAttr(numRows*sizeof(void **)); // Temp storage for stable sort. This should probably be allocated from roxiemem
  1026. void **temp = (void **) tempAttr.bufferBase();
  1027. sortRows(rows, numRows, *compare, temp);
  1028. }
  1029. else
  1030. sortRows(rows, numRows, *compare, NULL);
  1031. elapsedCycles += (get_cycles_now() - startCycles);
  1032. }
  1033. }
  1034. bool spillRows()
  1035. {
  1036. unsigned numRows = rowsToSort.numCommitted();
  1037. if (numRows == 0)
  1038. return false;
  1039. sortCommitted();
  1040. const void * * rows = rowsToSort.getBlock(numRows);
  1041. Owned<IRowWriter> out = queryMerger()->createWriteBlock();
  1042. for (unsigned i= 0; i < numRows; i++)
  1043. {
  1044. out->putRow(rows[i]);
  1045. }
  1046. rowsToSort.noteSpilled(numRows);
  1047. return true;
  1048. }
  1049. IDiskMerger * queryMerger()
  1050. {
  1051. if (!diskMerger)
  1052. {
  1053. unsigned __int64 seq = (memsize_t)this ^ get_cycles_now();
  1054. StringBuffer spillBasename;
  1055. spillBasename.append(tempDirectory).append(PATHSEPCHAR).appendf("spill_sort_%" I64F "u", seq);
  1056. Owned<IRowLinkCounter> linker = new RoxieRowLinkCounter();
  1057. unsigned heapFlags = 0;
  1058. Owned<IRowInterfaces> rowInterfaces = createRowInterfaces(rowMeta, activityId, heapFlags, ctx);
  1059. diskMerger.setown(createDiskMerger(rowInterfaces, linker, spillBasename));
  1060. }
  1061. return diskMerger;
  1062. }
  1063. };
  1064. class CSpillingQuickSortAlgorithm : public CSpillingSortAlgorithm
  1065. {
  1066. public:
  1067. CSpillingQuickSortAlgorithm(ICompare *_compare, roxiemem::IRowManager &_rowManager, IOutputMetaData * _rowMeta, ICodeContext *_ctx, const char *_tempDirectory, unsigned _activityId, bool _stable)
  1068. : CSpillingSortAlgorithm(_compare, _rowManager, _rowMeta, _ctx, _tempDirectory, _activityId, _stable)
  1069. {
  1070. }
  1071. virtual void sortRows(void * * rows, size_t numRows, ICompare & compare, void * * stableTemp)
  1072. {
  1073. if (stableTemp)
  1074. qsortvecstableinplace(rows, numRows, compare, stableTemp);
  1075. else
  1076. qsortvec(rows, numRows, compare);
  1077. }
  1078. };
  1079. class CSpillingMergeSortAlgorithm : public CSpillingSortAlgorithm
  1080. {
  1081. public:
  1082. CSpillingMergeSortAlgorithm(ICompare *_compare, roxiemem::IRowManager &_rowManager, IOutputMetaData * _rowMeta, ICodeContext *_ctx, const char *_tempDirectory, unsigned _activityId, bool _parallel)
  1083. : CSpillingSortAlgorithm(_compare, _rowManager, _rowMeta, _ctx, _tempDirectory, _activityId, true)
  1084. {
  1085. parallel = _parallel;
  1086. }
  1087. virtual void sortRows(void * * rows, size_t numRows, ICompare & compare, void * * stableTemp)
  1088. {
  1089. if (parallel)
  1090. parmsortvecstableinplace(rows, numRows, compare, stableTemp);
  1091. else
  1092. msortvecstableinplace(rows, numRows, compare, stableTemp);
  1093. }
  1094. protected:
  1095. bool parallel;
  1096. };
  1097. extern ISortAlgorithm *createQuickSortAlgorithm(ICompare *_compare)
  1098. {
  1099. return new CQuickSortAlgorithm(_compare);
  1100. }
  1101. extern ISortAlgorithm *createParallelQuickSortAlgorithm(ICompare *_compare)
  1102. {
  1103. return new CParallelQuickSortAlgorithm(_compare);
  1104. }
  1105. extern ISortAlgorithm *createStableQuickSortAlgorithm(ICompare *_compare)
  1106. {
  1107. return new CStableQuickSortAlgorithm(_compare);
  1108. }
  1109. extern ISortAlgorithm *createParallelStableQuickSortAlgorithm(ICompare *_compare)
  1110. {
  1111. return new CParallelStableQuickSortAlgorithm(_compare);
  1112. }
  1113. extern ISortAlgorithm *createTbbQuickSortAlgorithm(ICompare *_compare)
  1114. {
  1115. return new CTbbQuickSortAlgorithm(_compare);
  1116. }
  1117. extern ISortAlgorithm *createTbbStableQuickSortAlgorithm(ICompare *_compare)
  1118. {
  1119. return new CTbbStableQuickSortAlgorithm(_compare);
  1120. }
  1121. extern ISortAlgorithm *createHeapSortAlgorithm(ICompare *_compare)
  1122. {
  1123. return new CHeapSortAlgorithm(_compare);
  1124. }
  1125. extern ISortAlgorithm *createMergeSortAlgorithm(ICompare *_compare)
  1126. {
  1127. return new CMergeSortAlgorithm(_compare);
  1128. }
  1129. extern ISortAlgorithm *createParallelMergeSortAlgorithm(ICompare *_compare)
  1130. {
  1131. return new CParallelMergeSortAlgorithm(_compare);
  1132. }
  1133. extern ISortAlgorithm *createSpillingQuickSortAlgorithm(ICompare *_compare, roxiemem::IRowManager &_rowManager, IOutputMetaData * _rowMeta, ICodeContext *_ctx, const char *_tempDirectory, unsigned _activityId, bool _stable)
  1134. {
  1135. return new CSpillingQuickSortAlgorithm(_compare, _rowManager, _rowMeta, _ctx, _tempDirectory, _activityId, _stable);
  1136. }
  1137. extern ISortAlgorithm *createSortAlgorithm(RoxieSortAlgorithm _algorithm, ICompare *_compare, roxiemem::IRowManager &_rowManager, IOutputMetaData * _rowMeta, ICodeContext *_ctx, const char *_tempDirectory, unsigned _activityId)
  1138. {
  1139. switch (_algorithm)
  1140. {
  1141. case heapSortAlgorithm:
  1142. return createHeapSortAlgorithm(_compare);
  1143. case quickSortAlgorithm:
  1144. return createQuickSortAlgorithm(_compare);
  1145. case stableQuickSortAlgorithm:
  1146. return createStableQuickSortAlgorithm(_compare);
  1147. case parallelQuickSortAlgorithm:
  1148. return createParallelQuickSortAlgorithm(_compare);
  1149. case parallelStableQuickSortAlgorithm:
  1150. return createParallelStableQuickSortAlgorithm(_compare);
  1151. case spillingQuickSortAlgorithm:
  1152. case stableSpillingQuickSortAlgorithm:
  1153. return createSpillingQuickSortAlgorithm(_compare, _rowManager, _rowMeta, _ctx, _tempDirectory, _activityId, _algorithm==stableSpillingQuickSortAlgorithm);
  1154. case mergeSortAlgorithm:
  1155. return new CMergeSortAlgorithm(_compare);
  1156. case parallelMergeSortAlgorithm:
  1157. return new CParallelMergeSortAlgorithm(_compare);
  1158. case spillingMergeSortAlgorithm:
  1159. return new CSpillingMergeSortAlgorithm(_compare, _rowManager, _rowMeta, _ctx, _tempDirectory, _activityId, false);
  1160. case spillingParallelMergeSortAlgorithm:
  1161. return new CSpillingMergeSortAlgorithm(_compare, _rowManager, _rowMeta, _ctx, _tempDirectory, _activityId, true);
  1162. case tbbQuickSortAlgorithm:
  1163. return createTbbQuickSortAlgorithm(_compare);
  1164. case tbbStableQuickSortAlgorithm:
  1165. return createTbbStableQuickSortAlgorithm(_compare);
  1166. default:
  1167. break;
  1168. }
  1169. throwUnexpected();
  1170. }
  1171. //===================================================
  1172. CSafeSocket::CSafeSocket(ISocket *_sock)
  1173. {
  1174. httpMode = false;
  1175. sent = 0;
  1176. heartbeat = false;
  1177. sock.setown(_sock);
  1178. }
  1179. CSafeSocket::~CSafeSocket()
  1180. {
  1181. sock.clear();
  1182. ForEachItemIn(idx, queued)
  1183. {
  1184. free(queued.item(idx));
  1185. }
  1186. queued.kill();
  1187. lengths.kill();
  1188. }
  1189. unsigned CSafeSocket::bytesOut() const
  1190. {
  1191. return sent;
  1192. }
  1193. bool CSafeSocket::checkConnection() const
  1194. {
  1195. if (sock)
  1196. return sock->check_connection();
  1197. else
  1198. return false;
  1199. }
  1200. size32_t CSafeSocket::write(const void *buf, size32_t size, bool takeOwnership)
  1201. {
  1202. CriticalBlock c(crit); // NOTE: anyone needing to write multiple times without interleave should have already locked this. We lock again for the simple cases.
  1203. OwnedMalloc<void> ownedBuffer;
  1204. if (takeOwnership)
  1205. ownedBuffer.setown((void *) buf);
  1206. if (!size)
  1207. return 0;
  1208. try
  1209. {
  1210. if (httpMode)
  1211. {
  1212. if (!takeOwnership)
  1213. {
  1214. ownedBuffer.setown(malloc(size));
  1215. if (!ownedBuffer)
  1216. throw MakeStringException(THORHELPER_INTERNAL_ERROR, "Out of memory in CSafeSocket::write (requesting %d bytes)", size);
  1217. memcpy(ownedBuffer, buf, size);
  1218. }
  1219. queued.append(ownedBuffer.getClear());
  1220. lengths.append(size);
  1221. return size;
  1222. }
  1223. else
  1224. {
  1225. sent += size;
  1226. size32_t written = sock->write(buf, size);
  1227. return written;
  1228. }
  1229. }
  1230. catch(...)
  1231. {
  1232. heartbeat = false;
  1233. throw;
  1234. }
  1235. }
  1236. bool CSafeSocket::readBlock(MemoryBuffer &ret, unsigned timeout, unsigned maxBlockSize)
  1237. {
  1238. // MORE - this is still not good enough as we could get someone else's block if there are multiple input datasets
  1239. CriticalBlock c(crit);
  1240. try
  1241. {
  1242. unsigned bytesRead;
  1243. unsigned len;
  1244. try
  1245. {
  1246. sock->read(&len, sizeof (len), sizeof (len), bytesRead, timeout);
  1247. }
  1248. catch (IJSOCK_Exception *E)
  1249. {
  1250. if (E->errorCode()==JSOCKERR_graceful_close)
  1251. {
  1252. E->Release();
  1253. return false;
  1254. }
  1255. throw;
  1256. }
  1257. assertex(bytesRead == sizeof(len));
  1258. _WINREV(len);
  1259. if (len & 0x80000000)
  1260. len ^= 0x80000000;
  1261. if (len > maxBlockSize)
  1262. throw MakeStringException(THORHELPER_DATA_ERROR, "Maximum block size (%d bytes) exceeded (missing length prefix?)", maxBlockSize);
  1263. if (len)
  1264. {
  1265. unsigned bytesRead;
  1266. sock->read(ret.reserveTruncate(len), len, len, bytesRead, timeout);
  1267. }
  1268. return len != 0;
  1269. }
  1270. catch(...)
  1271. {
  1272. heartbeat = false;
  1273. throw;
  1274. }
  1275. }
  1276. int readHttpHeaderLine(IBufferedSocket *linereader, char *headerline, unsigned maxlen)
  1277. {
  1278. Owned<IMultiException> me = makeMultiException("roxie");
  1279. int bytesread = linereader->readline(headerline, maxlen, true, me);
  1280. if (me->ordinality())
  1281. throw me.getClear();
  1282. if(bytesread <= 0 || (unsigned)bytesread > maxlen)
  1283. throw MakeStringException(THORHELPER_DATA_ERROR, "HTTP-GET Bad Request");
  1284. return bytesread;
  1285. }
  1286. inline bool endOfParameters(const char *str)
  1287. {
  1288. return (*str==0 || *str=='#');
  1289. }
  1290. void parseHttpParameterString(IProperties *p, const char *str)
  1291. {
  1292. while (!endOfParameters(str))
  1293. {
  1294. StringBuffer s, prop, val;
  1295. while (!endOfParameters(str) && *str != '&' && *str != '=')
  1296. s.append(*str++);
  1297. appendDecodedURL(prop, s.trim());
  1298. if (endOfParameters(str) || *str == '&')
  1299. val.set("1");
  1300. else
  1301. {
  1302. s.clear();
  1303. str++;
  1304. while (!endOfParameters(str) && *str != '&')
  1305. s.append(*str++);
  1306. appendDecodedURL(val, s.trim());
  1307. }
  1308. if (prop.length())
  1309. p->setProp(prop, val);
  1310. if (!endOfParameters(str))
  1311. str++;
  1312. }
  1313. }
  1314. bool CSafeSocket::readBlock(StringBuffer &ret, unsigned timeout, HttpHelper *pHttpHelper, bool &continuationNeeded, bool &isStatus, unsigned maxBlockSize)
  1315. {
  1316. continuationNeeded = false;
  1317. isStatus = false;
  1318. CriticalBlock c(crit);
  1319. try
  1320. {
  1321. unsigned bytesRead;
  1322. unsigned len = 0;
  1323. try
  1324. {
  1325. sock->read(&len, sizeof (len), sizeof (len), bytesRead, timeout);
  1326. if (bytesRead==0) //graceful timeout
  1327. return false;
  1328. }
  1329. catch (IJSOCK_Exception *E)
  1330. {
  1331. if (E->errorCode()==JSOCKERR_graceful_close)
  1332. {
  1333. E->Release();
  1334. return false;
  1335. }
  1336. throw;
  1337. }
  1338. assertex(bytesRead == sizeof(len));
  1339. unsigned left = 0;
  1340. char *buf;
  1341. if (pHttpHelper)
  1342. {
  1343. if (strncmp((char *)&len, "POST", 4) == 0)
  1344. pHttpHelper->setHttpMethod(HttpMethod::POST);
  1345. else if (strncmp((char *)&len, "GET", 3) == 0)
  1346. pHttpHelper->setHttpMethod(HttpMethod::GET);
  1347. }
  1348. if (pHttpHelper && pHttpHelper->isHttp())
  1349. {
  1350. #define MAX_HTTP_HEADERSIZE 16000 //arbitrary per line limit, most web servers are lower, but REST queries can be complex..
  1351. char header[MAX_HTTP_HEADERSIZE + 1]; // allow room for \0
  1352. sock->read(header, 1, MAX_HTTP_HEADERSIZE, bytesRead, timeout);
  1353. header[bytesRead] = 0;
  1354. char *payload = strstr(header, "\r\n\r\n");
  1355. if (payload)
  1356. {
  1357. *payload = 0;
  1358. payload += 4;
  1359. pHttpHelper->parseHTTPRequestLine(header);
  1360. const char *headers = strstr(header, "\r\n");
  1361. if (headers)
  1362. pHttpHelper->parseRequestHeaders(headers+2);
  1363. if (pHttpHelper->isHttpGet())
  1364. {
  1365. pHttpHelper->checkTarget();
  1366. return true;
  1367. }
  1368. const char *val = pHttpHelper->queryRequestHeader("Expect");
  1369. if (val && streq(val, "100-continue"))
  1370. {
  1371. StringBuffer cont("HTTP/1.1 100 Continue\r\n\r\n"); //tell client to go ahead and send body
  1372. sock->write(cont, cont.length());
  1373. }
  1374. // determine payload length
  1375. val = pHttpHelper->queryRequestHeader("Content-Length");
  1376. if (val)
  1377. {
  1378. len = atoi(val);
  1379. buf = ret.reserveTruncate(len);
  1380. left = len - (bytesRead - (payload - header));
  1381. if (len > left)
  1382. memcpy(buf, payload, len - left);
  1383. }
  1384. else
  1385. left = len = 0;
  1386. }
  1387. else
  1388. left = len = 0;
  1389. if (!len)
  1390. throw MakeStringException(THORHELPER_DATA_ERROR, "Badly formed HTTP header");
  1391. }
  1392. else if (strnicmp((char *)&len, "STAT", 4) == 0)
  1393. isStatus = true;
  1394. else
  1395. {
  1396. _WINREV(len);
  1397. if (len & 0x80000000)
  1398. {
  1399. len ^= 0x80000000;
  1400. continuationNeeded = true;
  1401. }
  1402. if (len > maxBlockSize)
  1403. throw MakeStringException(THORHELPER_DATA_ERROR, "Maximum block size (%d bytes) exceeded (missing length prefix?)", maxBlockSize);
  1404. left = len;
  1405. if (len)
  1406. buf = ret.reserveTruncate(len);
  1407. }
  1408. if (left)
  1409. sock->read(buf + (len - left), left, left, bytesRead, timeout);
  1410. if (len && pHttpHelper)
  1411. {
  1412. if (pHttpHelper->getReqCompression()!=HttpCompression::NONE)
  1413. {
  1414. #ifdef _USE_ZLIB
  1415. StringBuffer decoded;
  1416. httpInflate((const byte*)ret.str(), len, decoded, pHttpHelper->getReqCompression()==HttpCompression::GZIP);
  1417. PROGLOG("%s Content decoded from %d bytes to %d bytes", pHttpHelper->queryRequestHeader("Content-Encoding"), len, decoded.length());
  1418. ret.swapWith(decoded);
  1419. #else
  1420. throw MakeStringException(THORHELPER_UNSUPPORTED_ENCODING, "Unsupported Content-Encoding (_USE_ZLIB is required): %s", pHttpHelper->queryRequestHeader("Content-Encoding"));
  1421. #endif
  1422. }
  1423. if (pHttpHelper->isFormPost())
  1424. pHttpHelper->checkSetFormPostContent(ret.str());
  1425. }
  1426. return len != 0;
  1427. }
  1428. catch (IException *E)
  1429. {
  1430. if (pHttpHelper)
  1431. checkSendHttpException(*pHttpHelper, E, NULL);
  1432. heartbeat = false;
  1433. throw;
  1434. }
  1435. catch (...)
  1436. {
  1437. heartbeat = false;
  1438. throw;
  1439. }
  1440. }
  1441. void CSafeSocket::setHttpMode(const char *queryName, bool arrayMode, HttpHelper &httphelper)
  1442. {
  1443. CriticalBlock c(crit); // Should not be needed
  1444. httpMode = true;
  1445. mlResponseFmt = httphelper.queryResponseMlFormat();
  1446. respCompression = httphelper.getRespCompression();
  1447. heartbeat = false;
  1448. //reset persistent http connection
  1449. contentHead.clear();
  1450. contentTail.clear();
  1451. ForEachItemIn(idx, queued)
  1452. free(queued.item(idx));
  1453. queued.kill();
  1454. lengths.kill();
  1455. if (mlResponseFmt==MarkupFmt_JSON)
  1456. {
  1457. contentHead.set("{");
  1458. contentTail.set("}");
  1459. }
  1460. else
  1461. {
  1462. StringAttrBuilder headText(contentHead), tailText(contentTail);
  1463. if (httphelper.getUseEnvelope())
  1464. headText.append(
  1465. "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
  1466. "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
  1467. "<soap:Body>");
  1468. if (arrayMode)
  1469. {
  1470. headText.append("<").append(queryName).append("ResponseArray>");
  1471. tailText.append("</").append(queryName).append("ResponseArray>");
  1472. }
  1473. if (httphelper.getUseEnvelope())
  1474. tailText.append("</soap:Body></soap:Envelope>");
  1475. }
  1476. }
  1477. void CSafeSocket::checkSendHttpException(HttpHelper &httphelper, IException *E, const char *queryName)
  1478. {
  1479. if (!httphelper.isHttp())
  1480. return;
  1481. if (httphelper.queryResponseMlFormat()==MarkupFmt_JSON)
  1482. sendJsonException(E, queryName);
  1483. else
  1484. sendSoapException(E, queryName);
  1485. }
  1486. void CSafeSocket::sendSoapException(IException *E, const char *queryName)
  1487. {
  1488. try
  1489. {
  1490. adaptiveRoot = false;
  1491. if (!queryName)
  1492. queryName = "Unknown"; // Exceptions when parsing query XML can leave queryName unset/unknowable....
  1493. StringBuffer response;
  1494. response.append("<").append(queryName).append("Response");
  1495. response.append(" xmlns=\"urn:hpccsystems:ecl:").appendLower(strlen(queryName), queryName).append("\">");
  1496. response.appendf("<Results><Result><Exception><Source>Roxie</Source><Code>%d</Code>", E->errorCode());
  1497. response.append("<Message>");
  1498. StringBuffer s;
  1499. E->errorMessage(s);
  1500. encodeXML(s.str(), response);
  1501. response.append("</Message></Exception></Result></Results>");
  1502. response.append("</").append(queryName).append("Response>");
  1503. write(response.str(), response.length());
  1504. }
  1505. catch(IException *EE)
  1506. {
  1507. StringBuffer error("While reporting exception: ");
  1508. EE->errorMessage(error);
  1509. DBGLOG("%s", error.str());
  1510. EE->Release();
  1511. }
  1512. #ifndef _DEBUG
  1513. catch(...) {}
  1514. #endif
  1515. }
  1516. void CSafeSocket::sendJsonException(IException *E, const char *queryName)
  1517. {
  1518. try
  1519. {
  1520. adaptiveRoot = false;
  1521. if (!queryName)
  1522. queryName = "Unknown"; // Exceptions when parsing query XML can leave queryName unset/unknowable....
  1523. StringBuffer response;
  1524. appendfJSONName(response, "%sResponse", queryName).append(" {");
  1525. appendJSONName(response, "Results").append(" {");
  1526. appendJSONName(response, "Exception").append(" [{");
  1527. appendJSONValue(response, "Source", "Roxie");
  1528. appendJSONValue(response, "Code", E->errorCode());
  1529. StringBuffer s;
  1530. appendJSONValue(response, "Message", E->errorMessage(s).str());
  1531. response.append("}]}}");
  1532. write(response.str(), response.length());
  1533. }
  1534. catch(IException *EE)
  1535. {
  1536. StringBuffer error("While reporting exception: ");
  1537. DBGLOG("%s", EE->errorMessage(error).str());
  1538. EE->Release();
  1539. }
  1540. #ifndef _DEBUG
  1541. catch(...) {}
  1542. #endif
  1543. }
  1544. void CSafeSocket::setHeartBeat()
  1545. {
  1546. CriticalBlock c(crit);
  1547. heartbeat = true;
  1548. }
  1549. bool CSafeSocket::sendHeartBeat(const IContextLogger &logctx)
  1550. {
  1551. if (heartbeat)
  1552. {
  1553. StringBuffer s;
  1554. bool rval = false;
  1555. unsigned replyLen = 5;
  1556. unsigned rev = replyLen | 0x80000000; // make it a blocked msg
  1557. _WINREV(rev);
  1558. s.append(sizeof(rev), (char *) &rev);
  1559. s.append('H');
  1560. rev = (unsigned) time(NULL);
  1561. _WINREV(rev);
  1562. s.append(sizeof(rev), (char *) &rev);
  1563. try
  1564. {
  1565. CriticalBlock c(crit);
  1566. sock->write(s.str(), replyLen + sizeof(rev));
  1567. rval = true;
  1568. }
  1569. catch (IException * E)
  1570. {
  1571. StringBuffer error("HeartBeat write failed with exception: ");
  1572. E->errorMessage(error);
  1573. logctx.CTXLOG("%s", error.str());
  1574. E->Release();
  1575. }
  1576. catch(...)
  1577. {
  1578. logctx.CTXLOG("HeartBeat write failed (Unknown exception)");
  1579. }
  1580. return rval;
  1581. }
  1582. else
  1583. return true;
  1584. };
  1585. class HttpResponseHandler
  1586. {
  1587. private:
  1588. CriticalBlock c; // should not be anyone writing but better to be safe
  1589. StringBuffer header;
  1590. StringBuffer content;
  1591. ISocket *sock = nullptr;
  1592. HttpCompression compression = HttpCompression::NONE;
  1593. bool httpKeepAlive = false;
  1594. unsigned int sent = 0;
  1595. public:
  1596. HttpResponseHandler(ISocket *s, CriticalSection &crit, bool keepAlive) : sock(s), c(crit), httpKeepAlive(keepAlive)
  1597. {
  1598. }
  1599. inline bool compressing()
  1600. {
  1601. return compression!=HttpCompression::NONE;
  1602. }
  1603. inline const char *traceName()
  1604. {
  1605. return compressing() ? "compressor" : "socket";
  1606. }
  1607. inline const char *compressTypeName()
  1608. {
  1609. return compression==HttpCompression::GZIP ? "gzip" : "deflate";
  1610. }
  1611. void init(unsigned length, TextMarkupFormat mlFmt, HttpCompression respCompression)
  1612. {
  1613. if (length > 1500)
  1614. compression = respCompression;
  1615. header.append("HTTP/1.0 200 OK\r\n");
  1616. header.append("Content-Type: ").append(mlFmt == MarkupFmt_JSON ? "application/json" : "text/xml").append("\r\n");
  1617. if (httpKeepAlive)
  1618. header.append("Connection: Keep-Alive\r\n");
  1619. if (!compressing())
  1620. {
  1621. header.append("Content-Length: ").append(length).append("\r\n\r\n");
  1622. if (traceLevel > 5)
  1623. DBGLOG("Writing HTTP header length %d to HTTP socket", header.length());
  1624. sock->write(header.str(), header.length());
  1625. sent += header.length();
  1626. }
  1627. else
  1628. {
  1629. header.append("Content-Encoding: ").append(compression==HttpCompression::GZIP ? "gzip" : "deflate").append("\r\n");
  1630. }
  1631. }
  1632. size32_t write(void const* buf, size32_t size)
  1633. {
  1634. if (!compressing())
  1635. {
  1636. sent += size;
  1637. return sock->write(buf, size);
  1638. }
  1639. content.append(size, (const char *)buf);
  1640. return size;
  1641. }
  1642. size32_t finalize()
  1643. {
  1644. if (compressing())
  1645. {
  1646. #ifdef _USE_ZLIB
  1647. ZlibCompressionType zt = ZlibCompressionType::GZIP;
  1648. if (compression==HttpCompression::DEFLATE)
  1649. zt = ZlibCompressionType::DEFLATE;
  1650. if (compression==HttpCompression::ZLIB_DEFLATE)
  1651. zt = ZlibCompressionType::ZLIB_DEFLATE;
  1652. MemoryBuffer mb;
  1653. zlib_deflate(mb, content.str(), content.length(), GZ_DEFAULT_COMPRESSION, zt);
  1654. if (traceLevel > 5)
  1655. DBGLOG("Compressed content length %u to %u (%s)", content.length(), mb.length(), compressTypeName());
  1656. header.append("Content-Length: ").append(mb.length()).append("\r\n\r\n");
  1657. if (traceLevel > 5)
  1658. DBGLOG("Writing HTTP header length %d to HTTP socket (compressed body)", header.length());
  1659. sock->write(header.str(), header.length());
  1660. sent += header.length();
  1661. if (traceLevel > 5)
  1662. DBGLOG("Writing compressed %s content, length %u, to HTTP socket", compressTypeName(), mb.length());
  1663. sock->write(mb.toByteArray(), mb.length());
  1664. sent += mb.length();
  1665. #else
  1666. throw MakeStringException(-1, "_USE_ZLIB is required for compressed output");
  1667. #endif
  1668. }
  1669. return sent;
  1670. }
  1671. };
  1672. void CSafeSocket::flush()
  1673. {
  1674. if (httpMode)
  1675. {
  1676. unsigned contentLength = 0;
  1677. if (!adaptiveRoot)
  1678. contentLength = contentHead.length() + contentTail.length();
  1679. ForEachItemIn(idx, lengths)
  1680. contentLength += lengths.item(idx);
  1681. HttpResponseHandler resp(sock, crit, httpKeepAlive);
  1682. resp.init(contentLength, mlResponseFmt, respCompression);
  1683. if (!adaptiveRoot || mlResponseFmt != MarkupFmt_JSON)
  1684. {
  1685. if (traceLevel > 5)
  1686. DBGLOG("Writing content head length %" I64F "u to HTTP %s", static_cast<__uint64>(contentHead.length()), resp.traceName());
  1687. resp.write(contentHead.str(), contentHead.length());
  1688. }
  1689. ForEachItemIn(idx2, queued)
  1690. {
  1691. unsigned length = lengths.item(idx2);
  1692. if (traceLevel > 5)
  1693. DBGLOG("Writing block length %d to HTTP %s", length, resp.traceName());
  1694. resp.write(queued.item(idx2), length);
  1695. }
  1696. if (!adaptiveRoot || mlResponseFmt != MarkupFmt_JSON)
  1697. {
  1698. if (traceLevel > 5)
  1699. DBGLOG("Writing content tail length %" I64F "u to HTTP %s", static_cast<__uint64>(contentTail.length()), resp.traceName());
  1700. resp.write(contentTail.str(), contentTail.length());
  1701. }
  1702. sent += resp.finalize();
  1703. if (traceLevel > 5)
  1704. DBGLOG("Total written %d", sent);
  1705. }
  1706. }
  1707. void CSafeSocket::sendException(const char *source, unsigned code, const char *message, bool isBlocked, const IContextLogger &logctx)
  1708. {
  1709. try
  1710. {
  1711. FlushingStringBuffer response(this, isBlocked, MarkupFmt_XML, false, httpMode, logctx);
  1712. response.startDataset("Exception", NULL, (unsigned) -1);
  1713. response.appendf("<Source>%s</Source><Code>%d</Code>", source, code);
  1714. response.append("<Message>");
  1715. response.encodeString(message, strlen(message));
  1716. response.append("</Message>");
  1717. }
  1718. catch(IException *EE)
  1719. {
  1720. StringBuffer error("While reporting exception: ");
  1721. EE->errorMessage(error);
  1722. logctx.CTXLOG("%s", error.str());
  1723. EE->Release();
  1724. }
  1725. #ifndef _DEBUG
  1726. catch(...) {}
  1727. #endif
  1728. }
  1729. //==============================================================================================================
  1730. #define RESULT_FLUSH_THRESHOLD 10000u
  1731. #ifdef _DEBUG
  1732. #define HTTP_SPLIT_THRESHOLD 100u
  1733. #define HTTP_SPLIT_RESERVE 200u
  1734. #else
  1735. #define HTTP_SPLIT_THRESHOLD 64000u
  1736. #define HTTP_SPLIT_RESERVE 65535u
  1737. #endif
  1738. interface IXmlStreamFlusher;
  1739. //==============================================================================================================
  1740. bool FlushingStringBuffer::needsFlush(bool closing)
  1741. {
  1742. if (isBlocked || closing) // can't flush unblocked. MORE - may need to break it up though....
  1743. {
  1744. size32_t len = s.length() - emptyLength;
  1745. return len > (closing ? 0 : RESULT_FLUSH_THRESHOLD);
  1746. }
  1747. else
  1748. return false; // MORE - if there is a single result, it can be flushed (actually, can flush anytime all prior results have been closed)
  1749. }
  1750. void FlushingStringBuffer::startBlock()
  1751. {
  1752. size32_t len = 0;
  1753. s.clear();
  1754. if (!isHttp)
  1755. append(sizeof(size32_t), (char *) &len);
  1756. rowCount = 0;
  1757. if (isBlocked)
  1758. {
  1759. s.append('R');
  1760. unsigned rev = sequenceNumber++;
  1761. _WINREV(rev);
  1762. s.append(sizeof(rev), (char *) &rev);
  1763. rev = rowCount;
  1764. _WINREV(rev);
  1765. s.append(sizeof(rev), (char *) &rev); // NOTE - need to patch up later. At this point it is 0.
  1766. s.append(strlen(name)+1, name);
  1767. }
  1768. emptyLength = s.length();
  1769. // MORE - should probably pre-reserve string at RESULT_FLUSH_THRESHOLD plus a bit
  1770. }
  1771. FlushingStringBuffer::FlushingStringBuffer(SafeSocket *_sock, bool _isBlocked, TextMarkupFormat _mlFmt, bool _isRaw, bool _isHttp, const IContextLogger &_logctx)
  1772. : sock(_sock), isBlocked(_isBlocked), mlFmt(_mlFmt), isRaw(_isRaw), isHttp(_isHttp), logctx(_logctx)
  1773. {
  1774. sequenceNumber = 0;
  1775. rowCount = 0;
  1776. isSoap = false;
  1777. isEmpty = true;
  1778. extend = false;
  1779. emptyLength = 0;
  1780. tagClosed = true;
  1781. }
  1782. FlushingStringBuffer::~FlushingStringBuffer()
  1783. {
  1784. try
  1785. {
  1786. flush(true);
  1787. }
  1788. catch (IException *E)
  1789. {
  1790. // Ignore any socket errors that we get at termination - nothing we can do about them anyway...
  1791. E->Release();
  1792. }
  1793. catch(...)
  1794. {
  1795. }
  1796. ForEachItemIn(idx, queued)
  1797. {
  1798. free(queued.item(idx));
  1799. }
  1800. }
  1801. //void FlushingStringBuffer::append(char data)
  1802. //{
  1803. //append(1, &data);
  1804. //}
  1805. void FlushingStringBuffer::append(const char *data)
  1806. {
  1807. append(strlen(data), data);
  1808. }
  1809. void FlushingStringBuffer::append(double data)
  1810. {
  1811. if (isRaw)
  1812. append(sizeof(data), (char *)&data);
  1813. else
  1814. {
  1815. StringBuffer v;
  1816. v.append(data);
  1817. append(v.length(), v.str());
  1818. }
  1819. }
  1820. void FlushingStringBuffer::append(unsigned len, const char *data)
  1821. {
  1822. try
  1823. {
  1824. CriticalBlock b(crit);
  1825. s.append(len, data);
  1826. }
  1827. catch (IException *E)
  1828. {
  1829. logctx.logOperatorException(E, __FILE__, __LINE__, "FlushingStringBuffer::append");
  1830. throw;
  1831. }
  1832. }
  1833. void FlushingStringBuffer::appendf(const char *format, ...)
  1834. {
  1835. StringBuffer t;
  1836. va_list args;
  1837. va_start(args, format);
  1838. t.valist_appendf(format, args);
  1839. va_end(args);
  1840. append(t.length(), t.str());
  1841. }
  1842. void FlushingStringBuffer::encodeString(const char *x, unsigned len, bool utf8)
  1843. {
  1844. if (mlFmt==MarkupFmt_XML)
  1845. {
  1846. StringBuffer t;
  1847. ::encodeXML(x, t, 0, len, utf8);
  1848. append(t.length(), t.str());
  1849. }
  1850. else
  1851. append(len, x);
  1852. }
  1853. void FlushingStringBuffer::encodeData(const void *data, unsigned len)
  1854. {
  1855. static char hexchar[] = "0123456789ABCDEF";
  1856. if (isRaw)
  1857. append(len, (const char *) data);
  1858. else
  1859. {
  1860. const byte *field = (const byte *) data;
  1861. for (unsigned i = 0; i < len; i++)
  1862. {
  1863. append(hexchar[field[i] >> 4]);
  1864. append(hexchar[field[i] & 0x0f]);
  1865. }
  1866. }
  1867. }
  1868. void FlushingStringBuffer::addPayload(StringBuffer &s, unsigned int reserve)
  1869. {
  1870. if (!s.length())
  1871. return;
  1872. lengths.append(s.length());
  1873. queued.append(s.detach());
  1874. if (reserve)
  1875. s.ensureCapacity(reserve);
  1876. }
  1877. void FlushingStringBuffer::flushXML(StringBuffer &current, bool isClosing, const char *delim)
  1878. {
  1879. CriticalBlock b(crit);
  1880. if (isClosing && delim && current.length())
  1881. {
  1882. if (!first)
  1883. s.append(delim);
  1884. else
  1885. first = false;
  1886. }
  1887. if (isHttp) // we don't do any chunking for non-HTTP yet
  1888. {
  1889. if (isClosing || current.length() > HTTP_SPLIT_THRESHOLD)
  1890. {
  1891. addPayload(s, HTTP_SPLIT_RESERVE);
  1892. addPayload(current, isClosing ? 0 : HTTP_SPLIT_RESERVE);
  1893. }
  1894. }
  1895. else if (isClosing)
  1896. append(current.length(), current.str());
  1897. }
  1898. void FlushingStringBuffer::flush(bool closing)
  1899. {
  1900. CriticalBlock b(crit);
  1901. if (closing && tail.length())
  1902. {
  1903. s.append(tail);
  1904. tail.clear();
  1905. }
  1906. if (isHttp)
  1907. {
  1908. if (!closing && s.length() > HTTP_SPLIT_THRESHOLD)
  1909. addPayload(s, HTTP_SPLIT_RESERVE);
  1910. }
  1911. else if (needsFlush(closing))
  1912. {
  1913. // MORE - if not blocked we can get very large blocks.
  1914. assertex(s.length() > sizeof(size32_t));
  1915. unsigned replyLen = s.length() - sizeof(size32_t);
  1916. unsigned revLen = replyLen | ((isBlocked)?0x80000000:0);
  1917. _WINREV(revLen);
  1918. if (logctx.queryTraceLevel() > 1)
  1919. {
  1920. if (isBlocked)
  1921. logctx.CTXLOG("Sending reply: Sending blocked %s data", getFormatName(mlFmt));
  1922. else
  1923. #ifdef _DEBUG
  1924. logctx.CTXLOG("Sending reply length %d: %.1024s", (unsigned) (s.length() - sizeof(size32_t)), s.str()+sizeof(size32_t));
  1925. #else
  1926. logctx.CTXLOG("Sending reply length %d: %.40s", (unsigned) (s.length() - sizeof(size32_t)), s.str()+sizeof(size32_t));
  1927. #endif
  1928. }
  1929. *(size32_t *) s.str() = revLen;
  1930. if (isBlocked)
  1931. {
  1932. unsigned revRowCount = rowCount;
  1933. _WINREV(revRowCount);
  1934. *(size32_t *) (s.str()+9) = revRowCount;
  1935. }
  1936. if (logctx.queryTraceLevel() > 9)
  1937. logctx.CTXLOG("writing block size %d to socket", replyLen);
  1938. try
  1939. {
  1940. if (sock)
  1941. {
  1942. if (isHttp)
  1943. sock->write(s.str()+sizeof(revLen), replyLen);
  1944. else
  1945. sock->write(s.str(), replyLen + sizeof(revLen));
  1946. }
  1947. else
  1948. fwrite(s.str()+sizeof(revLen), replyLen, 1, stdout);
  1949. }
  1950. catch (...)
  1951. {
  1952. if (logctx.queryTraceLevel() > 9)
  1953. logctx.CTXLOG("Exception caught FlushingStringBuffer::flush");
  1954. s.clear();
  1955. emptyLength = 0;
  1956. throw;
  1957. }
  1958. if (logctx.queryTraceLevel() > 9)
  1959. logctx.CTXLOG("wrote block size %d to socket", replyLen);
  1960. if (closing)
  1961. {
  1962. s.clear();
  1963. emptyLength = 0;
  1964. }
  1965. else
  1966. startBlock();
  1967. }
  1968. }
  1969. void *FlushingStringBuffer::getPayload(size32_t &length)
  1970. {
  1971. assertex(isHttp);
  1972. CriticalBlock b(crit);
  1973. if (queued.ordinality())
  1974. {
  1975. length = lengths.item(0);
  1976. void *ret = queued.item(0);
  1977. queued.remove(0);
  1978. lengths.remove(0);
  1979. return ret;
  1980. }
  1981. length = s.length();
  1982. return length ? s.detach() : NULL;
  1983. }
  1984. void FlushingStringBuffer::startDataset(const char *elementName, const char *resultName, unsigned sequence, bool _extend, const IProperties *xmlns, bool adaptive)
  1985. {
  1986. CriticalBlock b(crit);
  1987. extend = _extend;
  1988. if (isEmpty || !extend)
  1989. {
  1990. name.clear().append(resultName ? resultName : elementName);
  1991. sequenceNumber = 0;
  1992. startBlock();
  1993. if (!isBlocked)
  1994. {
  1995. if (mlFmt==MarkupFmt_XML && elementName)
  1996. {
  1997. s.append('<').append(elementName);
  1998. if (!adaptive)
  1999. {
  2000. if (isSoap && (resultName || (sequence != (unsigned) -1)))
  2001. {
  2002. s.append(" xmlns=\'urn:hpccsystems:ecl:").appendLower(queryName.length(), queryName.str()).append(":result:");
  2003. if (resultName && *resultName)
  2004. s.appendLower(strlen(resultName), resultName).append('\'');
  2005. else
  2006. s.append("result_").append(sequence+1).append('\'');
  2007. if (xmlns)
  2008. {
  2009. Owned<IPropertyIterator> it = const_cast<IProperties*>(xmlns)->getIterator(); //should fix IProperties to be const friendly
  2010. ForEach(*it)
  2011. {
  2012. const char *name = it->getPropKey();
  2013. s.append(' ');
  2014. if (!streq(name, "xmlns"))
  2015. s.append("xmlns:");
  2016. s.append(name).append("='");
  2017. encodeUtf8XML(const_cast<IProperties*>(xmlns)->queryProp(name), s);
  2018. s.append("'");
  2019. }
  2020. }
  2021. }
  2022. if (resultName && *resultName)
  2023. s.appendf(" name='%s'",resultName);
  2024. else if (sequence != (unsigned) -1)
  2025. s.appendf(" name='Result %d'",sequence+1);
  2026. }
  2027. s.append(">\n");
  2028. tail.clear().appendf("</%s>\n", elementName);
  2029. }
  2030. }
  2031. isEmpty = false;
  2032. }
  2033. }
  2034. void FlushingStringBuffer::startScalar(const char *resultName, unsigned sequence, bool simpleTag, const char *simpleName)
  2035. {
  2036. if (s.length())
  2037. throw MakeStringException(0, "Attempt to output scalar ('%s',%d) multiple times", resultName ? resultName : "", (int)sequence);
  2038. CriticalBlock b(crit);
  2039. name.clear().append(resultName ? resultName : "Dataset");
  2040. sequenceNumber = 0;
  2041. startBlock();
  2042. if (!isBlocked)
  2043. {
  2044. if (mlFmt==MarkupFmt_XML)
  2045. {
  2046. if (!simpleTag)
  2047. {
  2048. tail.clear();
  2049. s.append("<Dataset");
  2050. if (isSoap && (resultName || (sequence != (unsigned) -1)))
  2051. {
  2052. s.append(" xmlns=\'urn:hpccsystems:ecl:").appendLower(queryName.length(), queryName.str()).append(":result:");
  2053. if (resultName && *resultName)
  2054. s.appendLower(strlen(resultName), resultName).append('\'');
  2055. else
  2056. s.append("result_").append(sequence+1).append('\'');
  2057. }
  2058. if (resultName && *resultName)
  2059. s.appendf(" name='%s'>\n",resultName);
  2060. else
  2061. s.appendf(" name='Result %d'>\n",sequence+1);
  2062. s.append(" <Row>");
  2063. }
  2064. if (!simpleName)
  2065. simpleName = resultName;
  2066. if (simpleName && *simpleName)
  2067. {
  2068. s.appendf("<%s>", simpleName);
  2069. tail.appendf("</%s>", simpleName);
  2070. }
  2071. else
  2072. {
  2073. s.appendf("<Result_%d>", sequence+1);
  2074. tail.appendf("</Result_%d>", sequence+1);
  2075. }
  2076. if (!simpleTag)
  2077. tail.appendf("</Row>\n</Dataset>\n");
  2078. }
  2079. else if (!isRaw)
  2080. {
  2081. tail.clear().append('\n');
  2082. }
  2083. }
  2084. }
  2085. void FlushingStringBuffer::setScalarInt(const char *resultName, unsigned sequence, __int64 value, unsigned size)
  2086. {
  2087. startScalar(resultName, sequence);
  2088. s.append(value);
  2089. }
  2090. void FlushingStringBuffer::setScalarUInt(const char *resultName, unsigned sequence, unsigned __int64 value, unsigned size)
  2091. {
  2092. startScalar(resultName, sequence);
  2093. s.append(value);
  2094. }
  2095. void FlushingStringBuffer::incrementRowCount()
  2096. {
  2097. CriticalBlock b(crit);
  2098. rowCount++;
  2099. }
  2100. void FlushingJsonBuffer::append(double data)
  2101. {
  2102. CriticalBlock b(crit);
  2103. appendJSONRealValue(s, NULL, data);
  2104. }
  2105. void FlushingJsonBuffer::encodeString(const char *x, unsigned len, bool utf8)
  2106. {
  2107. CriticalBlock b(crit);
  2108. appendJSONStringValue(s, NULL, len, x, true);
  2109. }
  2110. void FlushingJsonBuffer::encodeData(const void *data, unsigned len)
  2111. {
  2112. CriticalBlock b(crit);
  2113. appendJSONDataValue(s, NULL, len, data);
  2114. }
  2115. void FlushingJsonBuffer::startDataset(const char *elementName, const char *resultName, unsigned sequence, bool _extend, const IProperties *xmlns, bool adaptive)
  2116. {
  2117. CriticalBlock b(crit);
  2118. extend = _extend;
  2119. if (isEmpty || !extend)
  2120. {
  2121. name.clear().append(resultName ? resultName : elementName);
  2122. sequenceNumber = 0;
  2123. startBlock();
  2124. if (elementName && !isBlocked)
  2125. {
  2126. StringBuffer seqName;
  2127. if (!resultName || !*resultName)
  2128. resultName = seqName.appendf("result_%d", sequence+1).str();
  2129. appendJSONName(s, resultName).append('{');
  2130. if (!adaptive)
  2131. appendJSONName(s, "Row").append('[');
  2132. tail.set(adaptive ? "}" : "]}");
  2133. }
  2134. isEmpty = false;
  2135. }
  2136. }
  2137. void FlushingJsonBuffer::startScalar(const char *resultName, unsigned sequence, bool simpleTag, const char *simpleName)
  2138. {
  2139. if (s.length())
  2140. throw MakeStringException(0, "Attempt to output scalar ('%s',%d) multiple times", resultName ? resultName : "", (int)sequence);
  2141. CriticalBlock b(crit);
  2142. name.set(resultName ? resultName : "Dataset");
  2143. sequenceNumber = 0;
  2144. startBlock();
  2145. if (!isBlocked)
  2146. {
  2147. if (!simpleTag)
  2148. {
  2149. StringBuffer seqName;
  2150. if (!resultName || !*resultName)
  2151. resultName = seqName.appendf("Result_%d", sequence+1).str();
  2152. appendJSONName(s, resultName).append('{');
  2153. appendJSONName(s, "Row").append("[");
  2154. }
  2155. s.append('{');
  2156. appendJSONName(s, (simpleName && *simpleName) ? simpleName : resultName);
  2157. tail.set("}");
  2158. if (!simpleTag)
  2159. tail.append("]}");
  2160. }
  2161. }
  2162. void FlushingJsonBuffer::setScalarInt(const char *resultName, unsigned sequence, __int64 value, unsigned size, bool simpleTag, const char *simpleName)
  2163. {
  2164. startScalar(resultName, sequence, simpleTag, simpleName);
  2165. if (size < 7) //JavaScript only supports 53 significant bits
  2166. s.append(value);
  2167. else
  2168. s.append('"').append(value).append('"');
  2169. }
  2170. void FlushingJsonBuffer::setScalarUInt(const char *resultName, unsigned sequence, unsigned __int64 value, unsigned size, bool simpleTag, const char *simpleName)
  2171. {
  2172. startScalar(resultName, sequence, simpleTag, simpleName);
  2173. if (size < 7) //JavaScript doesn't support unsigned, and only supports 53 significant bits
  2174. s.append(value);
  2175. else
  2176. s.append('"').append(value).append('"');
  2177. }
  2178. //=====================================================================================================
  2179. ClusterWriteHandler::ClusterWriteHandler(char const * _logicalName, char const * _activityType)
  2180. : logicalName(_logicalName), activityType(_activityType)
  2181. {
  2182. makePhysicalPartName(logicalName.get(), 1, 1, physicalName, false);
  2183. splitFilename(physicalName, &physicalDir, &physicalDir, &physicalBase, &physicalBase);
  2184. }
  2185. void ClusterWriteHandler::addCluster(char const * cluster)
  2186. {
  2187. Owned<IGroup> group = queryNamedGroupStore().lookup(cluster);
  2188. if (!group)
  2189. throw MakeStringException(0, "Unknown cluster %s while writing file %s", cluster, logicalName.get());
  2190. if (group->isMember())
  2191. {
  2192. if (localCluster)
  2193. throw MakeStringException(0, "Cluster %s occupies node already specified while writing file %s", cluster,
  2194. logicalName.get());
  2195. localClusterName.set(cluster);
  2196. localCluster.set(group);
  2197. }
  2198. else
  2199. {
  2200. ForEachItemIn(idx, remoteNodes)
  2201. {
  2202. Owned<INode> other = remoteNodes.item(idx).getNode(0);
  2203. if (group->isMember(other))
  2204. throw MakeStringException(0, "Cluster %s occupies node already specified while writing file %s",
  2205. cluster, logicalName.get());
  2206. }
  2207. remoteNodes.append(*group.getClear());
  2208. remoteClusters.append(cluster);
  2209. }
  2210. }
  2211. void ClusterWriteHandler::getLocalPhysicalFilename(StringAttr & out) const
  2212. {
  2213. if(localCluster.get())
  2214. out.set(physicalName.str());
  2215. else
  2216. getTempFilename(out);
  2217. PROGLOG("%s(CLUSTER) for logical filename %s writing to local file %s", activityType.get(), logicalName.get(), out.get());
  2218. }
  2219. void ClusterWriteHandler::splitPhysicalFilename(StringBuffer & dir, StringBuffer & base) const
  2220. {
  2221. dir.append(physicalDir);
  2222. base.append(physicalBase);
  2223. }
  2224. void ClusterWriteHandler::getTempFilename(StringAttr & out) const
  2225. {
  2226. // Should be implemented by more derived (platform-specific) class, if needed
  2227. throwUnexpected();
  2228. }
  2229. void ClusterWriteHandler::copyPhysical(IFile * source, bool noCopy) const
  2230. {
  2231. RemoteFilename rdn, rfn;
  2232. rdn.setLocalPath(physicalDir.str());
  2233. rfn.setLocalPath(physicalName.str());
  2234. ForEachItemIn(idx, remoteNodes)
  2235. {
  2236. rdn.setEp(remoteNodes.item(idx).queryNode(0).endpoint());
  2237. rfn.setEp(remoteNodes.item(idx).queryNode(0).endpoint());
  2238. Owned<IFile> targetdir = createIFile(rdn);
  2239. Owned<IFile> target = createIFile(rfn);
  2240. PROGLOG("%s(CLUSTER) for logical filename %s copying %s to %s", activityType.get(), logicalName.get(), source->queryFilename(), target->queryFilename());
  2241. if(noCopy)
  2242. {
  2243. WARNLOG("Skipping remote copy due to debug option");
  2244. }
  2245. else
  2246. {
  2247. targetdir->createDirectory();
  2248. copyFile(target, source);
  2249. }
  2250. }
  2251. }
  2252. void ClusterWriteHandler::setDescriptorParts(IFileDescriptor * desc, char const * basename, IPropertyTree * attrs) const
  2253. {
  2254. if(!localCluster.get()&&(remoteNodes.ordinality()==0))
  2255. throw MakeStringException(0, "Attempting to write file to no clusters");
  2256. ClusterPartDiskMapSpec partmap; // will get this from group at some point
  2257. desc->setNumParts(1);
  2258. desc->setPartMask(basename);
  2259. if (localCluster)
  2260. desc->addCluster(localClusterName,localCluster, partmap);
  2261. ForEachItemIn(idx,remoteNodes)
  2262. desc->addCluster(remoteClusters.item(idx),&remoteNodes.item(idx), partmap);
  2263. if (attrs) {
  2264. // need to set part attr
  2265. IPartDescriptor *partdesc = desc->queryPart(0);
  2266. IPropertyTree &pprop = partdesc->queryProperties();
  2267. // bit of a kludge (should really set properties *after* creating part rather than passing prop tree in)
  2268. Owned<IAttributeIterator> ai = attrs->getAttributes();
  2269. ForEach(*ai)
  2270. pprop.setProp(ai->queryName(),ai->queryValue());
  2271. }
  2272. }
  2273. void ClusterWriteHandler::finish(IFile * file) const
  2274. {
  2275. if(!localCluster.get())
  2276. {
  2277. PROGLOG("%s(CLUSTER) for logical filename %s removing temporary file %s", activityType.get(), logicalName.get(), file->queryFilename());
  2278. file->remove();
  2279. }
  2280. }
  2281. void ClusterWriteHandler::getClusters(StringArray &clusters) const
  2282. {
  2283. if(localCluster)
  2284. clusters.append(localClusterName);
  2285. ForEachItemIn(c, remoteClusters)
  2286. clusters.append(remoteClusters.item(c));
  2287. }
  2288. //=====================================================================================================
  2289. class COrderedOutputSerializer : implements IOrderedOutputSerializer, public CInterface
  2290. {
  2291. class COrderedResult : public CInterface
  2292. {
  2293. bool closed;
  2294. StringBuffer sb;
  2295. public:
  2296. COrderedResult() : closed(false) {}
  2297. bool flush(FILE * outFile, bool onlyClosed)
  2298. {
  2299. if (closed || !onlyClosed)
  2300. {
  2301. if (sb.length())
  2302. {
  2303. ::fwrite(sb.str(), sb.length(), 1, outFile);
  2304. sb.clear();
  2305. }
  2306. }
  2307. return closed;
  2308. }
  2309. size32_t printf(const char *format, va_list args) __attribute__((format(printf,2,0)))
  2310. {
  2311. if (closed)
  2312. throw MakeStringException(0, "Attempting to append to previously closed result in COrderedResult::printf");
  2313. int prevLen = sb.length();
  2314. sb.valist_appendf(format, args);
  2315. return sb.length() - prevLen;
  2316. }
  2317. size32_t fwrite(const void * data, size32_t size, size32_t count)
  2318. {
  2319. if (closed)
  2320. throw MakeStringException(0, "Attempting to append to previously closed result in COrderedResult::fwrite");
  2321. size32_t len = size * count;
  2322. sb.append(len, (const char *)data);
  2323. return len;
  2324. }
  2325. void close(bool nl)
  2326. {
  2327. if (closed)
  2328. throw MakeStringException(0, "Attempting to reclose result in COrderedResult::close");
  2329. if (nl)
  2330. sb.append('\n');
  2331. closed = true;
  2332. }
  2333. };
  2334. CIArrayOf<COrderedResult> COrderedResultArr;
  2335. int lastSeqFlushed;
  2336. FILE * outFile;
  2337. CriticalSection crit;
  2338. COrderedResult * getResult(size32_t seq)
  2339. {
  2340. while ((int)COrderedResultArr.ordinality() < (seq+1))
  2341. COrderedResultArr.append(*(new COrderedResult()));
  2342. return &COrderedResultArr.item(seq);
  2343. }
  2344. void flushCurrent()//stream current sequence
  2345. {
  2346. COrderedResult &res = COrderedResultArr.item(lastSeqFlushed + 1);
  2347. res.flush(outFile,false);
  2348. fflush(outFile);
  2349. }
  2350. void flushCompleted(bool onlyClosed)//flush completed sequence(s)
  2351. {
  2352. int lastSeq = (int)COrderedResultArr.ordinality()-1;
  2353. for (; lastSeqFlushed < lastSeq; lastSeqFlushed++)
  2354. {
  2355. COrderedResult &res = COrderedResultArr.item(lastSeqFlushed + 1);
  2356. if (!res.flush(outFile,onlyClosed) && onlyClosed)
  2357. break;
  2358. }
  2359. fflush(outFile);
  2360. }
  2361. public:
  2362. IMPLEMENT_IINTERFACE;
  2363. COrderedOutputSerializer(FILE* _outFile) : lastSeqFlushed(-1), outFile(_outFile) {}
  2364. ~COrderedOutputSerializer()
  2365. {
  2366. if (lastSeqFlushed != (COrderedResultArr.ordinality()-1))
  2367. flushCompleted(false);
  2368. COrderedResultArr.kill();
  2369. }
  2370. //IOrderedOutputSerializer
  2371. size32_t fwrite(int seq, const void * data, size32_t size, size32_t count)
  2372. {
  2373. CriticalBlock c(crit);
  2374. size32_t ret = getResult(seq)->fwrite(data,size, count);
  2375. if (seq == (lastSeqFlushed + 1))
  2376. flushCurrent();
  2377. return ret;
  2378. }
  2379. size32_t printf(int seq, const char *format, ...) __attribute__((format(printf, 3, 4)))
  2380. {
  2381. CriticalBlock c(crit);
  2382. va_list args;
  2383. va_start(args, format);
  2384. int ret = getResult(seq)->printf(format, args);
  2385. va_end(args);
  2386. if (seq == (lastSeqFlushed + 1))
  2387. flushCurrent();
  2388. return ret;
  2389. }
  2390. void close(int seq, bool nl)
  2391. {
  2392. CriticalBlock c(crit);
  2393. getResult(seq)->close(nl);
  2394. if ( seq == (lastSeqFlushed+1) )
  2395. flushCompleted(true);
  2396. }
  2397. };
  2398. IOrderedOutputSerializer * createOrderedOutputSerializer(FILE * _outFile)
  2399. {
  2400. return new COrderedOutputSerializer(_outFile);
  2401. }
  2402. //=====================================================================================================
  2403. StringBuffer & mangleHelperFileName(StringBuffer & out, const char * in, const char * wuid, unsigned int flags)
  2404. {
  2405. out = in;
  2406. if (flags & (TDXtemporary | TDXjobtemp))
  2407. out.append("__").append(wuid);
  2408. return out;
  2409. }
  2410. StringBuffer & mangleLocalTempFilename(StringBuffer & out, char const * in)
  2411. {
  2412. char const * start = in;
  2413. while(true)
  2414. {
  2415. char const * end = strstr(start, "::");
  2416. if(end)
  2417. {
  2418. out.append(end-start, start).append("__scope__");
  2419. start = end + 2;
  2420. }
  2421. else
  2422. {
  2423. out.append(start);
  2424. break;
  2425. }
  2426. }
  2427. return out;
  2428. }
  2429. static const char *skipLfnForeign(const char *lfn)
  2430. {
  2431. // NOTE: The leading ~ and any leading spaces have already been stripped at this point
  2432. const char *finger = lfn;
  2433. if (strnicmp(finger, "foreign", 7)==0)
  2434. {
  2435. finger += 7;
  2436. while (*finger == ' ')
  2437. finger++;
  2438. if (finger[0] == ':' && finger[1] == ':')
  2439. {
  2440. // foreign scope - need to strip off the ip and port (i.e. from here to the next ::)
  2441. finger += 2; // skip ::
  2442. finger = strstr(finger, "::");
  2443. if (finger)
  2444. {
  2445. finger += 2;
  2446. while (*finger == ' ')
  2447. finger++;
  2448. return finger;
  2449. }
  2450. }
  2451. }
  2452. return lfn;
  2453. }
  2454. StringBuffer & expandLogicalFilename(StringBuffer & logicalName, const char * fname, IConstWorkUnit * wu, bool resolveLocally, bool ignoreForeignPrefix)
  2455. {
  2456. if (fname[0]=='~')
  2457. {
  2458. while (*fname=='~' || *fname==' ')
  2459. fname++;
  2460. if (ignoreForeignPrefix)
  2461. fname = skipLfnForeign(fname);
  2462. logicalName.append(fname);
  2463. }
  2464. else if (resolveLocally)
  2465. {
  2466. StringBuffer sb(fname);
  2467. sb.replaceString("::",PATHSEPSTR);
  2468. makeAbsolutePath(sb.str(), logicalName.clear());
  2469. }
  2470. else
  2471. {
  2472. SCMStringBuffer lfn;
  2473. if (wu)
  2474. {
  2475. wu->getScope(lfn);
  2476. if(lfn.length())
  2477. logicalName.append(lfn.s).append("::");
  2478. }
  2479. logicalName.append(fname);
  2480. }
  2481. return logicalName;
  2482. }
  2483. //----------------------------------------------------------------------------------
  2484. void IRoxieContextLogger::CTXLOGae(IException *E, const char *file, unsigned line, const char *prefix, const char *format, ...) const
  2485. {
  2486. va_list args;
  2487. va_start(args, format);
  2488. CTXLOGaeva(E, file, line, prefix, format, args);
  2489. va_end(args);
  2490. }
  2491. void loadHttpHeaders(IProperties *p, const char *finger)
  2492. {
  2493. while (*finger)
  2494. {
  2495. StringBuffer prop, val;
  2496. while (*finger && *finger != '\r' && *finger != ':')
  2497. prop.append(*finger++);
  2498. if (*finger && *finger != '\r')
  2499. {
  2500. finger++;
  2501. while (isspace(*finger) && *finger != '\r')
  2502. finger++;
  2503. while (*finger && *finger != '\r')
  2504. val.append(*finger++);
  2505. prop.clip();
  2506. val.clip();
  2507. if (prop.length())
  2508. p->setProp(prop.str(), val.str());
  2509. }
  2510. if (*finger)
  2511. finger++;
  2512. if ('\n'==*finger)
  2513. finger++;
  2514. }
  2515. }
  2516. void HttpHelper::parseRequestHeaders(const char *headers)
  2517. {
  2518. if (!reqHeaders)
  2519. reqHeaders.setown(createProperties());
  2520. loadHttpHeaders(reqHeaders, headers);
  2521. const char *val = queryRequestHeader("Content-Type");
  2522. if (val)
  2523. setContentType(val); //response type defaults to request type
  2524. val = queryRequestHeader("Authorization");
  2525. if (val && !strncmp(val, "Basic ", 6))
  2526. setAuthToken(val+6);
  2527. }
  2528. void HttpHelper::parseURL()
  2529. {
  2530. const char *start = url.str();
  2531. while (isspace(*start))
  2532. start++;
  2533. if (*start=='/')
  2534. start++;
  2535. StringAttr path;
  2536. const char *finger = strpbrk(start, "?");
  2537. if (finger)
  2538. path.set(start, finger-start);
  2539. else
  2540. path.set(start);
  2541. if (path.length())
  2542. pathNodes.appendList(path, "/");
  2543. if (!finger)
  2544. return;
  2545. parseHttpParameterString(parameters, ++finger);
  2546. }
  2547. //=====================================================================================================================
  2548. class NullSectionTimer : public CSimpleInterfaceOf<ISectionTimer>
  2549. {
  2550. virtual unsigned __int64 getStartCycles() { return 0; }
  2551. virtual void noteSectionTime(unsigned __int64 startCycles) {}
  2552. };
  2553. static NullSectionTimer nullSectionTimer;
  2554. ISectionTimer * queryNullSectionTimer() { return &nullSectionTimer; }