roxiehelper.cpp 78 KB

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