roxiehelper.cpp 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440
  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 "thorherror.h"
  15. #include "roxiehelper.hpp"
  16. #include "roxielmj.hpp"
  17. #include "jmisc.hpp"
  18. #include "jfile.hpp"
  19. #include "mpbase.hpp"
  20. #include "dafdesc.hpp"
  21. #include "dadfs.hpp"
  22. unsigned traceLevel = 0;
  23. //OwnedRowArray
  24. void OwnedRowArray::clear()
  25. {
  26. ForEachItemIn(idx, buff)
  27. ReleaseRoxieRow(buff.item(idx));
  28. buff.kill();
  29. }
  30. void OwnedRowArray::clearPart(aindex_t from, aindex_t to)
  31. {
  32. aindex_t idx;
  33. for(idx = from; idx < to; idx++)
  34. ReleaseRoxieRow(buff.item(idx));
  35. buff.removen(from, to-from);
  36. }
  37. void OwnedRowArray::replace(const void * row, aindex_t pos)
  38. {
  39. ReleaseRoxieRow(buff.item(pos));
  40. buff.replace(row, pos);
  41. }
  42. //=========================================================================================
  43. //CRHRollingCacheElem copied/modified from THOR
  44. CRHRollingCacheElem::CRHRollingCacheElem()
  45. {
  46. row = NULL;
  47. cmp = INT_MIN;
  48. }
  49. CRHRollingCacheElem::~CRHRollingCacheElem()
  50. {
  51. if (row)
  52. ReleaseRoxieRow(row);
  53. }
  54. void CRHRollingCacheElem::set(const void *_row)
  55. {
  56. if (row)
  57. ReleaseRoxieRow(row);
  58. row = _row;
  59. }
  60. //CRHRollingCache copied/modified from THOR CRollingCache
  61. CRHRollingCache::~CRHRollingCache()
  62. {
  63. loop
  64. {
  65. CRHRollingCacheElem *e = cache.dequeue();
  66. if (!e)
  67. break;
  68. delete e;
  69. }
  70. }
  71. void CRHRollingCache::init(IInputBase *_in, unsigned _max)
  72. {
  73. max = _max;
  74. in =_in;
  75. cache.clear();
  76. cache.reserve(max);
  77. eos = false;
  78. while (cache.ordinality()<max/2)
  79. cache.enqueue(NULL);
  80. while (!eos && (cache.ordinality()<max))
  81. advance();
  82. }
  83. #ifdef TRACEROLLING
  84. void CRHRollingCache::PrintCache()
  85. {
  86. for (unsigned i = 0;i<max;i++) {
  87. CRHRollingCacheElem *e = cache.item(i);
  88. if (i==0)
  89. DBGLOG("RC==============================");
  90. int ii = 0;
  91. if (e && e->row)
  92. ii = isalpha(*((char*)e->row)) ? 0 : 4;
  93. chas sz[100];
  94. sprintf(sz,"%c%d: %s",(i==max/2)?'>':' ',i,e?(const char *)e->row+ii:"-----");
  95. for (int xx=0; sz[xx] != NULL; xx++)
  96. {
  97. if (!isprint(sz[xx]))
  98. {
  99. sz[xx] = NULL;
  100. break;
  101. }
  102. }
  103. DBGLOG(sz);
  104. if (i == max-1)
  105. DBGLOG("RC==============================");
  106. }
  107. }
  108. #endif
  109. CRHRollingCacheElem * CRHRollingCache::mid(int rel)
  110. {
  111. return cache.item((max/2)+rel); // relies on unsigned wrap
  112. }
  113. void CRHRollingCache::advance()
  114. {
  115. CRHRollingCacheElem *e = (cache.ordinality()==max)?cache.dequeue():NULL; //cache full, remove head element
  116. if (!eos) {
  117. if (!e)
  118. e = new CRHRollingCacheElem();
  119. const void * nextrec = in->nextInGroup();//get row from CRHCRHDualCache::cOut, which gets from CRHCRHDualCache, which gets from input
  120. if (!nextrec)
  121. nextrec = in->nextInGroup();
  122. if (nextrec) {
  123. e->set(nextrec);
  124. cache.enqueue(e);
  125. #ifdef TRACEROLLING
  126. PrintCache();
  127. #endif
  128. return;
  129. }
  130. else
  131. eos = true;
  132. }
  133. delete e;
  134. cache.enqueue(NULL);
  135. #ifdef TRACEROLLING
  136. PrintCache();
  137. #endif
  138. }
  139. //=========================================================================================
  140. //CRHDualCache copied from THOR, and modified to get input from IInputBase instead
  141. //of IReadSeqVar and to manage rows as OwnedRoxieRow types
  142. CRHDualCache::CRHDualCache()
  143. {
  144. strm1 = NULL;
  145. strm2 = NULL;
  146. }
  147. CRHDualCache::~CRHDualCache()
  148. {
  149. ::Release(strm1);
  150. ::Release(strm2);
  151. loop
  152. {
  153. CRHRollingCacheElem *e = cache.dequeue();
  154. if (!e)
  155. break;
  156. delete e;
  157. }
  158. }
  159. void CRHDualCache::init(IInputBase * _in)
  160. {
  161. in = _in;
  162. cache.clear();
  163. eos = false;
  164. base = 0;
  165. posL = 0;
  166. posR = 0;
  167. strm1 = new cOut(this,posL);
  168. strm2 = new cOut(this,posR) ;
  169. }
  170. #ifdef TRACEROLLING
  171. void CRHDualCache::PrintCache()
  172. {
  173. for (unsigned i = 0;i<cache.ordinality();i++) {
  174. CRHRollingCacheElem *e = cache.item(i);
  175. if (i==0)
  176. {
  177. DBGLOG("DC=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-BASE:%d,posL=%d,posR=%d %s", base, posL,posR, eos?"EOS":"");
  178. }
  179. DBGLOG("%c%d: %s",(i==cache.ordinality()/2)?'>':' ',i,e?(const char *)e->row:"-----");
  180. if (i == cache.ordinality()-1)
  181. DBGLOG("DC=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-");
  182. }
  183. }
  184. #endif
  185. bool CRHDualCache::get(unsigned n, CRHRollingCacheElem *&out)
  186. {
  187. // take off any no longer needed
  188. CRHRollingCacheElem *e=NULL;
  189. while ((base<posL) && (base<posR)) {
  190. delete e;
  191. e = cache.dequeue();
  192. base++;
  193. }
  194. assertex(n>=base);
  195. while (!eos && (n-base>=cache.ordinality())) //element already in cache?
  196. {
  197. if (!e)
  198. e = new CRHRollingCacheElem;
  199. const void * nextrec = in->nextInGroup(); //get from activity
  200. if (!nextrec)
  201. nextrec = in->nextInGroup();
  202. if (!nextrec) {
  203. eos = true;
  204. break;
  205. }
  206. e->set(nextrec);
  207. cache.enqueue(e);
  208. e = NULL;
  209. #ifdef TRACEROLLING
  210. PrintCache();
  211. #endif
  212. }
  213. delete e;
  214. if (n-base>=cache.ordinality())
  215. return false;
  216. out = cache.item(n-base);
  217. return true;
  218. }
  219. size32_t CRHDualCache::getRecordSize(const void *ptr)
  220. {
  221. return in->queryOutputMeta()->getRecordSize(ptr);
  222. }
  223. size32_t CRHDualCache::getFixedSize() const
  224. {
  225. return in->queryOutputMeta()->getFixedSize();
  226. }
  227. size32_t CRHDualCache::getMinRecordSize() const
  228. {
  229. return in->queryOutputMeta()->getMinRecordSize();
  230. }
  231. CRHDualCache::cOut::cOut(CRHDualCache *_parent, unsigned &_pos)
  232. : pos(_pos)
  233. {
  234. parent = _parent;
  235. stopped = false;
  236. }
  237. const void * CRHDualCache::cOut::nextInGroup()
  238. {
  239. CRHRollingCacheElem *e;
  240. if (stopped || !parent->get(pos,e))
  241. return NULL; //no more data
  242. LinkRoxieRow(e->row);
  243. pos++;
  244. return e->row;
  245. }
  246. IOutputMetaData * CRHDualCache::cOut::queryOutputMeta() const
  247. {
  248. return parent->input()->queryOutputMeta();
  249. }
  250. void CRHDualCache::cOut::stop()
  251. {
  252. pos = (unsigned)-1;
  253. stopped = true;
  254. }
  255. //=========================================================================================
  256. IRHLimitedCompareHelper *createRHLimitedCompareHelper()
  257. {
  258. return new CRHLimitedCompareHelper();
  259. }
  260. //CRHLimitedCompareHelper
  261. void CRHLimitedCompareHelper::init( unsigned _atmost,
  262. IInputBase *_in,
  263. ICompare * _cmp,
  264. ICompare * _limitedcmp )
  265. {
  266. atmost = _atmost;
  267. cache.setown(new CRHRollingCache());
  268. cache->init(_in,(atmost+1)*2);
  269. cmp = _cmp;
  270. limitedcmp = _limitedcmp;
  271. }
  272. bool CRHLimitedCompareHelper::getGroup(OwnedRowArray &group, const void *left)
  273. {
  274. // this could be improved!
  275. // first move 'mid' forwards until mid>=left
  276. int low = 0;
  277. loop
  278. {
  279. CRHRollingCacheElem * r = cache->mid(0);
  280. if (!r)
  281. break; // hit eos
  282. int c = cmp->docompare(left,r->row);
  283. if (c == 0)
  284. {
  285. r->cmp = limitedcmp->docompare(left,r->row);
  286. if (r->cmp <= 0)
  287. break;
  288. }
  289. else if (c < 0)
  290. {
  291. r->cmp = -1;
  292. break;
  293. }
  294. else
  295. r->cmp = 1;
  296. cache->advance();
  297. if (cache->mid(low-1)) // only if haven't hit start
  298. low--;
  299. }
  300. // now scan back (note low should be filled even at eos)
  301. loop
  302. {
  303. CRHRollingCacheElem * pr = cache->mid(low-1);
  304. if (!pr)
  305. break; // hit start
  306. int c = cmp->docompare(left,pr->row);
  307. if (c == 0)
  308. {
  309. pr->cmp = limitedcmp->docompare(left,pr->row);
  310. if (pr->cmp==1)
  311. break;
  312. }
  313. else
  314. {
  315. pr->cmp = 1;
  316. break;
  317. }
  318. low--;
  319. }
  320. int high = 0;
  321. if (cache->mid(0)) // check haven't already hit end
  322. {
  323. // now scan fwd
  324. loop
  325. {
  326. high++;
  327. CRHRollingCacheElem * nr = cache->mid(high);
  328. if (!nr)
  329. break;
  330. int c = cmp->docompare(left,nr->row);
  331. if (c==0)
  332. {
  333. nr->cmp = limitedcmp->docompare(left,nr->row);
  334. if (nr->cmp==-1)
  335. break;
  336. }
  337. else
  338. {
  339. nr->cmp = -1;
  340. break;
  341. }
  342. }
  343. }
  344. while (high-low>(int)atmost)
  345. {
  346. int vl = iabs(cache->mid(low)->cmp);
  347. int vh = iabs(cache->mid(high-1)->cmp);
  348. int v;
  349. if (vl==0)
  350. {
  351. if (vh==0) // both ends equal
  352. return false;
  353. v = vh;
  354. }
  355. else if (vh==0)
  356. v = vl;
  357. else
  358. v = imin(vl,vh);
  359. // remove worst match from either end
  360. while ((low<high)&&(iabs(cache->mid(low)->cmp)==v))
  361. low++;
  362. while ((low<high)&&(iabs(cache->mid(high-1)->cmp)==v))
  363. high--;
  364. if (low>=high)
  365. return true; // couldn't make group;
  366. }
  367. for (int i=low;i<high;i++)
  368. {
  369. CRHRollingCacheElem *r = cache->mid(i);
  370. LinkRoxieRow(r->row);
  371. group.append(r->row);
  372. }
  373. return group.ordinality()>0;
  374. }
  375. //=========================================================================================
  376. CSafeSocket::CSafeSocket(ISocket *_sock)
  377. {
  378. httpMode = false;
  379. mlFmt = MarkupFmt_Unknown;
  380. sent = 0;
  381. heartbeat = false;
  382. sock.setown(_sock);
  383. }
  384. CSafeSocket::~CSafeSocket()
  385. {
  386. sock.clear();
  387. ForEachItemIn(idx, queued)
  388. {
  389. free(queued.item(idx));
  390. }
  391. queued.kill();
  392. lengths.kill();
  393. }
  394. unsigned CSafeSocket::bytesOut() const
  395. {
  396. return sent;
  397. }
  398. bool CSafeSocket::checkConnection() const
  399. {
  400. if (sock)
  401. return sock->check_connection();
  402. else
  403. return false;
  404. }
  405. size32_t CSafeSocket::write(const void *buf, size32_t size, bool takeOwnership)
  406. {
  407. CriticalBlock c(crit); // NOTE: anyone needing to write multiple times without interleave should have already locked this. We lock again for the simple cases.
  408. OwnedMalloc<void> ownedBuffer;
  409. if (takeOwnership)
  410. ownedBuffer.setown((void *) buf);
  411. if (!size)
  412. return 0;
  413. try
  414. {
  415. if (httpMode)
  416. {
  417. if (!takeOwnership)
  418. {
  419. ownedBuffer.setown(malloc(size));
  420. if (!ownedBuffer)
  421. throw MakeStringException(THORHELPER_INTERNAL_ERROR, "Out of memory in CSafeSocket::write (requesting %d bytes)", size);
  422. memcpy(ownedBuffer, buf, size);
  423. }
  424. queued.append(ownedBuffer.getClear());
  425. lengths.append(size);
  426. return size;
  427. }
  428. else
  429. {
  430. sent += size;
  431. size32_t written = sock->write(buf, size);
  432. return written;
  433. }
  434. }
  435. catch(...)
  436. {
  437. heartbeat = false;
  438. throw;
  439. }
  440. }
  441. bool CSafeSocket::readBlock(MemoryBuffer &ret, unsigned timeout, unsigned maxBlockSize)
  442. {
  443. // MORE - this is still not good enough as we could get someone else's block if there are multiple input datasets
  444. CriticalBlock c(crit);
  445. try
  446. {
  447. unsigned bytesRead;
  448. unsigned len;
  449. try
  450. {
  451. sock->read(&len, sizeof (len), sizeof (len), bytesRead, timeout);
  452. }
  453. catch (IJSOCK_Exception *E)
  454. {
  455. if (E->errorCode()==JSOCKERR_graceful_close)
  456. {
  457. E->Release();
  458. return false;
  459. }
  460. throw;
  461. }
  462. assertex(bytesRead == sizeof(len));
  463. _WINREV(len);
  464. if (len & 0x80000000)
  465. len ^= 0x80000000;
  466. if (len > maxBlockSize)
  467. throw MakeStringException(THORHELPER_DATA_ERROR, "Maximum block size (%d bytes) exceeded (missing length prefix?)", maxBlockSize);
  468. if (len)
  469. {
  470. unsigned bytesRead;
  471. sock->read(ret.reserveTruncate(len), len, len, bytesRead, timeout);
  472. }
  473. return len != 0;
  474. }
  475. catch(...)
  476. {
  477. heartbeat = false;
  478. throw;
  479. }
  480. }
  481. bool CSafeSocket::readBlock(StringBuffer &ret, unsigned timeout, HttpHelper *pHttpHelper, bool &continuationNeeded, bool &isStatus, unsigned maxBlockSize)
  482. {
  483. continuationNeeded = false;
  484. isStatus = false;
  485. CriticalBlock c(crit);
  486. try
  487. {
  488. unsigned bytesRead;
  489. unsigned len = 0;
  490. try
  491. {
  492. sock->read(&len, sizeof (len), sizeof (len), bytesRead, timeout);
  493. }
  494. catch (IJSOCK_Exception *E)
  495. {
  496. if (E->errorCode()==JSOCKERR_graceful_close)
  497. {
  498. E->Release();
  499. return false;
  500. }
  501. throw;
  502. }
  503. assertex(bytesRead == sizeof(len));
  504. unsigned left = 0;
  505. char *buf;
  506. if (pHttpHelper != NULL && strncmp((char *)&len, "POST", 4) == 0)
  507. {
  508. #define MAX_HTTP_HEADERSIZE 8000
  509. char header[MAX_HTTP_HEADERSIZE + 1]; // allow room for \0
  510. sock->read(header, 1, MAX_HTTP_HEADERSIZE, bytesRead, timeout);
  511. header[bytesRead] = 0;
  512. char *payload = strstr(header, "\r\n\r\n");
  513. if (payload)
  514. {
  515. *payload = 0;
  516. payload += 4;
  517. char *str;
  518. // capture authentication token
  519. if ((str = strstr(header, "Authorization: Basic ")) != NULL)
  520. pHttpHelper->setAuthToken(str+21);
  521. // capture content type
  522. if ((str = strstr(header, "Content-Type: ")) != NULL)
  523. pHttpHelper->setContentType(str+14);
  524. // determine payload length
  525. str = strstr(header, "Content-Length: ");
  526. if (str)
  527. {
  528. len = atoi(str + strlen("Content-Length: "));
  529. buf = ret.reserveTruncate(len);
  530. left = len - (bytesRead - (payload - header));
  531. if (len > left)
  532. memcpy(buf, payload, len - left);
  533. }
  534. else
  535. left = len = 0;
  536. }
  537. else
  538. left = len = 0;
  539. pHttpHelper->setIsHttp(true);
  540. if (!len)
  541. throw MakeStringException(THORHELPER_DATA_ERROR, "Badly formed HTTP header");
  542. }
  543. else if (strnicmp((char *)&len, "STAT", 4) == 0)
  544. isStatus = true;
  545. else
  546. {
  547. _WINREV(len);
  548. if (len & 0x80000000)
  549. {
  550. len ^= 0x80000000;
  551. continuationNeeded = true;
  552. }
  553. if (len > maxBlockSize)
  554. throw MakeStringException(THORHELPER_DATA_ERROR, "Maximum block size (%d bytes) exceeded (missing length prefix?)", maxBlockSize);
  555. left = len;
  556. if (len)
  557. buf = ret.reserveTruncate(len);
  558. }
  559. if (left)
  560. {
  561. sock->read(buf + (len - left), left, left, bytesRead, timeout);
  562. }
  563. return len != 0;
  564. }
  565. catch (...)
  566. {
  567. heartbeat = false;
  568. throw;
  569. }
  570. }
  571. void CSafeSocket::setHttpMode(const char *queryName, bool arrayMode, TextMarkupFormat _mlfmt)
  572. {
  573. CriticalBlock c(crit); // Should not be needed
  574. httpMode = true;
  575. mlFmt = _mlfmt;
  576. heartbeat = false;
  577. assertex(contentHead.length()==0 && contentTail.length()==0);
  578. if (mlFmt==MarkupFmt_JSON)
  579. {
  580. contentHead.append("{");
  581. contentTail.append("}");
  582. }
  583. else
  584. {
  585. contentHead.append(
  586. "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
  587. "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
  588. "<soap:Body>");
  589. if (arrayMode)
  590. {
  591. contentHead.append("<").append(queryName).append("ResponseArray>");
  592. contentTail.append("</").append(queryName).append("ResponseArray>");
  593. }
  594. contentTail.append("</soap:Body></soap:Envelope>");
  595. }
  596. }
  597. void CSafeSocket::setHeartBeat()
  598. {
  599. CriticalBlock c(crit);
  600. heartbeat = true;
  601. }
  602. bool CSafeSocket::sendHeartBeat(const IContextLogger &logctx)
  603. {
  604. if (heartbeat)
  605. {
  606. StringBuffer s;
  607. bool rval = false;
  608. unsigned replyLen = 5;
  609. unsigned rev = replyLen | 0x80000000; // make it a blocked msg
  610. _WINREV(rev);
  611. s.append(sizeof(rev), (char *) &rev);
  612. s.append('H');
  613. rev = (unsigned) time(NULL);
  614. _WINREV(rev);
  615. s.append(sizeof(rev), (char *) &rev);
  616. try
  617. {
  618. CriticalBlock c(crit);
  619. sock->write(s.str(), replyLen + sizeof(rev));
  620. rval = true;
  621. }
  622. catch (IException * E)
  623. {
  624. StringBuffer error("HeartBeat write failed with exception: ");
  625. E->errorMessage(error);
  626. logctx.CTXLOG("%s", error.str());
  627. E->Release();
  628. }
  629. catch(...)
  630. {
  631. logctx.CTXLOG("HeartBeat write failed (Unknown exception)");
  632. }
  633. return rval;
  634. }
  635. else
  636. return true;
  637. };
  638. void CSafeSocket::flush()
  639. {
  640. if (httpMode)
  641. {
  642. unsigned length = contentHead.length() + contentTail.length();
  643. ForEachItemIn(idx, lengths)
  644. length += lengths.item(idx);
  645. StringBuffer header;
  646. header.append("HTTP/1.0 200 OK\r\n");
  647. header.append("Content-Type: ").append(mlFmt == MarkupFmt_JSON ? "application/json" : "text/xml").append("\r\n");
  648. header.append("Content-Length: ").append(length).append("\r\n\r\n");
  649. CriticalBlock c(crit); // should not be anyone writing but better to be safe
  650. if (traceLevel > 5)
  651. DBGLOG("Writing HTTP header length %d to HTTP socket", header.length());
  652. sock->write(header.str(), header.length());
  653. sent += header.length();
  654. if (traceLevel > 5)
  655. DBGLOG("Writing content head length %d to HTTP socket", contentHead.length());
  656. sock->write(contentHead.str(), contentHead.length());
  657. sent += contentHead.length();
  658. ForEachItemIn(idx2, queued)
  659. {
  660. unsigned length = lengths.item(idx2);
  661. if (traceLevel > 5)
  662. DBGLOG("Writing block length %d to HTTP socket", length);
  663. sock->write(queued.item(idx2), length);
  664. sent += length;
  665. }
  666. if (traceLevel > 5)
  667. DBGLOG("Writing content tail length %d to HTTP socket", contentTail.length());
  668. sock->write(contentTail.str(), contentTail.length());
  669. sent += contentTail.length();
  670. if (traceLevel > 5)
  671. DBGLOG("Total written %d", sent);
  672. }
  673. }
  674. void CSafeSocket::sendException(const char *source, unsigned code, const char *message, bool isBlocked, const IContextLogger &logctx)
  675. {
  676. try
  677. {
  678. FlushingStringBuffer response(this, isBlocked, MarkupFmt_XML, false, httpMode, logctx);
  679. response.startDataset("Exception", NULL, (unsigned) -1);
  680. response.appendf("<Source>%s</Source><Code>%d</Code>", source, code);
  681. response.append("<Message>");
  682. response.encodeXML(message);
  683. response.append("</Message>");
  684. }
  685. catch(IException *EE)
  686. {
  687. StringBuffer error("While reporting exception: ");
  688. EE->errorMessage(error);
  689. logctx.CTXLOG("%s", error.str());
  690. EE->Release();
  691. }
  692. #ifndef _DEBUG
  693. catch(...) {}
  694. #endif
  695. }
  696. //==============================================================================================================
  697. #define RESULT_FLUSH_THRESHOLD 10000u
  698. #ifdef _DEBUG
  699. #define HTTP_SPLIT_THRESHOLD 100u
  700. #define HTTP_SPLIT_RESERVE 200u
  701. #else
  702. #define HTTP_SPLIT_THRESHOLD 64000u
  703. #define HTTP_SPLIT_RESERVE 65535u
  704. #endif
  705. interface IXmlStreamFlusher;
  706. //==============================================================================================================
  707. bool FlushingStringBuffer::needsFlush(bool closing)
  708. {
  709. if (isBlocked || closing) // can't flush unblocked. MORE - may need to break it up though....
  710. {
  711. size32_t len = s.length() - emptyLength;
  712. return len > (closing ? 0 : RESULT_FLUSH_THRESHOLD);
  713. }
  714. else
  715. return false; // MORE - if there is a single result, it can be flushed (actually, can flush anytime all prior results have been closed)
  716. }
  717. void FlushingStringBuffer::startBlock()
  718. {
  719. size32_t len = 0;
  720. s.clear();
  721. if (!isHttp)
  722. append(sizeof(size32_t), (char *) &len);
  723. rowCount = 0;
  724. if (isBlocked)
  725. {
  726. s.append('R');
  727. unsigned rev = sequenceNumber++;
  728. _WINREV(rev);
  729. s.append(sizeof(rev), (char *) &rev);
  730. rev = rowCount;
  731. _WINREV(rev);
  732. s.append(sizeof(rev), (char *) &rev); // NOTE - need to patch up later. At this point it is 0.
  733. s.append(strlen(name)+1, name);
  734. }
  735. emptyLength = s.length();
  736. // MORE - should probably pre-reserve string at RESULT_FLUSH_THRESHOLD plus a bit
  737. }
  738. FlushingStringBuffer::FlushingStringBuffer(SafeSocket *_sock, bool _isBlocked, TextMarkupFormat _mlFmt, bool _isRaw, bool _isHttp, const IContextLogger &_logctx)
  739. : sock(_sock), isBlocked(_isBlocked), mlFmt(_mlFmt), isRaw(_isRaw), isHttp(_isHttp), logctx(_logctx)
  740. {
  741. sequenceNumber = 0;
  742. rowCount = 0;
  743. isSoap = false;
  744. isEmpty = true;
  745. extend = false;
  746. trim = false;
  747. emptyLength = 0;
  748. tagClosed = true;
  749. }
  750. FlushingStringBuffer::~FlushingStringBuffer()
  751. {
  752. try
  753. {
  754. flush(true);
  755. }
  756. catch (IException *E)
  757. {
  758. // Ignore any socket errors that we get at termination - nothing we can do about them anyway...
  759. E->Release();
  760. }
  761. catch(...)
  762. {
  763. }
  764. ForEachItemIn(idx, queued)
  765. {
  766. free(queued.item(idx));
  767. }
  768. }
  769. //void FlushingStringBuffer::append(char data)
  770. //{
  771. //append(1, &data);
  772. //}
  773. void FlushingStringBuffer::append(const char *data)
  774. {
  775. append(strlen(data), data);
  776. }
  777. void FlushingStringBuffer::append(unsigned len, const char *data)
  778. {
  779. try
  780. {
  781. CriticalBlock b(crit);
  782. s.append(len, data);
  783. }
  784. catch (IException *E)
  785. {
  786. logctx.logOperatorException(E, __FILE__, __LINE__, "FlushingStringBuffer::append");
  787. throw;
  788. }
  789. }
  790. void FlushingStringBuffer::appendf(const char *format, ...)
  791. {
  792. StringBuffer t;
  793. va_list args;
  794. va_start(args, format);
  795. t.valist_appendf(format, args);
  796. va_end(args);
  797. append(t.length(), t.str());
  798. }
  799. void FlushingStringBuffer::encodeXML(const char *x, unsigned flags, unsigned len, bool utf8)
  800. {
  801. StringBuffer t;
  802. ::encodeXML(x, t, flags, len, utf8);
  803. append(t.length(), t.str());
  804. }
  805. void FlushingStringBuffer::addPayload(StringBuffer &s, unsigned int reserve)
  806. {
  807. if (!s.length())
  808. return;
  809. lengths.append(s.length());
  810. queued.append(s.detach());
  811. if (reserve)
  812. s.ensureCapacity(reserve);
  813. }
  814. void FlushingStringBuffer::flushXML(StringBuffer &current, bool isClosing)
  815. {
  816. CriticalBlock b(crit);
  817. if (isHttp) // we don't do any chunking for non-HTTP yet
  818. {
  819. if (isClosing || current.length() > HTTP_SPLIT_THRESHOLD)
  820. {
  821. addPayload(s, HTTP_SPLIT_RESERVE);
  822. addPayload(current, isClosing ? 0 : HTTP_SPLIT_RESERVE);
  823. }
  824. }
  825. else if (isClosing)
  826. append(current.length(), current.str());
  827. }
  828. void FlushingStringBuffer::flush(bool closing)
  829. {
  830. CriticalBlock b(crit);
  831. if (closing && tail.length())
  832. {
  833. s.append(tail);
  834. tail.clear();
  835. }
  836. if (isHttp)
  837. {
  838. if (!closing && s.length() > HTTP_SPLIT_THRESHOLD)
  839. addPayload(s, HTTP_SPLIT_RESERVE);
  840. }
  841. else if (needsFlush(closing))
  842. {
  843. // MORE - if not blocked we can get very large blocks.
  844. assertex(s.length() > sizeof(size32_t));
  845. unsigned replyLen = s.length() - sizeof(size32_t);
  846. unsigned revLen = replyLen | ((isBlocked)?0x80000000:0);
  847. _WINREV(revLen);
  848. if (logctx.queryTraceLevel() > 1)
  849. {
  850. if (isBlocked)
  851. logctx.CTXLOG("Sending reply: Sending blocked %s data", getFormatName(mlFmt));
  852. else
  853. #ifdef _DEBUG
  854. logctx.CTXLOG("Sending reply length %d: %.1024s", (unsigned) (s.length() - sizeof(size32_t)), s.str()+sizeof(size32_t));
  855. #else
  856. logctx.CTXLOG("Sending reply length %d: %.40s", (unsigned) (s.length() - sizeof(size32_t)), s.str()+sizeof(size32_t));
  857. #endif
  858. }
  859. *(size32_t *) s.str() = revLen;
  860. if (isBlocked)
  861. {
  862. unsigned revRowCount = rowCount;
  863. _WINREV(revRowCount);
  864. *(size32_t *) (s.str()+9) = revRowCount;
  865. }
  866. if (logctx.queryTraceLevel() > 9)
  867. logctx.CTXLOG("writing block size %d to socket", replyLen);
  868. try
  869. {
  870. if (sock)
  871. {
  872. if (isHttp)
  873. sock->write(s.str()+sizeof(revLen), replyLen);
  874. else
  875. sock->write(s.str(), replyLen + sizeof(revLen));
  876. }
  877. else
  878. fwrite(s.str()+sizeof(revLen), replyLen, 1, stdout);
  879. }
  880. catch (...)
  881. {
  882. if (logctx.queryTraceLevel() > 9)
  883. logctx.CTXLOG("Exception caught FlushingStringBuffer::flush");
  884. s.clear();
  885. emptyLength = 0;
  886. throw;
  887. }
  888. if (logctx.queryTraceLevel() > 9)
  889. logctx.CTXLOG("wrote block size %d to socket", replyLen);
  890. if (closing)
  891. {
  892. s.clear();
  893. emptyLength = 0;
  894. }
  895. else
  896. startBlock();
  897. }
  898. }
  899. void *FlushingStringBuffer::getPayload(size32_t &length)
  900. {
  901. assertex(isHttp);
  902. CriticalBlock b(crit);
  903. if (queued.ordinality())
  904. {
  905. length = lengths.item(0);
  906. void *ret = queued.item(0);
  907. queued.remove(0);
  908. lengths.remove(0);
  909. return ret;
  910. }
  911. length = s.length();
  912. return length ? s.detach() : NULL;
  913. }
  914. void FlushingStringBuffer::startDataset(const char *elementName, const char *resultName, unsigned sequence, bool _extend, const IProperties *xmlns)
  915. {
  916. CriticalBlock b(crit);
  917. extend = _extend;
  918. if (isEmpty || !extend)
  919. {
  920. name.clear().append(resultName ? resultName : elementName);
  921. sequenceNumber = 0;
  922. startBlock();
  923. if (!isBlocked)
  924. {
  925. if (mlFmt==MarkupFmt_XML)
  926. {
  927. s.append('<').append(elementName);
  928. if (isSoap && (resultName || (sequence != (unsigned) -1)))
  929. {
  930. s.append(" xmlns=\'urn:hpccsystems:ecl:").appendLower(queryName.length(), queryName.sget()).append(":result:");
  931. if (resultName && *resultName)
  932. s.appendLower(strlen(resultName), resultName).append('\'');
  933. else
  934. s.append("result_").append(sequence+1).append('\'');
  935. if (xmlns)
  936. {
  937. Owned<IPropertyIterator> it = const_cast<IProperties*>(xmlns)->getIterator(); //should fix IProperties to be const friendly
  938. ForEach(*it)
  939. {
  940. const char *name = it->getPropKey();
  941. s.append(' ');
  942. if (!streq(name, "xmlns"))
  943. s.append("xmlns:");
  944. s.append(name).append("='");
  945. encodeUtf8XML(const_cast<IProperties*>(xmlns)->queryProp(name), s);
  946. s.append("'");
  947. }
  948. }
  949. }
  950. if (resultName && *resultName)
  951. s.appendf(" name='%s'",resultName);
  952. else if (sequence != (unsigned) -1)
  953. s.appendf(" name='Result %d'",sequence+1);
  954. s.append(">\n");
  955. tail.clear().appendf("</%s>\n", elementName);
  956. }
  957. }
  958. isEmpty = false;
  959. }
  960. }
  961. void FlushingStringBuffer::startScalar(const char *resultName, unsigned sequence)
  962. {
  963. CriticalBlock b(crit);
  964. assertex(!s.length());
  965. name.clear().append(resultName ? resultName : "Dataset");
  966. sequenceNumber = 0;
  967. startBlock();
  968. if (!isBlocked)
  969. {
  970. if (mlFmt==MarkupFmt_XML)
  971. {
  972. tail.clear();
  973. s.append("<Dataset");
  974. if (isSoap && (resultName || (sequence != (unsigned) -1)))
  975. {
  976. s.append(" xmlns=\'urn:hpccsystems:ecl:").appendLower(queryName.length(), queryName.sget()).append(":result:");
  977. if (resultName && *resultName)
  978. s.appendLower(strlen(resultName), resultName).append('\'');
  979. else
  980. s.append("result_").append(sequence+1).append('\'');
  981. }
  982. if (resultName && *resultName)
  983. s.appendf(" name='%s'>\n",resultName);
  984. else
  985. s.appendf(" name='Result %d'>\n",sequence+1);
  986. s.append(" <Row>");
  987. if (resultName && *resultName)
  988. {
  989. s.appendf("<%s>", resultName);
  990. tail.appendf("</%s>", resultName);
  991. }
  992. else
  993. {
  994. s.appendf("<Result_%d>", sequence+1);
  995. tail.appendf("</Result_%d>", sequence+1);
  996. }
  997. tail.appendf("</Row>\n</Dataset>\n");
  998. }
  999. else if (!isRaw)
  1000. {
  1001. tail.clear().append('\n');
  1002. }
  1003. }
  1004. }
  1005. void FlushingStringBuffer::incrementRowCount()
  1006. {
  1007. CriticalBlock b(crit);
  1008. rowCount++;
  1009. }
  1010. void FlushingJsonBuffer::encodeXML(const char *x, unsigned flags, unsigned len, bool utf8)
  1011. {
  1012. CriticalBlock b(crit);
  1013. appendJSONStringValue(s, NULL, len, x, true);
  1014. }
  1015. void FlushingJsonBuffer::startDataset(const char *elementName, const char *resultName, unsigned sequence, bool _extend)
  1016. {
  1017. CriticalBlock b(crit);
  1018. extend = _extend;
  1019. if (isEmpty || !extend)
  1020. {
  1021. name.clear().append(resultName ? resultName : elementName);
  1022. sequenceNumber = 0;
  1023. startBlock();
  1024. if (!isBlocked)
  1025. {
  1026. StringBuffer seqName;
  1027. if (!resultName || !*resultName)
  1028. resultName = seqName.appendf("result_%d", sequence+1).str();
  1029. appendJSONName(s, resultName).append('{');
  1030. tail.set("}");
  1031. }
  1032. isEmpty = false;
  1033. }
  1034. }
  1035. void FlushingJsonBuffer::startScalar(const char *resultName, unsigned sequence)
  1036. {
  1037. CriticalBlock b(crit);
  1038. assertex(!s.length());
  1039. name.set(resultName ? resultName : "Dataset");
  1040. sequenceNumber = 0;
  1041. startBlock();
  1042. if (!isBlocked)
  1043. {
  1044. StringBuffer seqName;
  1045. if (!resultName || !*resultName)
  1046. resultName = seqName.appendf("Result_%d", sequence+1).str();
  1047. appendJSONName(s, resultName).append('{');
  1048. appendJSONName(s, "Row").append("[{");
  1049. appendJSONName(s, resultName);
  1050. tail.set("}]}");
  1051. }
  1052. }
  1053. //=====================================================================================================
  1054. ClusterWriteHandler::ClusterWriteHandler(char const * _logicalName, char const * _activityType)
  1055. : logicalName(_logicalName), activityType(_activityType)
  1056. {
  1057. makePhysicalPartName(logicalName.get(), 1, 1, physicalName, false);
  1058. splitFilename(physicalName, &physicalDir, &physicalDir, &physicalBase, &physicalBase);
  1059. }
  1060. void ClusterWriteHandler::addCluster(char const * cluster)
  1061. {
  1062. Owned<IGroup> group = queryNamedGroupStore().lookup(cluster);
  1063. if (!group)
  1064. throw MakeStringException(0, "Unknown cluster %s while writing file %s", cluster, logicalName.get());
  1065. if (group->isMember())
  1066. {
  1067. if (localCluster)
  1068. throw MakeStringException(0, "Cluster %s occupies node already specified while writing file %s", cluster,
  1069. logicalName.get());
  1070. localClusterName.set(cluster);
  1071. localCluster.set(group);
  1072. }
  1073. else
  1074. {
  1075. ForEachItemIn(idx, remoteNodes)
  1076. {
  1077. Owned<INode> other = remoteNodes.item(idx).getNode(0);
  1078. if (group->isMember(other))
  1079. throw MakeStringException(0, "Cluster %s occupies node already specified while writing file %s",
  1080. cluster, logicalName.get());
  1081. }
  1082. remoteNodes.append(*group.getClear());
  1083. remoteClusters.append(cluster);
  1084. }
  1085. }
  1086. void ClusterWriteHandler::getLocalPhysicalFilename(StringAttr & out) const
  1087. {
  1088. if(localCluster.get())
  1089. out.set(physicalName.str());
  1090. else
  1091. getTempFilename(out);
  1092. PROGLOG("%s(CLUSTER) for logical filename %s writing to local file %s", activityType.get(), logicalName.get(), out.get());
  1093. }
  1094. void ClusterWriteHandler::splitPhysicalFilename(StringBuffer & dir, StringBuffer & base) const
  1095. {
  1096. dir.append(physicalDir);
  1097. base.append(physicalBase);
  1098. }
  1099. void ClusterWriteHandler::getTempFilename(StringAttr & out) const
  1100. {
  1101. // Should be implemented by more derived (platform-specific) class, if needed
  1102. throwUnexpected();
  1103. }
  1104. void ClusterWriteHandler::copyPhysical(IFile * source, bool noCopy) const
  1105. {
  1106. RemoteFilename rdn, rfn;
  1107. rdn.setLocalPath(physicalDir.str());
  1108. rfn.setLocalPath(physicalName.str());
  1109. ForEachItemIn(idx, remoteNodes)
  1110. {
  1111. rdn.setEp(remoteNodes.item(idx).queryNode(0).endpoint());
  1112. rfn.setEp(remoteNodes.item(idx).queryNode(0).endpoint());
  1113. Owned<IFile> targetdir = createIFile(rdn);
  1114. Owned<IFile> target = createIFile(rfn);
  1115. PROGLOG("%s(CLUSTER) for logical filename %s copying %s to %s", activityType.get(), logicalName.get(), source->queryFilename(), target->queryFilename());
  1116. if(noCopy)
  1117. {
  1118. WARNLOG("Skipping remote copy due to debug option");
  1119. }
  1120. else
  1121. {
  1122. targetdir->createDirectory();
  1123. copyFile(target, source);
  1124. }
  1125. }
  1126. }
  1127. void ClusterWriteHandler::setDescriptorParts(IFileDescriptor * desc, char const * basename, IPropertyTree * attrs) const
  1128. {
  1129. if(!localCluster.get()&&(remoteNodes.ordinality()==0))
  1130. throw MakeStringException(0, "Attempting to write file to no clusters");
  1131. ClusterPartDiskMapSpec partmap; // will get this from group at some point
  1132. desc->setNumParts(1);
  1133. desc->setPartMask(basename);
  1134. if (localCluster)
  1135. desc->addCluster(localClusterName,localCluster, partmap);
  1136. ForEachItemIn(idx,remoteNodes)
  1137. desc->addCluster(remoteClusters.item(idx),&remoteNodes.item(idx), partmap);
  1138. if (attrs) {
  1139. // need to set part attr
  1140. IPartDescriptor *partdesc = desc->queryPart(0);
  1141. IPropertyTree &pprop = partdesc->queryProperties();
  1142. // bit of a kludge (should really set properties *after* creating part rather than passing prop tree in)
  1143. Owned<IAttributeIterator> ai = attrs->getAttributes();
  1144. ForEach(*ai)
  1145. pprop.setProp(ai->queryName(),ai->queryValue());
  1146. }
  1147. }
  1148. void ClusterWriteHandler::finish(IFile * file) const
  1149. {
  1150. if(!localCluster.get())
  1151. {
  1152. PROGLOG("%s(CLUSTER) for logical filename %s removing temporary file %s", activityType.get(), logicalName.get(), file->queryFilename());
  1153. file->remove();
  1154. }
  1155. }
  1156. void ClusterWriteHandler::getClusters(StringArray &clusters) const
  1157. {
  1158. if(localCluster)
  1159. clusters.append(localClusterName);
  1160. ForEachItemIn(c, remoteClusters)
  1161. clusters.append(remoteClusters.item(c));
  1162. }
  1163. //=====================================================================================================
  1164. class COrderedOutputSerializer : implements IOrderedOutputSerializer, public CInterface
  1165. {
  1166. class COrderedResult : public CInterface
  1167. {
  1168. bool closed;
  1169. StringBuffer sb;
  1170. public:
  1171. IMPLEMENT_IINTERFACE;
  1172. COrderedResult() : closed(false) {}
  1173. bool flush(FILE * outFile, bool onlyClosed)
  1174. {
  1175. if (closed || !onlyClosed)
  1176. {
  1177. if (sb.length())
  1178. {
  1179. ::fwrite(sb.str(), sb.length(), 1, outFile);
  1180. sb.clear();
  1181. }
  1182. }
  1183. return closed;
  1184. }
  1185. size32_t printf(const char *format, va_list args)
  1186. {
  1187. if (closed)
  1188. throw MakeStringException(0, "Attempting to append to previously closed result in COrderedResult::printf");
  1189. int prevLen = sb.length();
  1190. sb.valist_appendf(format, args);
  1191. return sb.length() - prevLen;
  1192. }
  1193. size32_t fwrite(const void * data, size32_t size, size32_t count)
  1194. {
  1195. if (closed)
  1196. throw MakeStringException(0, "Attempting to append to previously closed result in COrderedResult::fwrite");
  1197. size32_t len = size * count;
  1198. sb.append(len, (const char *)data);
  1199. return len;
  1200. }
  1201. void close(bool nl)
  1202. {
  1203. if (closed)
  1204. throw MakeStringException(0, "Attempting to reclose result in COrderedResult::close");
  1205. if (nl)
  1206. sb.append('\n');
  1207. closed = true;
  1208. }
  1209. };
  1210. CIArrayOf<COrderedResult> COrderedResultArr;
  1211. int lastSeqFlushed;
  1212. FILE * outFile;
  1213. CriticalSection crit;
  1214. COrderedResult * getResult(size32_t seq)
  1215. {
  1216. while ((int)COrderedResultArr.ordinality() < (seq+1))
  1217. COrderedResultArr.append(*(new COrderedResult()));
  1218. return &COrderedResultArr.item(seq);
  1219. }
  1220. void flushCurrent()//stream current sequence
  1221. {
  1222. COrderedResult &res = COrderedResultArr.item(lastSeqFlushed + 1);
  1223. res.flush(outFile,false);
  1224. fflush(outFile);
  1225. }
  1226. void flushCompleted(bool onlyClosed)//flush completed sequence(s)
  1227. {
  1228. int lastSeq = (int)COrderedResultArr.ordinality()-1;
  1229. for (; lastSeqFlushed < lastSeq; lastSeqFlushed++)
  1230. {
  1231. COrderedResult &res = COrderedResultArr.item(lastSeqFlushed + 1);
  1232. if (!res.flush(outFile,onlyClosed) && onlyClosed)
  1233. break;
  1234. }
  1235. fflush(outFile);
  1236. }
  1237. public:
  1238. IMPLEMENT_IINTERFACE;
  1239. COrderedOutputSerializer(FILE* _outFile) : lastSeqFlushed(-1), outFile(_outFile) {}
  1240. ~COrderedOutputSerializer()
  1241. {
  1242. if (lastSeqFlushed != (COrderedResultArr.ordinality()-1))
  1243. flushCompleted(false);
  1244. COrderedResultArr.kill();
  1245. }
  1246. //IOrderedOutputSerializer
  1247. size32_t fwrite(int seq, const void * data, size32_t size, size32_t count)
  1248. {
  1249. CriticalBlock c(crit);
  1250. size32_t ret = getResult(seq)->fwrite(data,size, count);
  1251. if (seq == (lastSeqFlushed + 1))
  1252. flushCurrent();
  1253. return ret;
  1254. }
  1255. size32_t printf(int seq, const char *format, ...) __attribute__((format(printf, 3, 4)))
  1256. {
  1257. CriticalBlock c(crit);
  1258. va_list args;
  1259. va_start(args, format);
  1260. int ret = getResult(seq)->printf(format, args);
  1261. va_end(args);
  1262. if (seq == (lastSeqFlushed + 1))
  1263. flushCurrent();
  1264. return ret;
  1265. }
  1266. void close(int seq, bool nl)
  1267. {
  1268. CriticalBlock c(crit);
  1269. getResult(seq)->close(nl);
  1270. if ( seq == (lastSeqFlushed+1) )
  1271. flushCompleted(true);
  1272. }
  1273. };
  1274. IOrderedOutputSerializer * createOrderedOutputSerializer(FILE * _outFile)
  1275. {
  1276. return new COrderedOutputSerializer(_outFile);
  1277. }
  1278. //=====================================================================================================
  1279. StringBuffer & mangleHelperFileName(StringBuffer & out, const char * in, const char * wuid, unsigned int flags)
  1280. {
  1281. out = in;
  1282. if (flags & (TDXtemporary | TDXjobtemp))
  1283. out.append("__").append(wuid);
  1284. return out;
  1285. }
  1286. StringBuffer & mangleLocalTempFilename(StringBuffer & out, char const * in)
  1287. {
  1288. char const * start = in;
  1289. while(true)
  1290. {
  1291. char const * end = strstr(start, "::");
  1292. if(end)
  1293. {
  1294. out.append(end-start, start).append("__scope__");
  1295. start = end + 2;
  1296. }
  1297. else
  1298. {
  1299. out.append(start);
  1300. break;
  1301. }
  1302. }
  1303. return out;
  1304. }
  1305. StringBuffer & expandLogicalFilename(StringBuffer & logicalName, const char * fname, IConstWorkUnit * wu, bool resolveLocally)
  1306. {
  1307. if (fname[0]=='~')
  1308. logicalName.append(fname+1);
  1309. else if (resolveLocally)
  1310. {
  1311. StringBuffer sb(fname);
  1312. sb.replaceString("::",PATHSEPSTR);
  1313. makeAbsolutePath(sb.str(), logicalName.clear());
  1314. }
  1315. else
  1316. {
  1317. SCMStringBuffer lfn;
  1318. if (wu)
  1319. {
  1320. wu->getScope(lfn);
  1321. if(lfn.length())
  1322. logicalName.append(lfn.s).append("::");
  1323. }
  1324. logicalName.append(fname);
  1325. }
  1326. return logicalName;
  1327. }