roxiehelper.cpp 78 KB

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