thorsoapcall.cpp 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907
  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 "jliball.hpp"
  14. #include "jqueue.tpp"
  15. #include "jisem.hpp"
  16. #include "thorxmlread.hpp"
  17. #include "thorxmlwrite.hpp"
  18. #include "thorcommon.ipp"
  19. #include "thorsoapcall.hpp"
  20. #include "securesocket.hpp"
  21. #include "eclrtl.hpp"
  22. #include "roxiemem.hpp"
  23. using roxiemem::OwnedRoxieString;
  24. #ifndef _WIN32
  25. #include <stdexcept>
  26. #endif
  27. #include <new>
  28. #define CONTENT_LENGTH "Content-Length: "
  29. unsigned soapTraceLevel = 1;
  30. #define WSCBUFFERSIZE 0x10000
  31. #define MAXWSCTHREADS 50 //Max Web Service Call Threads
  32. interface IReceivedRoxieException : extends IException
  33. {
  34. public:
  35. virtual const void *errorRow() = 0;
  36. };
  37. #define EXCEPTION_PREFIX "ReceivedRoxieException:"
  38. class ReceivedRoxieException: public CInterface, public IReceivedRoxieException
  39. {
  40. public:
  41. IMPLEMENT_IINTERFACE;
  42. ReceivedRoxieException(int code, const char *_msg, const void *_row=NULL) : errcode(code), msg(_msg), row(_row) { };
  43. int errorCode() const { return (errcode); };
  44. StringBuffer & errorMessage(StringBuffer &str) const
  45. {
  46. if (strncmp(str.str(), EXCEPTION_PREFIX, strlen(EXCEPTION_PREFIX)) == 0)
  47. str.append(msg);
  48. else
  49. str.append(EXCEPTION_PREFIX).append(" (").append(msg).append(")");
  50. return str;
  51. };
  52. MessageAudience errorAudience() const { return (MSGAUD_user); };
  53. const void *errorRow() { return (row); };
  54. private:
  55. int errcode;
  56. StringAttr msg;
  57. const void *row;
  58. };
  59. //=================================================================================================
  60. class Url : public CInterface, implements IInterface
  61. {
  62. public:
  63. IMPLEMENT_IINTERFACE;
  64. StringBuffer method;
  65. StringBuffer host;
  66. unsigned port;
  67. StringBuffer path;
  68. StringBuffer userPasswordPair;
  69. StringBuffer &getUrlString(StringBuffer &url) const
  70. {
  71. return url.append(method).append("://").append(host).append(":").append(port).append(path);
  72. }
  73. IException *getUrlException(IException *e) const
  74. {
  75. StringBuffer url;
  76. StringBuffer text;
  77. e->errorMessage(text);
  78. rtlAddExceptionTag(text, "url", getUrlString(url).str());
  79. if (text.length() <= 1024)
  80. return MakeStringException(e->errorCode(), "%s", text.str());
  81. else
  82. return MakeStringExceptionDirect(e->errorCode(), text.str());
  83. }
  84. Url() : port(0)
  85. {
  86. }
  87. private:
  88. char translateHex(char hex) {
  89. if(hex >= 'A')
  90. return (hex & 0xdf) - 'A' + 10;
  91. else
  92. return hex - '0';
  93. }
  94. void userPassword_decode(const char* userpass, StringBuffer& result)
  95. {
  96. if(!userpass || !*userpass)
  97. return;
  98. const char *finger = userpass;
  99. while (*finger)
  100. {
  101. char c = *finger++;
  102. if (c == '%')
  103. {
  104. if(*finger != '\0')
  105. {
  106. c = translateHex(*finger);
  107. finger++;
  108. }
  109. if(*finger != '\0')
  110. {
  111. c = (char)(c*16 + translateHex(*finger));
  112. finger++;
  113. }
  114. }
  115. result.append(c);
  116. }
  117. return;
  118. }
  119. public:
  120. Url(char *urltext)
  121. {
  122. char *p;
  123. if ((p = strstr(urltext, "://")) != NULL)
  124. {
  125. *p = 0;
  126. p += 3; // skip past the colon-slash-slash
  127. method.append(urltext);
  128. urltext = p;
  129. }
  130. else
  131. throw MakeStringException(-1, "Malformed URL");
  132. if ((p = strchr(urltext, '@')) != NULL)
  133. {
  134. // extract username & password
  135. *p = 0;
  136. p++;
  137. userPassword_decode(urltext, userPasswordPair);
  138. urltext = p;
  139. }
  140. if ((p = strchr(urltext, ':')) != NULL)
  141. {
  142. // extract the port
  143. *p = 0;
  144. p++;
  145. port = atoi(p);
  146. host.append(urltext);
  147. if ((p = strchr(p, '/')) != NULL)
  148. path.append(p);
  149. else
  150. path.append("/");
  151. }
  152. else
  153. {
  154. // no port - look at method for port
  155. if (stricmp(method.str(), "https") == 0)
  156. port = 443;
  157. else if (stricmp(method.str(), "http") == 0)
  158. port = 80;
  159. else
  160. throw MakeStringException(-1, "Unsupported access method");
  161. if ((p = strchr(urltext, '/')) != NULL)
  162. {
  163. *p = 0;
  164. p++;
  165. host.append(urltext);
  166. path.append("/").append(p);
  167. }
  168. else
  169. {
  170. host.append(urltext);
  171. path.append("/");
  172. }
  173. }
  174. IpAddress ipaddr(host);
  175. if ( ipaddr.isNull())
  176. throw MakeStringException(-1, "Invalid IP address %s", host.str());
  177. }
  178. };
  179. typedef IArrayOf<Url> UrlArray;
  180. //=================================================================================================
  181. //MORE: This whole class should really be replaced with a single function, avoiding at least one string clone.
  182. class UrlListParser
  183. {
  184. public:
  185. UrlListParser(const char * text)
  186. {
  187. fullText = text ? strdup(text) : NULL;
  188. }
  189. ~UrlListParser()
  190. {
  191. free(fullText);
  192. }
  193. unsigned getUrls(UrlArray &array)
  194. {
  195. if (fullText)
  196. {
  197. char *copyFullText = strdup(fullText);
  198. char *saveptr;
  199. char *url = strtok_r(copyFullText, "|", &saveptr);
  200. while (url != NULL)
  201. {
  202. array.append(*new Url(url));
  203. url = strtok_r(NULL, "|", &saveptr);
  204. }
  205. free(copyFullText);
  206. }
  207. return array.ordinality();
  208. }
  209. private:
  210. char *fullText;
  211. };
  212. //=================================================================================================
  213. #define BLACKLIST_RETRIES 10
  214. #define ROXIE_ABORT_EVENT 1407
  215. #define TIMELIMIT_EXCEEDED 1408
  216. class BlackLister : public CInterface, implements IThreadFactory
  217. {
  218. SocketEndpointArray list;
  219. Owned<IThreadPool> pool;
  220. CriticalSection crit;
  221. private:
  222. inline void checkRoxieAbortMonitor(IRoxieAbortMonitor * roxieAbortMonitor)
  223. {
  224. if (roxieAbortMonitor)
  225. {
  226. try
  227. {
  228. roxieAbortMonitor->checkForAbort();//throws
  229. }
  230. catch (IException *e)
  231. {
  232. StringBuffer s;
  233. throw MakeStringException(ROXIE_ABORT_EVENT, "%s", e->errorMessage(s).str());
  234. }
  235. }
  236. }
  237. public:
  238. bool lookup(SocketEndpoint &ep, const IContextLogger &logctx)
  239. {
  240. CriticalBlock b(crit);
  241. if (list.find(ep)!=NotFound)
  242. {
  243. if (soapTraceLevel > 3)
  244. {
  245. StringBuffer s;
  246. logctx.CTXLOG("socket %s is blacklisted", ep.getUrlStr(s).str());
  247. }
  248. return true;
  249. }
  250. return false;
  251. }
  252. void blacklist(SocketEndpoint &ep, const IContextLogger &logctx)
  253. {
  254. CriticalBlock b(crit);
  255. if (list.find(ep)==NotFound)
  256. {
  257. if (soapTraceLevel > 0)
  258. {
  259. StringBuffer s;
  260. logctx.CTXLOG("Blacklisting socket %s", ep.getUrlStr(s).str());
  261. }
  262. list.append(ep);
  263. pool->start(&ep);
  264. }
  265. }
  266. void deblacklist(SocketEndpoint &ep)
  267. {
  268. CriticalBlock b(crit);
  269. unsigned idx = list.find(ep);
  270. if (idx!=NotFound)
  271. {
  272. if (soapTraceLevel > 0)
  273. {
  274. StringBuffer s;
  275. DBGLOG("De-blacklisting socket %s", ep.getUrlStr(s).str());
  276. }
  277. list.remove(idx);
  278. }
  279. }
  280. public:
  281. IMPLEMENT_IINTERFACE;
  282. BlackLister()
  283. {
  284. pool.setown(createThreadPool("SocketBlacklistPool", this, NULL, 0, 0));
  285. }
  286. ISocket* connect(SocketEndpoint &ep,
  287. const IContextLogger &logctx,
  288. unsigned retries,
  289. unsigned timeoutMS,
  290. IRoxieAbortMonitor * roxieAbortMonitor)
  291. {
  292. if (lookup(ep, logctx))
  293. {
  294. StringBuffer s;
  295. ep.getUrlStr(s);
  296. throw MakeStringException(-1, "blacklisted socket %s", s.str());
  297. }
  298. Owned<IException> exc;
  299. try
  300. {
  301. checkRoxieAbortMonitor(roxieAbortMonitor);
  302. Owned<ISocket> sock;
  303. Owned<ISocketConnectWait> scw = nonBlockingConnect(ep, timeoutMS == WAIT_FOREVER ? 60000 : timeoutMS*(retries+1));
  304. loop
  305. {
  306. sock.setown(scw->wait(1000));//throws if connect fails or timeoutMS
  307. checkRoxieAbortMonitor(roxieAbortMonitor);
  308. if (sock)
  309. return sock.getLink();
  310. }
  311. }
  312. catch (IJSOCK_Exception *e)
  313. {
  314. EXCLOG(e,"BlackLister::connect");
  315. if (exc)
  316. e->Release();
  317. else
  318. exc.setown(e);
  319. }
  320. blacklist(ep, logctx);
  321. if (exc->errorCode()==JSOCKERR_connection_failed) {
  322. StringBuffer s;
  323. ep.getUrlStr(s);
  324. throw MakeStringException(JSOCKERR_connection_failed, "connection failed %s", s.str());
  325. }
  326. throw exc.getClear();
  327. return NULL;
  328. }
  329. bool blacklisted (unsigned short port, char const* host)
  330. {
  331. SocketEndpoint ep(host, port);
  332. return (list.find(ep)!=NotFound);
  333. }
  334. ISocket* connect(unsigned short port,
  335. char const* host,
  336. const IContextLogger &logctx,
  337. unsigned retries,
  338. unsigned timeoutMS,
  339. IRoxieAbortMonitor * roxieAbortMonitor )
  340. {
  341. SocketEndpoint ep(host, port);
  342. return connect(ep, logctx, retries, timeoutMS, roxieAbortMonitor);
  343. }
  344. virtual IPooledThread *createNew()
  345. {
  346. class SocketDeblacklister : public CInterface, implements IPooledThread
  347. {
  348. SocketEndpoint ep;
  349. BlackLister &parent;
  350. Semaphore stopped;
  351. public:
  352. IMPLEMENT_IINTERFACE;
  353. SocketDeblacklister(BlackLister &_parent): parent(_parent)
  354. {
  355. }
  356. ~SocketDeblacklister()
  357. {
  358. }
  359. virtual void init(void *param)
  360. {
  361. ep.set(*(SocketEndpoint *) param);
  362. }
  363. virtual void main()
  364. {
  365. unsigned delay = 5000;
  366. for (unsigned i = 0; i < BLACKLIST_RETRIES; i++)
  367. {
  368. try
  369. {
  370. Owned<ISocket> s = ISocket::connect_timeout(ep, 10000);
  371. s->close();
  372. break;
  373. }
  374. catch (IJSOCK_Exception *E)
  375. {
  376. // EXCLOG(E, "While updating socket blacklist"); // MORE - may need to downgrade if this fires traps
  377. E->Release();
  378. if (stopped.wait(delay))
  379. return;
  380. delay += delay;
  381. }
  382. }
  383. parent.deblacklist(ep);
  384. }
  385. virtual bool stop()
  386. {
  387. stopped.signal();
  388. return true;
  389. }
  390. virtual bool canReuse() { return true; }
  391. };
  392. return new SocketDeblacklister(*this);
  393. }
  394. void stop()
  395. {
  396. pool->stopAll();
  397. }
  398. } *blacklist;
  399. MODULE_INIT(INIT_PRIORITY_STANDARD)
  400. {
  401. blacklist = new BlackLister;
  402. return true;
  403. }
  404. MODULE_EXIT()
  405. {
  406. blacklist->stop();
  407. delete blacklist;
  408. }
  409. //=================================================================================================
  410. class ColumnProvider : public CInterface, public IColumnProvider
  411. {
  412. public:
  413. ColumnProvider(unsigned _callLatencyMs) : callLatencyMs(_callLatencyMs), base(NULL) {}
  414. IMPLEMENT_IINTERFACE;
  415. virtual bool getBool(const char * path) { return base->getBool(path); }
  416. virtual void getData(size32_t len, void * text, const char * path) { base->getData(len, text, path); }
  417. virtual void getDataX(size32_t & len, void * & text, const char * path) { base->getDataX(len, text, path); }
  418. virtual __int64 getInt(const char * path)
  419. {
  420. __int64 ret = base->getInt(path);
  421. if((ret==0) && path && *path=='_')
  422. {
  423. if (stricmp(path, "_call_latency_ms")==0)
  424. ret = callLatencyMs;
  425. else if (stricmp(path, "_call_latency")==0)
  426. ret = (callLatencyMs + 500) / 1000;
  427. }
  428. return ret;
  429. }
  430. virtual void getQString(size32_t len, char * text, const char * path) { base->getQString(len, text, path); }
  431. virtual void getString(size32_t len, char * text, const char * path) { base->getString(len, text, path); }
  432. virtual void getStringX(size32_t & len, char * & text, const char * path) { base->getStringX(len, text, path); }
  433. virtual void getUnicodeX(size32_t & len, UChar * & text, const char * path) { base->getUnicodeX(len, text, path); }
  434. virtual bool getIsSetAll(const char * path) { return base->getIsSetAll(path); }
  435. virtual IColumnProviderIterator * getChildIterator(const char * path) { return base->getChildIterator(path); }
  436. virtual void getUtf8X(size32_t & len, char * & text, const char * path) { base->getUtf8X(len, text, path); }
  437. virtual bool readBool(const char * path, bool _default) { return base->readBool(path, _default); }
  438. virtual void readData(size32_t len, void * text, const char * path, size32_t _lenDefault, const void * _default) { base->readData(len, text, path, _lenDefault, _default); }
  439. virtual void readDataX(size32_t & len, void * & text, const char * path, size32_t _lenDefault, const void * _default) { base->readDataX(len, text, path, _lenDefault, _default); }
  440. virtual __int64 readInt(const char * path, __int64 _default)
  441. {
  442. if(path && *path=='_')
  443. {
  444. if (stricmp(path, "_call_latency_ms")==0)
  445. return callLatencyMs;
  446. else if (stricmp(path, "_call_latency")==0)
  447. return (callLatencyMs + 500) / 1000;
  448. }
  449. return base->readInt(path, _default);
  450. }
  451. virtual void readQString(size32_t len, char * text, const char * path, size32_t _lenDefault, const char * _default) { base->readQString(len, text, path, _lenDefault, _default); }
  452. virtual void readString(size32_t len, char * text, const char * path, size32_t _lenDefault, const char * _default) { base->readString(len, text, path, _lenDefault, _default); }
  453. virtual void readStringX(size32_t & len, char * & text, const char * path, size32_t _lenDefault, const char * _default) { base->readStringX(len, text, path, _lenDefault, _default); }
  454. virtual void readUnicodeX(size32_t & len, UChar * & text, const char * path, size32_t _lenDefault, const UChar * _default) { base->readUnicodeX(len, text, path, _lenDefault, _default); }
  455. virtual bool readIsSetAll(const char * path, bool _default) { return base->readIsSetAll(path, _default); }
  456. virtual void readUtf8X(size32_t & len, char * & text, const char * path, size32_t _lenDefault, const char * _default) { base->readUtf8X(len, text, path, _lenDefault, _default); }
  457. void setBase(IColumnProvider * _base) { base = _base; }
  458. virtual void getDataRaw(size32_t len, void * text, const char * path) { base->getDataRaw(len, text, path); }
  459. virtual void getDataRawX(size32_t & len, void * & text, const char * path) { base->getDataRawX(len, text, path); }
  460. virtual void readDataRaw(size32_t len, void * text, const char * path, size32_t _lenDefault, const void * _default) { base->readDataRaw(len, text, path, _lenDefault, _default); }
  461. virtual void readDataRawX(size32_t & len, void * & text, const char * path, size32_t _lenDefault, const void * _default) { base->readDataRawX(len, text, path, _lenDefault, _default); }
  462. protected:
  463. IColumnProvider * base;
  464. private:
  465. unsigned callLatencyMs;
  466. };
  467. //=================================================================================================
  468. //Same as ColumnProvider, except returns data as hex64Binary instead of 16 bit hex
  469. class ColumnProviderData64 : public ColumnProvider
  470. {
  471. public:
  472. ColumnProviderData64(unsigned _callLatencyMs) : ColumnProvider(_callLatencyMs) {}
  473. virtual void getData(size32_t len, void * text, const char * path) { ColumnProvider::getDataRaw(len, text, path); }
  474. virtual void getDataX(size32_t & len, void * & text, const char * path) { ColumnProvider::getDataRawX(len, text, path); }
  475. virtual void readData(size32_t len, void * text, const char * path, size32_t _lenDefault, const void * _default) { ColumnProvider::readDataRaw(len, text, path, _lenDefault, _default); }
  476. virtual void readDataX(size32_t len, void * text, const char * path, size32_t _lenDefault, const void * _default) { ColumnProvider::readDataRawX(len, text, path, _lenDefault, _default); }
  477. };
  478. //=================================================================================================
  479. IColumnProvider * CreateColumnProvider(unsigned _callLatencyMs, bool _encoding)
  480. {
  481. if (!_encoding)
  482. return new ColumnProvider(_callLatencyMs);
  483. else
  484. return new ColumnProviderData64(_callLatencyMs);
  485. }
  486. //=================================================================================================
  487. enum WSCType{STsoap, SThttp} ; //web service call type
  488. //Web Services Call Asynchronous For
  489. interface IWSCAsyncFor: public IInterface
  490. {
  491. virtual void processException(const Url &url, const void *row, IException *e) = 0;
  492. virtual void processException(const Url &url, ConstPointerArray &inputRows, IException *e) = 0;
  493. virtual void checkTimeLimitExceeded(unsigned * _remainingMS) = 0;
  494. virtual void createHttpRequest(Url &url, StringBuffer &request) = 0;
  495. virtual int readHttpResponse(StringBuffer &response, ISocket *socket) = 0;
  496. virtual void processResponse(Url &url, StringBuffer &response, ColumnProvider * meta) = 0;
  497. virtual StringBuffer getResponsePath() = 0;
  498. virtual ConstPointerArray & getInputRows() = 0;
  499. virtual IWSCHelper * getMaster() = 0;
  500. virtual IEngineRowAllocator * getOutputAllocator() = 0;
  501. virtual void For(unsigned num,unsigned maxatonce,bool abortFollowingException=false,bool shuffled=false) = 0;
  502. virtual void Do(unsigned idx=0)=0;
  503. };
  504. class CWSCHelper;
  505. IWSCAsyncFor * createWSCAsyncFor(CWSCHelper * _master, CommonXmlWriter &_xmlWriter, ConstPointerArray &_inputRows, PTreeReaderOptions _options);
  506. //=================================================================================================
  507. class CMatchCB : public CInterface, implements IXMLSelect
  508. {
  509. IWSCAsyncFor &parent;
  510. const Url &url;
  511. StringAttr tail;
  512. ColumnProvider * meta;
  513. public:
  514. IMPLEMENT_IINTERFACE;
  515. CMatchCB(IWSCAsyncFor &_parent, const Url &_url, const char *_tail, ColumnProvider * _meta) : parent(_parent), url(_url), tail(_tail), meta(_meta)
  516. {
  517. }
  518. virtual void match(IColumnProvider &entry, offset_t startOffset, offset_t endOffset)
  519. {
  520. Owned<IException> e;
  521. if (tail.length())
  522. {
  523. StringBuffer path(parent.getResponsePath());
  524. unsigned idx = (unsigned)entry.getInt(path.append("/@sequence").str());
  525. Owned<IColumnProviderIterator> excIter = entry.getChildIterator("Exception");
  526. IColumnProvider *excptEntry = excIter->first();
  527. if (excptEntry)
  528. {
  529. int code = (int)excptEntry->getInt("Code");
  530. size32_t len;
  531. char *message;
  532. excptEntry->getStringX(len, message, "Message");
  533. StringBuffer mstr(len, message);
  534. rtlFree(message);
  535. DBGLOG("Roxie exception: %s", mstr.str());
  536. e.setown(new ReceivedRoxieException(code, mstr.str()));
  537. parent.processException(url, parent.getInputRows().item(idx), e.getLink());
  538. }
  539. }
  540. if (parent.getMaster()->getRowTransformer() && !e)
  541. {
  542. IEngineRowAllocator * outputAllocator = parent.getOutputAllocator();
  543. Owned<IColumnProviderIterator> iter = entry.getChildIterator(tail);
  544. IColumnProvider *rowEntry = iter->first();
  545. while (rowEntry)
  546. {
  547. RtlDynamicRowBuilder rowBuilder(outputAllocator);
  548. size32_t sizeGot;
  549. if(meta)
  550. {
  551. meta->setBase(rowEntry);
  552. sizeGot = parent.getMaster()->transformRow(rowBuilder, meta);
  553. }
  554. else
  555. {
  556. sizeGot = parent.getMaster()->transformRow(rowBuilder, rowEntry);
  557. }
  558. if (sizeGot > 0)
  559. parent.getMaster()->putRow(rowBuilder.finalizeRowClear(sizeGot));
  560. rowEntry = iter->next();
  561. }
  562. }
  563. }
  564. };
  565. //=================================================================================================
  566. bool isValidHttpValue(char const * in)
  567. {
  568. for (const byte * ptr = (byte*)in; *ptr; ++ptr)
  569. if (((*ptr <= '\x1F') && (*ptr != '\x09')) || (*ptr == '\x7F'))
  570. return false;
  571. return true;
  572. }
  573. //=================================================================================================
  574. //Web Service Call helper thread
  575. class CWSCHelperThread : public Thread
  576. {
  577. private:
  578. CWSCHelper * master;
  579. virtual void outputXmlRows(CommonXmlWriter &xmlWriter, ConstPointerArray &inputRows, const char *itemtag=NULL, bool encode_off=false, char const * itemns = NULL);
  580. virtual void createESPQuery(CommonXmlWriter &xmlWriter, ConstPointerArray &inputRows);
  581. virtual void createSOAPliteralOrEncodedQuery(CommonXmlWriter &xmlWriter, ConstPointerArray &inputRows);
  582. virtual void createXmlSoapQuery(CommonXmlWriter &xmlWriter, ConstPointerArray &inputRows);
  583. virtual void processQuery(ConstPointerArray &inputRows);
  584. //Thread
  585. virtual int run();
  586. public:
  587. CWSCHelperThread(CWSCHelper * _master) : Thread("CWSCHelperThread")
  588. {
  589. master = _master;
  590. }
  591. ~CWSCHelperThread()
  592. {
  593. }
  594. };
  595. //=================================================================================================
  596. class CWSCHelper : public CInterface, implements IWSCHelper
  597. {
  598. private:
  599. SimpleInterThreadQueueOf<const void, true> outputQ;
  600. SpinLock outputQLock;
  601. CriticalSection toXmlCrit, transformCrit, onfailCrit, timeoutCrit;
  602. unsigned done;
  603. Linked<ClientCertificate> clientCert;
  604. static CriticalSection secureContextCrit;
  605. static Owned<ISecureSocketContext> secureContext;
  606. CTimeMon timeLimitMon;
  607. bool complete, timeLimitExceeded;
  608. IRoxieAbortMonitor * roxieAbortMonitor;
  609. protected:
  610. CIArrayOf<CWSCHelperThread> threads;
  611. WSCType wscType;
  612. public:
  613. IMPLEMENT_IINTERFACE;
  614. CWSCHelper(IWSCRowProvider *_rowProvider, IEngineRowAllocator * _outputAllocator, const char *_authToken, WSCMode _wscMode, ClientCertificate *_clientCert, const IContextLogger &_logctx, IRoxieAbortMonitor *_roxieAbortMonitor, WSCType _wscType)
  615. : logctx(_logctx), outputAllocator(_outputAllocator), clientCert(_clientCert), roxieAbortMonitor(_roxieAbortMonitor)
  616. {
  617. wscMode = _wscMode;
  618. wscType = _wscType;
  619. done = 0;
  620. complete = aborted = timeLimitExceeded = false;
  621. rowProvider = _rowProvider;
  622. helper = rowProvider->queryActionHelper();
  623. callHelper = rowProvider->queryCallHelper(); //MORE: This should not be done this way!! Should use extra as below.
  624. helperExtra = static_cast<IHThorSoapCallExtra*>(helper->selectInterface(TAIsoapcallextra_1));
  625. flags = helper->getFlags();
  626. OwnedRoxieString s;
  627. authToken.append(_authToken);
  628. if (helper->numRetries() < 0)
  629. maxRetries = 3; // default to 3 retries
  630. else
  631. maxRetries = helper->numRetries();
  632. //Allow all of these options to be specified separately. Possibly useful, and the code is cleaner.
  633. logMin = (flags & SOAPFlogmin) != 0;
  634. logXML = (flags & SOAPFlog) != 0;
  635. logUserMsg = (flags & SOAPFlogusermsg) != 0;
  636. double dval = helper->getTimeout(); // In seconds, but may include fractions of a second...
  637. if (dval < 0.0) //not provided, or out of range
  638. timeoutMS = 300*1000; // 300 second default
  639. else if (dval == 0)
  640. timeoutMS = WAIT_FOREVER;
  641. else
  642. timeoutMS = (unsigned)(dval * 1000);
  643. dval = helper->getTimeLimit();
  644. if (dval <= 0.0)
  645. timeLimitMS = WAIT_FOREVER;
  646. else
  647. timeLimitMS = (unsigned)(dval * 1000);
  648. if (wscType == STsoap)
  649. {
  650. soapaction.set(s.setown(helper->getSoapAction()));
  651. if(soapaction.get() && !isValidHttpValue(soapaction.get()))
  652. throw MakeStringException(-1, "SOAPAction value contained illegal characters: %s", soapaction.get());
  653. httpHeaderName.set(s.setown(helper->getHttpHeaderName()));
  654. if(httpHeaderName.get() && !isValidHttpValue(httpHeaderName.get()))
  655. throw MakeStringException(-1, "HTTPHEADER name contained illegal characters: %s", httpHeaderName.get());
  656. httpHeaderValue.set(s.setown(helper->getHttpHeaderValue()));
  657. if(httpHeaderValue.get() && !isValidHttpValue(httpHeaderValue.get()))
  658. throw MakeStringException(-1, "HTTPHEADER value contained illegal characters: %s", httpHeaderValue.get());
  659. StringAttr proxyAddress;
  660. proxyAddress.set(s.setown(helper->getProxyAddress()));
  661. if (!proxyAddress.isEmpty())
  662. {
  663. UrlListParser proxyUrlListParser(proxyAddress);
  664. if (0 == proxyUrlListParser.getUrls(proxyUrlArray))
  665. throw MakeStringException(0, "SOAPCALL PROXYADDRESS specified no URLs");
  666. }
  667. if ((flags & SOAPFliteral) && (flags & SOAPFencoding))
  668. throw MakeStringException(0, "SOAPCALL 'LITERAL' and 'ENCODING' options are mutually exclusive");
  669. header.set(s.setown(helper->getHeader()));
  670. footer.set(s.setown(helper->getFooter()));
  671. if(flags & SOAPFnamespace)
  672. {
  673. OwnedRoxieString ns = helper->getNamespaceName();
  674. if(ns && *ns)
  675. xmlnamespace.set(ns);
  676. }
  677. }
  678. if (wscType == SThttp)
  679. {
  680. //Check for unsupported flags
  681. if ((flags & SOAPFliteral) || (flags & SOAPFencoding))
  682. throw MakeStringException(0, "HTTPCALL 'LITERAL' and 'ENCODINGD' options not supported");
  683. }
  684. if (callHelper)
  685. {
  686. OwnedRoxieString iteratorPath(callHelper->getInputIteratorPath());
  687. char const * ipath = iteratorPath;
  688. if(ipath && (*ipath == '/'))
  689. ++ipath;
  690. inputpath.set(ipath);
  691. }
  692. service.set(s.setown(helper->getService()));
  693. service.trim();
  694. if (wscType == SThttp)
  695. {
  696. service.toUpperCase(); //GET/PUT/POST
  697. if (strcmp(service.str(), "GET"))
  698. throw MakeStringException(0, "HTTPCALL Only 'GET' service supported");
  699. OwnedRoxieString acceptTypeSupplied(helper->getAcceptType()); // text/html, text/xml, etc
  700. acceptType.set(acceptTypeSupplied);
  701. acceptType.trim();
  702. acceptType.toLowerCase();
  703. }
  704. if (callHelper)
  705. rowTransformer = callHelper->queryInputTransformer();
  706. else
  707. rowTransformer = NULL;
  708. OwnedRoxieString hosts(helper->getHosts());
  709. UrlListParser urlListParser(hosts);
  710. if ((numUrls = urlListParser.getUrls(urlArray)) > 0)
  711. {
  712. if (wscMode == SCrow)
  713. {
  714. numRowThreads = 1;
  715. numUrlThreads = helper->numParallelThreads();
  716. if (numUrlThreads == 0)
  717. numUrlThreads = 1;
  718. else if (numUrlThreads > MAXWSCTHREADS)
  719. numUrlThreads = MAXWSCTHREADS;
  720. numRecordsPerBatch = 1;
  721. }
  722. else
  723. {
  724. unsigned totThreads = helper->numParallelThreads();
  725. if (totThreads < 1)
  726. totThreads = 2; // default to 2 threads
  727. else if (totThreads > MAXWSCTHREADS)
  728. totThreads = MAXWSCTHREADS;
  729. numUrlThreads = (numUrls < totThreads)? numUrls: totThreads;
  730. numRowThreads = totThreads / numUrlThreads;
  731. if (numRowThreads < 1)
  732. numRowThreads = 1;
  733. else if (numRowThreads > MAXWSCTHREADS)
  734. numRowThreads = MAXWSCTHREADS;
  735. numRecordsPerBatch = helper->numRecordsPerBatch();
  736. if (numRecordsPerBatch < 1)
  737. numRecordsPerBatch = 1;
  738. }
  739. }
  740. else
  741. throw MakeStringException(0, "%sCALL specified no URLs",wscType == STsoap ? "SOAP" : "HTTP");
  742. for (unsigned i=0; i<numRowThreads; i++)
  743. threads.append(*new CWSCHelperThread(this));
  744. }
  745. ~CWSCHelper()
  746. {
  747. complete = true;
  748. waitUntilDone();
  749. threads.kill();
  750. }
  751. void waitUntilDone()
  752. {
  753. ForEachItemIn(i,threads)
  754. threads.item(i).join();
  755. loop
  756. {
  757. const void *row = outputQ.dequeueNow();
  758. if (!row)
  759. break;
  760. outputAllocator->releaseRow(row);
  761. }
  762. outputQ.reset();
  763. }
  764. void start()
  765. {
  766. if (timeLimitMS != WAIT_FOREVER)
  767. timeLimitMon.reset(timeLimitMS);
  768. done = 0;
  769. complete = aborted = timeLimitExceeded = false;
  770. ForEachItemIn(i,threads)
  771. threads.item(i).start();
  772. }
  773. void abort()
  774. {
  775. aborted = true;
  776. complete = true;
  777. outputQ.stop();
  778. }
  779. const void * getRow()
  780. {
  781. if (complete)
  782. return NULL;
  783. loop
  784. {
  785. const void *row = outputQ.dequeue();
  786. if (aborted)
  787. break;
  788. if (row)
  789. return row;
  790. // should only be here if setDone() triggered
  791. complete = true;
  792. Owned<IException> e = getError();
  793. if (e)
  794. throw e.getClear();
  795. break;
  796. }
  797. return NULL;
  798. }
  799. IException * getError()
  800. {
  801. SpinBlock sb(outputQLock);
  802. return error.getLink();
  803. }
  804. inline IEngineRowAllocator * queryOutputAllocator() const { return outputAllocator; }
  805. ISecureSocket *createSecureSocket(ISocket *sock)
  806. {
  807. {
  808. CriticalBlock b(secureContextCrit);
  809. if (!secureContext)
  810. {
  811. if (clientCert != NULL)
  812. secureContext.setown(createSecureSocketContextEx(clientCert->certificate, clientCert->privateKey, clientCert->passphrase, ClientSocket));
  813. else
  814. secureContext.setown(createSecureSocketContext(ClientSocket));
  815. }
  816. }
  817. return secureContext->createSecureSocket(sock);
  818. }
  819. bool isTimeLimitExceeded(unsigned *_remainingMS)
  820. {
  821. if (timeLimitMS != WAIT_FOREVER)
  822. {
  823. CriticalBlock block(timeoutCrit);
  824. if (timeLimitExceeded || timeLimitMon.timedout(_remainingMS))
  825. {
  826. timeLimitExceeded = true;
  827. return true;
  828. }
  829. }
  830. else
  831. *_remainingMS = (unsigned)-1;
  832. return false;
  833. }
  834. void addUserLogMsg(const byte * row)
  835. {
  836. if (logUserMsg)
  837. {
  838. size32_t lenText;
  839. rtlDataAttr text;
  840. helperExtra->getLogText(lenText, text.refstr(), row);
  841. logctx.CTXLOG("%s: %.*s", wscCallTypeText(), lenText, text.getstr());
  842. }
  843. }
  844. inline IXmlToRowTransformer * getRowTransformer() { return rowTransformer; }
  845. inline const char * wscCallTypeText() const { return wscType == STsoap ? "SOAPCALL" : "HTTPCALL"; }
  846. protected:
  847. friend class CWSCHelperThread;
  848. friend class CWSCAsyncFor;
  849. void putRow(const void * row)
  850. {
  851. assertex(row);
  852. outputQ.enqueue(row);
  853. }
  854. void setDone()
  855. {
  856. bool doStop;
  857. {
  858. SpinBlock sb(outputQLock);
  859. done++;
  860. doStop = (done == numRowThreads);
  861. }
  862. if (doStop)
  863. {
  864. // Note - Don't stop the queue - that effectively discards what's already on there,
  865. // which is not what we want.
  866. // Instead, push a NULL to indicate the end of the output.
  867. outputQ.enqueue(NULL);
  868. }
  869. }
  870. void setErrorOwn(IException * e)
  871. {
  872. SpinBlock sb(outputQLock);
  873. if (error)
  874. ::Release(e);
  875. else
  876. error.setown(e);
  877. }
  878. void toXML(const byte * self, IXmlWriter & out) { CriticalBlock block(toXmlCrit); helper->toXML(self, out); }
  879. size32_t transformRow(ARowBuilder & rowBuilder, IColumnProvider * row)
  880. {
  881. CriticalBlock block(transformCrit);
  882. NullDiskCallback callback;
  883. return rowTransformer->transform(rowBuilder, row, &callback);
  884. }
  885. unsigned onFailTransform(ARowBuilder & rowBuilder, const void * left, IException * e) { CriticalBlock block(onfailCrit); return callHelper->onFailTransform(rowBuilder, left, e); }
  886. StringBuffer authToken;
  887. WSCMode wscMode;
  888. IWSCRowProvider * rowProvider;
  889. IHThorWebServiceCallActionArg * helper;
  890. IHThorWebServiceCallArg * callHelper;
  891. IHThorWebServiceCallExtra * helperExtra;
  892. Linked<IEngineRowAllocator> outputAllocator;
  893. Owned<IException> error;
  894. UrlArray urlArray;
  895. UrlArray proxyUrlArray;
  896. unsigned numRecordsPerBatch;
  897. unsigned numUrls;
  898. unsigned numRowThreads;
  899. unsigned numUrlThreads;
  900. unsigned maxRetries;
  901. unsigned timeoutMS;
  902. unsigned timeLimitMS;
  903. bool logXML;
  904. bool logMin;
  905. bool logUserMsg;
  906. bool aborted;
  907. const IContextLogger &logctx;
  908. unsigned flags;
  909. StringAttr soapaction;
  910. StringAttr httpHeaderName;
  911. StringAttr httpHeaderValue;
  912. StringAttr inputpath;
  913. StringBuffer service;
  914. StringBuffer acceptType;//for httpcall, text/plain, text/html, text/xml, etc
  915. StringAttr header;
  916. StringAttr footer;
  917. StringAttr xmlnamespace;
  918. IXmlToRowTransformer * rowTransformer;
  919. };
  920. CriticalSection CWSCHelper::secureContextCrit;
  921. Owned<ISecureSocketContext> CWSCHelper::secureContext; // created on first use
  922. //=================================================================================================
  923. void CWSCHelperThread::outputXmlRows(CommonXmlWriter &xmlWriter, ConstPointerArray &inputRows, const char *itemtag, bool encode_off, char const * itemns)
  924. {
  925. ForEachItemIn(idx, inputRows)
  926. {
  927. if (itemtag) //TAG
  928. {
  929. xmlWriter.outputQuoted("<");
  930. xmlWriter.outputQuoted(itemtag);
  931. if(itemns)
  932. {
  933. xmlWriter.outputQuoted(" xmlns=\"");
  934. xmlWriter.outputQuoted(itemns);
  935. xmlWriter.outputQuoted("\"");
  936. }
  937. xmlWriter.outputQuoted(">");
  938. }
  939. if (master->header.get()) //OPTIONAL HEADER (specified by "HEADING" option)
  940. xmlWriter.outputQuoted(master->header.get());
  941. //XML ROW CONTENT
  942. master->toXML((const byte *)inputRows.item(idx), xmlWriter);
  943. if (master->footer.get()) //OPTION FOOTER
  944. xmlWriter.outputQuoted(master->footer.get());
  945. if (encode_off) //ENCODING
  946. xmlWriter.outputQuoted("<encode_>0</encode_>");
  947. if (itemtag) //CLOSE TAG
  948. {
  949. xmlWriter.outputQuoted("</");
  950. xmlWriter.outputQuoted(itemtag);
  951. xmlWriter.outputQuoted(">");
  952. }
  953. master->addUserLogMsg((const byte *)inputRows.item(idx));
  954. }
  955. }
  956. void CWSCHelperThread::createESPQuery(CommonXmlWriter &xmlWriter, ConstPointerArray &inputRows)
  957. {
  958. StringBuffer method_tag;
  959. method_tag.append(master->service).append("Request");
  960. StringAttr method_ns;
  961. if (inputRows.ordinality() > 1)
  962. {
  963. xmlWriter.outputQuoted("<");
  964. xmlWriter.outputQuoted(method_tag.str());
  965. xmlWriter.outputQuoted("Array");
  966. if (master->xmlnamespace.get())
  967. {
  968. xmlWriter.outputQuoted(" xmlns=\"");
  969. xmlWriter.outputQuoted(master->xmlnamespace.get());
  970. xmlWriter.outputQuoted("\"");
  971. }
  972. xmlWriter.outputQuoted(">");
  973. }
  974. else
  975. {
  976. if(master->xmlnamespace.get())
  977. method_ns.set(master->xmlnamespace.get());
  978. }
  979. outputXmlRows(xmlWriter, inputRows, method_tag.str(), (inputRows.ordinality() == 1), method_ns.get());
  980. if (inputRows.ordinality() > 1)
  981. {
  982. xmlWriter.outputQuoted("<encode_>0</encode_>");
  983. xmlWriter.outputQuoted("</");
  984. xmlWriter.outputQuoted(method_tag.str());
  985. xmlWriter.outputQuoted("Array>");
  986. }
  987. }
  988. //Create servce xml request body, with binding usage of either Literal or Encoded
  989. //Note that Encoded usage requires type encoding for data fields
  990. void CWSCHelperThread::createSOAPliteralOrEncodedQuery(CommonXmlWriter &xmlWriter, ConstPointerArray &inputRows)
  991. {
  992. xmlWriter.outputQuoted("<");
  993. xmlWriter.outputQuoted(master->service);
  994. if (master->flags & SOAPFencoding)
  995. xmlWriter.outputQuoted(" soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"");
  996. if (master->xmlnamespace.get())
  997. {
  998. xmlWriter.outputQuoted(" xmlns=\"");
  999. xmlWriter.outputQuoted(master->xmlnamespace.get());
  1000. xmlWriter.outputQuoted("\"");
  1001. }
  1002. xmlWriter.outputQuoted(">");
  1003. outputXmlRows(xmlWriter, inputRows);
  1004. xmlWriter.outputQuoted("</");
  1005. xmlWriter.outputQuoted(master->service);
  1006. xmlWriter.outputQuoted(">");
  1007. }
  1008. //Create SOAP body of http request
  1009. void CWSCHelperThread::createXmlSoapQuery(CommonXmlWriter &xmlWriter, ConstPointerArray &inputRows)
  1010. {
  1011. xmlWriter.outputQuoted("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
  1012. xmlWriter.outputQuoted("<soap:Envelope");
  1013. xmlWriter.outputQuoted(" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"");
  1014. if (master->flags & SOAPFencoding)
  1015. { //SOAP RPC/encoded. 'Encoded' usage includes type encoding
  1016. xmlWriter.outputQuoted(" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"");
  1017. xmlWriter.outputQuoted(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"");
  1018. }
  1019. xmlWriter.outputQuoted(">");
  1020. xmlWriter.outputQuoted("<soap:Body>");
  1021. if (master->flags & SOAPFliteral || master->flags & SOAPFencoding)
  1022. createSOAPliteralOrEncodedQuery(xmlWriter, inputRows);
  1023. else
  1024. createESPQuery(xmlWriter, inputRows);
  1025. xmlWriter.outputQuoted("</soap:Body></soap:Envelope>");
  1026. }
  1027. void CWSCHelperThread::processQuery(ConstPointerArray &inputRows)
  1028. {
  1029. unsigned xmlWriteFlags = 0;
  1030. unsigned xmlReadFlags = ptr_ignoreNameSpaces;
  1031. if (master->flags & SOAPFtrim)
  1032. xmlWriteFlags |= XWFtrim;
  1033. if ((master->flags & SOAPFpreserveSpace) == 0)
  1034. xmlReadFlags |= ptr_ignoreWhiteSpace;
  1035. XMLWriterType xmlType = !(master->flags & SOAPFencoding) ? WTStandard : WTEncodingData64;
  1036. CommonXmlWriter *xmlWriter = CreateCommonXmlWriter(xmlWriteFlags, 0, NULL, xmlType);
  1037. if (master->wscType == STsoap)
  1038. createXmlSoapQuery(*xmlWriter, inputRows);
  1039. Owned<IWSCAsyncFor> casyncfor = createWSCAsyncFor(master, *xmlWriter, inputRows, (PTreeReaderOptions) xmlReadFlags);
  1040. casyncfor->For(master->numUrls, master->numUrlThreads,false,true); // shuffle URLS for poormans load balance
  1041. delete xmlWriter;
  1042. }
  1043. int CWSCHelperThread::run()
  1044. {
  1045. ConstPointerArray inputRows;
  1046. if (master->wscMode == SCrow)
  1047. {
  1048. inputRows.append(NULL);
  1049. try
  1050. {
  1051. processQuery(inputRows);
  1052. }
  1053. catch (IException *e)
  1054. {
  1055. master->setErrorOwn(e);
  1056. }
  1057. inputRows.pop();
  1058. }
  1059. else
  1060. {
  1061. // following a bit odd but preserving previous semantics (except fixing abort leak)
  1062. loop
  1063. {
  1064. try
  1065. {
  1066. while (!master->complete && !master->error.get())
  1067. {
  1068. if (master->aborted) {
  1069. while (inputRows.ordinality() > 0)
  1070. master->rowProvider->releaseRow(inputRows.popGet());
  1071. return 0;
  1072. }
  1073. const void *r = master->rowProvider->getNextRow();
  1074. if (!r)
  1075. break;
  1076. inputRows.append(r);
  1077. if (inputRows.ordinality() >= master->numRecordsPerBatch)
  1078. break;
  1079. }
  1080. if (inputRows.ordinality() == 0)
  1081. break;
  1082. processQuery(inputRows);
  1083. }
  1084. catch (IException *e)
  1085. {
  1086. master->setErrorOwn(e); // going to exit next time round
  1087. }
  1088. while (inputRows.ordinality() > 0)
  1089. master->rowProvider->releaseRow(inputRows.popGet());
  1090. }
  1091. }
  1092. master->setDone();
  1093. return 0;
  1094. }
  1095. //=================================================================================================
  1096. IWSCHelper * createSoapCallHelper(IWSCRowProvider *r, IEngineRowAllocator * outputAllocator, const char *authToken, WSCMode wscMode, ClientCertificate *clientCert, const IContextLogger &logctx, IRoxieAbortMonitor * roxieAbortMonitor)
  1097. {
  1098. return new CWSCHelper(r, outputAllocator, authToken, wscMode, clientCert, logctx, roxieAbortMonitor, STsoap);
  1099. }
  1100. IWSCHelper * createHttpCallHelper(IWSCRowProvider *r, IEngineRowAllocator * outputAllocator, const char *authToken, WSCMode wscMode, ClientCertificate *clientCert, const IContextLogger &logctx, IRoxieAbortMonitor * roxieAbortMonitor)
  1101. {
  1102. return new CWSCHelper(r, outputAllocator, authToken, wscMode, clientCert, logctx, roxieAbortMonitor, SThttp);
  1103. }
  1104. //=================================================================================================
  1105. class CWSCAsyncFor : implements IWSCAsyncFor, public CInterface, public CAsyncFor
  1106. {
  1107. class CSocketDataProvider : public CInterface
  1108. {
  1109. const char * buffer;
  1110. size32_t currLen;
  1111. size32_t curPosn;
  1112. ISocket * socket;
  1113. unsigned timeoutMS;
  1114. public:
  1115. CSocketDataProvider(const char * _buffer, size32_t _curPosn, size32_t _currLen, ISocket * _sock, unsigned _timeout )
  1116. : buffer(_buffer), currLen(_currLen), curPosn(_curPosn), socket(_sock), timeoutMS(_timeout)
  1117. {
  1118. }
  1119. size32_t getBytes(char * buf, size32_t len)
  1120. {
  1121. size32_t count;
  1122. if ( len <= (currLen-curPosn))
  1123. { //its already in the buffer
  1124. memcpy(buf, (buffer + curPosn), len);
  1125. curPosn += len;
  1126. count = len;
  1127. }
  1128. else if (curPosn >= currLen)
  1129. { //nothing in buffer, read from socket
  1130. size32_t bytesRead=0;
  1131. count = 0;
  1132. do
  1133. {
  1134. socket->readtms(buf + count, 0, len - count, bytesRead, timeoutMS);
  1135. count += bytesRead;
  1136. } while (count != len);
  1137. currLen = curPosn = 0;
  1138. }
  1139. else
  1140. { //only some is in buffer, read rest from socket
  1141. size32_t bytesRead=0;
  1142. size32_t avail = currLen - curPosn;
  1143. memcpy(buf, (buffer + curPosn), avail);
  1144. count = avail;
  1145. do
  1146. {
  1147. size32_t read;
  1148. socket->readtms(buf+avail+bytesRead, 0, len-avail-bytesRead, read, timeoutMS);
  1149. bytesRead += read;
  1150. } while (len != (bytesRead + avail));
  1151. count += bytesRead;
  1152. currLen = curPosn = 0;
  1153. }
  1154. return count;
  1155. }
  1156. };
  1157. private:
  1158. CWSCHelper * master;
  1159. ConstPointerArray &inputRows;
  1160. CommonXmlWriter &xmlWriter;
  1161. IEngineRowAllocator * outputAllocator;
  1162. CriticalSection processExceptionCrit;
  1163. StringBuffer responsePath;
  1164. Owned<CSocketDataProvider> dataProvider;
  1165. PTreeReaderOptions options;
  1166. unsigned remainingMS;
  1167. inline void checkRoxieAbortMonitor(IRoxieAbortMonitor * roxieAbortMonitor)
  1168. {
  1169. if (roxieAbortMonitor)
  1170. {
  1171. try
  1172. {
  1173. roxieAbortMonitor->checkForAbort();//throws
  1174. }
  1175. catch (IException *e)
  1176. {
  1177. StringBuffer s;
  1178. throw MakeStringException(ROXIE_ABORT_EVENT, "%s", e->errorMessage(s).str());
  1179. }
  1180. }
  1181. }
  1182. void createHttpRequest(Url &url, StringBuffer &request)
  1183. {
  1184. // Create the HTTP POST request
  1185. if (master->wscType == STsoap)
  1186. request.clear().append("POST ").append(url.path).append(" HTTP/1.1\r\n");
  1187. else
  1188. request.clear().append(master->service).append(" ").append(url.path).append(" HTTP/1.1\r\n");
  1189. if (url.userPasswordPair.length() > 0)
  1190. {
  1191. StringBuffer authToken;
  1192. JBASE64_Encode(url.userPasswordPair.str(), url.userPasswordPair.length(), authToken);
  1193. request.append("Authorization: Basic ").append(authToken).append("\r\n");
  1194. }
  1195. else if (master->authToken.length() > 0)
  1196. {
  1197. request.append("Authorization: Basic ").append(master->authToken).append("\r\n");
  1198. }
  1199. if (master->wscType == STsoap)
  1200. {
  1201. if (master->soapaction.get())
  1202. request.append("SOAPAction: ").append(master->soapaction.get()).append("\r\n");
  1203. if (master->httpHeaderName.get() && master->httpHeaderValue.get())
  1204. {
  1205. StringBuffer hdr = master->httpHeaderName.get();
  1206. hdr.append(": ").append(master->httpHeaderValue);
  1207. if (soapTraceLevel > 6 || master->logXML)
  1208. master->logctx.CTXLOG("SOAPCALL: Adding HTTP Header(%s)", hdr.str());
  1209. request.append(hdr.append("\r\n"));
  1210. }
  1211. request.append("Content-Type: text/xml\r\n");
  1212. }
  1213. else if(master->wscType == SThttp)
  1214. request.append("Accept: ").append(master->acceptType).append("\r\n");
  1215. else
  1216. assertex(false);
  1217. request.append("Host: ").append(url.host).append(":").append(url.port).append("\r\n");//http 1.1
  1218. if (master->wscType == STsoap)
  1219. {
  1220. request.append(CONTENT_LENGTH).append(xmlWriter.length()).append("\r\n\r\n");
  1221. request.append(xmlWriter.str());//add SOAP xml content
  1222. }
  1223. else
  1224. request.append("\r\n");//httpcall
  1225. if (soapTraceLevel > 6 || master->logXML)
  1226. master->logctx.CTXLOG("%s: request(%s)", master->wscCallTypeText(), request.str());
  1227. if (master->logMin)
  1228. master->logctx.CTXLOG("%s: request(%s:%u)", master->wscCallTypeText(), url.host.str(), url.port);
  1229. }
  1230. int readHttpResponse(StringBuffer &response, ISocket *socket)
  1231. {
  1232. // Read the POST reply
  1233. // not doesn't *assume* is valid HTTP post format but if it is takes advantage of
  1234. response.clear();
  1235. unsigned bytesRead;
  1236. MemoryAttr buf;
  1237. char *buffer=(char *)buf.allocate(WSCBUFFERSIZE+1);
  1238. int rval = 200;
  1239. // first read header
  1240. size32_t payloadofs = 0;
  1241. size32_t payloadsize = 0;
  1242. StringBuffer dbgheader;
  1243. bool chunked = false;
  1244. size32_t read = 0;
  1245. do {
  1246. checkTimeLimitExceeded(&remainingMS);
  1247. checkRoxieAbortMonitor(master->roxieAbortMonitor);
  1248. socket->readtms(buffer+read, 0, WSCBUFFERSIZE-read, bytesRead, MIN(master->timeoutMS,remainingMS));
  1249. checkTimeLimitExceeded(&remainingMS);
  1250. checkRoxieAbortMonitor(master->roxieAbortMonitor);
  1251. read += bytesRead;
  1252. buffer[read] = 0;
  1253. if (strncmp(buffer, "HTTP", 4) == 0) {
  1254. const char *s = strstr(buffer,"\r\n\r\n");
  1255. if (s) {
  1256. payloadofs = (size32_t)(s-buffer+4);
  1257. if (soapTraceLevel > 6 || master->logXML)
  1258. dbgheader.append(payloadofs,buffer); // needed for tracing below
  1259. s = strstr(buffer, " ");
  1260. if (s)
  1261. rval = atoi(s+1);
  1262. if (!strstr(buffer,"Transfer-Encoding: chunked"))
  1263. {
  1264. chunked = false;
  1265. s = strstr(buffer,CONTENT_LENGTH);
  1266. if (s) {
  1267. s += strlen(CONTENT_LENGTH);
  1268. if ((size32_t)(s-buffer) < payloadofs)
  1269. payloadsize = atoi(s);
  1270. }
  1271. }
  1272. else
  1273. {
  1274. chunked = true;
  1275. size32_t chunkSize = 0;
  1276. size32_t dataLen = 0;
  1277. char ch;
  1278. /*
  1279. //from http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.4.4
  1280. "19.4.6 Introduction of Transfer-Encoding"
  1281. length := 0
  1282. read chunk-size, chunk-extension (if any) and CRLF
  1283. while (chunk-size > 0)
  1284. {
  1285. read chunk-data and CRLF
  1286. append chunk-data to entity-body
  1287. length := length + chunk-size
  1288. read chunk-size and CRLF
  1289. }
  1290. */
  1291. checkTimeLimitExceeded(&remainingMS);
  1292. dataProvider.setown(new CSocketDataProvider(buffer, payloadofs, read, socket, MIN(master->timeoutMS,remainingMS)));
  1293. dataProvider->getBytes(&ch, 1);
  1294. while (isalpha(ch) || isdigit(ch))
  1295. { //get chunk-size
  1296. if (isdigit(ch))
  1297. chunkSize = (chunkSize*16) + (ch - '0');
  1298. else
  1299. chunkSize = (chunkSize*16) + 10 + (toupper(ch) - 'A');
  1300. dataProvider->getBytes(&ch, 1);
  1301. }
  1302. while (chunkSize && ch != '\n')//consume chunk-extension and CRLF
  1303. dataProvider->getBytes(&ch, 1);
  1304. while (chunkSize)
  1305. {
  1306. if (chunkSize > WSCBUFFERSIZE)
  1307. DBGLOG("SOAPCALL chunk size %d", chunkSize);
  1308. //read chunk data directly into response
  1309. size32_t count = dataProvider->getBytes(response.reserve(dataLen + chunkSize), chunkSize);
  1310. assertex(count == chunkSize);
  1311. dataLen += count;
  1312. response.setLength(dataLen);
  1313. dataProvider->getBytes(&ch, 1);//consume CRLF at end of chunk
  1314. while (ch != '\n')
  1315. dataProvider->getBytes(&ch, 1);
  1316. chunkSize = 0;
  1317. dataProvider->getBytes(&ch, 1);
  1318. while (isalpha(ch) || isdigit(ch))
  1319. { //get next chunk size
  1320. if (isdigit(ch))
  1321. chunkSize = (chunkSize*16) + (ch - '0');
  1322. else
  1323. chunkSize = (chunkSize*16) + 10 + (toupper(ch) - 'A');
  1324. dataProvider->getBytes(&ch, 1);
  1325. }
  1326. while(chunkSize && ch != '\n')//consume chunk-extension and CRLF
  1327. dataProvider->getBytes(&ch, 1);
  1328. }
  1329. }
  1330. break;
  1331. }
  1332. }
  1333. if (bytesRead == 0) // socket closed
  1334. break;
  1335. } while (bytesRead&&(read<WSCBUFFERSIZE));
  1336. if (!chunked)
  1337. {
  1338. if (payloadsize)
  1339. response.ensureCapacity(payloadsize);
  1340. char *payload = buffer;
  1341. if (payloadofs) {
  1342. read -= payloadofs;
  1343. payload += payloadofs;
  1344. if (payloadsize&&(read>payloadsize))
  1345. read = payloadsize;
  1346. }
  1347. if (read)
  1348. response.append(read,payload);
  1349. if (payloadsize) { // read directly into response
  1350. while (read<payloadsize) {
  1351. checkTimeLimitExceeded(&remainingMS);
  1352. checkRoxieAbortMonitor(master->roxieAbortMonitor);
  1353. socket->readtms(response.reserve(payloadsize-read), 0, payloadsize-read, bytesRead, MIN(master->timeoutMS,remainingMS));
  1354. checkTimeLimitExceeded(&remainingMS);
  1355. checkRoxieAbortMonitor(master->roxieAbortMonitor);
  1356. read += bytesRead;
  1357. response.setLength(read);
  1358. if (bytesRead==0) {
  1359. master->logctx.CTXLOG("%sCALL: Warning %sHTTP response terminated prematurely",master->wscType == STsoap ? "SOAP" : "HTTP",chunked?"CHUNKED ":NULL);
  1360. break; // oops looks likesocket closed early
  1361. }
  1362. }
  1363. }
  1364. else {
  1365. loop {
  1366. checkTimeLimitExceeded(&remainingMS);
  1367. checkRoxieAbortMonitor(master->roxieAbortMonitor);
  1368. socket->readtms(buffer, 0, WSCBUFFERSIZE, bytesRead, MIN(master->timeoutMS,remainingMS));
  1369. checkTimeLimitExceeded(&remainingMS);
  1370. checkRoxieAbortMonitor(master->roxieAbortMonitor);
  1371. if (bytesRead==0)
  1372. break; // rely on socket closing to terminate message
  1373. response.append(bytesRead,buffer);
  1374. }
  1375. }
  1376. }
  1377. if (soapTraceLevel > 6 || master->logXML)
  1378. master->logctx.CTXLOG("%sCALL: LEN=%d %sresponse(%s%s)", master->wscType == STsoap ? "SOAP" : "HTTP",response.length(),chunked?"CHUNKED ":"", dbgheader.str(), response.str());
  1379. else if (soapTraceLevel > 8)
  1380. master->logctx.CTXLOG("%sCALL: LEN=%d %sresponse(%s)", master->wscType == STsoap ? "SOAP" : "HTTP",response.length(),chunked?"CHUNKED ":"", response.str()); // not sure this is that useful but...
  1381. return rval;
  1382. }
  1383. void processEspResponse(Url &url, StringBuffer &response, ColumnProvider * meta)
  1384. {
  1385. StringBuffer path(responsePath);
  1386. path.append("/Results/Result/");
  1387. const char *tail;
  1388. if (master->rowTransformer && master->inputpath.get())
  1389. {
  1390. StringBuffer ipath;
  1391. ipath.append("/Envelope/Body/").append(master->inputpath.get());
  1392. if((ipath.length() >= path.length()) && (0 == memcmp(ipath.str(), path.str(), path.length())))
  1393. {
  1394. tail = ipath.str() + path.length();
  1395. }
  1396. else
  1397. {
  1398. path.clear().append(ipath);
  1399. tail = NULL;
  1400. }
  1401. }
  1402. else
  1403. tail = "Dataset/Row";
  1404. CMatchCB matchCB(*this, url, tail, meta);
  1405. Owned<IXMLParse> xmlParser = createXMLParse((const void *)response.str(), (unsigned)response.length(), path.str(), matchCB, options, false);
  1406. while (xmlParser->next());
  1407. }
  1408. void processLiteralResponse(Url &url, StringBuffer &response, ColumnProvider * meta)
  1409. {
  1410. StringBuffer path("/Envelope/Body/");
  1411. if(master->rowTransformer && master->inputpath.get())
  1412. path.append(master->inputpath.get());
  1413. CMatchCB matchCB(*this, url, NULL, meta);
  1414. Owned<IXMLParse> xmlParser = createXMLParse((const void *)response.str(), (unsigned)response.length(), path.str(), matchCB, options, false);
  1415. while (xmlParser->next());
  1416. }
  1417. void processHttpResponse(Url &url, StringBuffer &response, ColumnProvider * meta)
  1418. {
  1419. StringBuffer path;
  1420. if(master->rowTransformer && master->inputpath.get())
  1421. path.append(master->inputpath.get());
  1422. CMatchCB matchCB(*this, url, NULL, meta);
  1423. Owned<IXMLParse> xmlParser = createXMLParse((const void *)response.str(), (unsigned)response.length(), path.str(), matchCB, options, false);
  1424. while (xmlParser->next());
  1425. }
  1426. void processResponse(Url &url, StringBuffer &response, ColumnProvider * meta)
  1427. {
  1428. if (master->wscType == SThttp)
  1429. processHttpResponse(url, response, meta);
  1430. else if (master->flags & SOAPFliteral)
  1431. processLiteralResponse(url, response, meta);
  1432. else if (master->flags & SOAPFencoding)
  1433. processLiteralResponse(url, response, meta);
  1434. else
  1435. processEspResponse(url, response, meta);
  1436. }
  1437. void processException(const Url &url, const void *row, IException *e)
  1438. {
  1439. CriticalBlock block(processExceptionCrit);
  1440. Owned<IException> ne = url.getUrlException(e);
  1441. e->Release();
  1442. if ((master->flags & SOAPFonfail) && master->callHelper)
  1443. {
  1444. try
  1445. {
  1446. RtlDynamicRowBuilder rowBuilder(outputAllocator);
  1447. size32_t sizeGot = master->onFailTransform(rowBuilder, row, ne);
  1448. if (sizeGot > 0)
  1449. master->putRow(rowBuilder.finalizeRowClear(sizeGot));
  1450. }
  1451. catch (IException *te)
  1452. {
  1453. master->setErrorOwn(te);
  1454. }
  1455. }
  1456. else
  1457. master->setErrorOwn(ne.getClear());
  1458. }
  1459. void processException(const Url &url, ConstPointerArray &inputRows, IException *e)
  1460. {
  1461. Owned<IException> ne = url.getUrlException(e);
  1462. e->Release();
  1463. if ((master->flags & SOAPFonfail) && master->callHelper)
  1464. {
  1465. ForEachItemIn(idx, inputRows)
  1466. {
  1467. try
  1468. {
  1469. RtlDynamicRowBuilder rowBuilder(outputAllocator);
  1470. size32_t sizeGot = master->onFailTransform(rowBuilder, inputRows.item(idx), ne);
  1471. if (sizeGot > 0)
  1472. master->putRow(rowBuilder.finalizeRowClear(sizeGot));
  1473. }
  1474. catch (IException *te)
  1475. {
  1476. master->setErrorOwn(te);
  1477. break;
  1478. }
  1479. }
  1480. }
  1481. else
  1482. master->setErrorOwn(ne.getClear());
  1483. }
  1484. inline void checkTimeLimitExceeded(unsigned * remainingMS)
  1485. {
  1486. if (master->isTimeLimitExceeded(remainingMS))
  1487. throw MakeStringException(TIMELIMIT_EXCEEDED, "%sCALL TIMELIMIT(%ums) exceeded", master->wscType == STsoap ? "SOAP" : "HTTP", master->timeLimitMS);
  1488. }
  1489. public:
  1490. CWSCAsyncFor(CWSCHelper * _master, CommonXmlWriter &_xmlWriter, ConstPointerArray &_inputRows, PTreeReaderOptions _options): xmlWriter(_xmlWriter), inputRows(_inputRows), options(_options)
  1491. {
  1492. master = _master;
  1493. outputAllocator = master->queryOutputAllocator();
  1494. responsePath.append("/Envelope/Body/");
  1495. if (inputRows.ordinality() > 1)
  1496. {
  1497. // can we receive a roxie exceptions for the whole RequestArray?
  1498. // if so, we need to handle them here
  1499. responsePath.append(master->service).append("ResponseArray/");
  1500. }
  1501. responsePath.append(master->service).append("Response");
  1502. }
  1503. ~CWSCAsyncFor()
  1504. {
  1505. }
  1506. IMPLEMENT_IINTERFACE;
  1507. void For(unsigned num,unsigned maxatonce,bool abortFollowingException, bool shuffled)
  1508. {
  1509. CAsyncFor::For(num, maxatonce, abortFollowingException, shuffled);
  1510. }
  1511. void Do(unsigned idx)
  1512. {
  1513. StringBuffer request;
  1514. StringBuffer response;
  1515. unsigned attempts = 0;
  1516. unsigned retryInterval = 0;
  1517. Url &url = master->urlArray.item(idx);
  1518. createHttpRequest(url, request);
  1519. unsigned startidx = idx;
  1520. while (!master->aborted)
  1521. {
  1522. Owned<ISocket> socket;
  1523. cycle_t startCycles, endCycles;
  1524. startCycles = get_cycles_now();
  1525. loop
  1526. {
  1527. try
  1528. {
  1529. checkTimeLimitExceeded(&remainingMS);
  1530. Url &connUrl = master->proxyUrlArray.empty() ? url : master->proxyUrlArray.item(0);
  1531. socket.setown(blacklist->connect(connUrl.port, connUrl.host, master->logctx, (unsigned)master->maxRetries, master->timeoutMS, master->roxieAbortMonitor));
  1532. if (stricmp(url.method, "https") == 0)
  1533. {
  1534. Owned<ISecureSocket> ssock = master->createSecureSocket(socket.getClear());
  1535. if (ssock)
  1536. {
  1537. checkTimeLimitExceeded(&remainingMS);
  1538. int status = ssock->secure_connect();
  1539. if (status < 0)
  1540. {
  1541. StringBuffer err;
  1542. err.append("Failure to establish secure connection to ");
  1543. connUrl.getUrlString(err);
  1544. err.append(": returned ").append(status);
  1545. throw MakeStringExceptionDirect(0, err.str());
  1546. }
  1547. socket.setown(ssock.getLink());
  1548. }
  1549. }
  1550. break;
  1551. }
  1552. catch (IException *e)
  1553. {
  1554. if (master->timeLimitExceeded)
  1555. {
  1556. master->logctx.CTXLOG("%sCALL exiting: time limit (%ums) exceeded",master->wscType == STsoap ? "SOAP" : "HTTP", master->timeLimitMS);
  1557. processException(url, inputRows, e);
  1558. return;
  1559. }
  1560. if (e->errorCode() == ROXIE_ABORT_EVENT)
  1561. {
  1562. StringBuffer s;
  1563. master->logctx.CTXLOG("%sCALL exiting: Roxie Abort : %s",master->wscType == STsoap ? "SOAP" : "HTTP",e->errorMessage(s).str());
  1564. throw;
  1565. }
  1566. do
  1567. {
  1568. idx++; // try next socket not blacklisted
  1569. if (idx==master->urlArray.ordinality())
  1570. idx = 0;
  1571. if (idx==startidx)
  1572. {
  1573. StringBuffer s;
  1574. master->logctx.CTXLOG("Exception %s", e->errorMessage(s).str());
  1575. processException(url, inputRows, e);
  1576. return;
  1577. }
  1578. } while (blacklist->blacklisted(url.port, url.host));
  1579. }
  1580. }
  1581. try
  1582. {
  1583. checkTimeLimitExceeded(&remainingMS);
  1584. checkRoxieAbortMonitor(master->roxieAbortMonitor);
  1585. socket->write(request.str(), request.length());
  1586. if (soapTraceLevel > 4)
  1587. master->logctx.CTXLOG("%sCALL: sent request (%s) to %s:%d", master->wscType == STsoap ? "SOAP" : "HTTP",master->service.str(), url.host.str(), url.port);
  1588. checkTimeLimitExceeded(&remainingMS);
  1589. checkRoxieAbortMonitor(master->roxieAbortMonitor);
  1590. int rval = readHttpResponse(response, socket);
  1591. if (soapTraceLevel > 4)
  1592. master->logctx.CTXLOG("%sCALL: received response (%s) from %s:%d", master->wscType == STsoap ? "SOAP" : "HTTP",master->service.str(), url.host.str(), url.port);
  1593. if (rval != 200)
  1594. {
  1595. if (rval == 503)
  1596. throw new ReceivedRoxieException(1001, "Server Too Busy");
  1597. StringBuffer text;
  1598. text.appendf("HTTP error (%d) in processQuery",rval);
  1599. rtlAddExceptionTag(text, "soapresponse", response.str());
  1600. throw MakeStringExceptionDirect(-1, text.str());
  1601. }
  1602. if (response.length() == 0)
  1603. {
  1604. throw MakeStringException(-1, "Zero length response in processQuery");
  1605. }
  1606. endCycles = get_cycles_now();
  1607. __int64 elapsedNs = cycle_to_nanosec(endCycles-startCycles);
  1608. master->logctx.noteStatistic(StTimeSoapcall, elapsedNs);
  1609. checkTimeLimitExceeded(&remainingMS);
  1610. ColumnProvider * meta = (ColumnProvider*)CreateColumnProvider((unsigned)nanoToMilli(elapsedNs), master->flags&SOAPFencoding?true:false);
  1611. processResponse(url, response, meta);
  1612. delete meta;
  1613. break;
  1614. }
  1615. catch (IReceivedRoxieException *e)
  1616. {
  1617. // server busy ... Sleep and retry
  1618. if (e->errorCode() == 1001)
  1619. {
  1620. if (retryInterval)
  1621. {
  1622. int sleepTime = retryInterval + getRandom() % retryInterval;
  1623. master->logctx.CTXLOG("Server busy (1001), sleeping for %d milliseconds before retry", sleepTime);
  1624. Sleep(sleepTime);
  1625. retryInterval = (retryInterval*2 >= 10000)? 10000: retryInterval*2;
  1626. }
  1627. else
  1628. {
  1629. master->logctx.CTXLOG("Server busy (1001), retrying");
  1630. retryInterval = 10;
  1631. }
  1632. e->Release();
  1633. }
  1634. else
  1635. {
  1636. // other roxie exception ...
  1637. master->logctx.CTXLOG("Exiting: received Roxie exception");
  1638. if (e->errorRow())
  1639. processException(url, e->errorRow(), e);
  1640. else
  1641. processException(url, inputRows, e);
  1642. break;
  1643. }
  1644. }
  1645. catch (IException *e)
  1646. {
  1647. if (master->timeLimitExceeded)
  1648. {
  1649. processException(url, inputRows, e);
  1650. master->logctx.CTXLOG("%sCALL exiting: time limit (%ums) exceeded", master->wscType == STsoap ? "SOAP" : "HTTP", master->timeLimitMS);
  1651. break;
  1652. }
  1653. if (e->errorCode() == ROXIE_ABORT_EVENT)
  1654. {
  1655. StringBuffer s;
  1656. master->logctx.CTXLOG("%sCALL exiting: Roxie Abort : %s",master->wscType == STsoap ? "SOAP" : "HTTP",e->errorMessage(s).str());
  1657. throw;
  1658. }
  1659. // other IException ... retry up to maxRetries
  1660. StringBuffer s;
  1661. master->logctx.CTXLOG("Exception %s - retrying? (%d<%d)", e->errorMessage(s).str(), attempts, master->maxRetries);
  1662. if (attempts > master->maxRetries)
  1663. {
  1664. // error affects all inputRows
  1665. master->logctx.CTXLOG("Exiting: maxRetries exceeded");
  1666. processException(url, inputRows, e);
  1667. break;
  1668. }
  1669. master->logctx.CTXLOG("Retrying: maxRetries not exceeded");
  1670. attempts++;
  1671. e->Release();
  1672. }
  1673. catch (std::exception & es)
  1674. {
  1675. if(dynamic_cast<std::bad_alloc *>(&es))
  1676. throw MakeStringException(-1, "std::exception: out of memory (std::bad_alloc) in CWSCAsyncFor processQuery");
  1677. throw MakeStringException(-1, "std::exception: standard library exception (%s) in CWSCAsyncFor processQuery",es.what());
  1678. }
  1679. catch (...)
  1680. {
  1681. throw MakeStringException(-1, "Unknown exception in processQuery");
  1682. }
  1683. }
  1684. }
  1685. inline virtual StringBuffer getResponsePath() { return responsePath; }
  1686. inline virtual ConstPointerArray & getInputRows() { return inputRows; }
  1687. inline virtual CWSCHelper * getMaster() { return master; }
  1688. inline virtual IEngineRowAllocator * getOutputAllocator() { return outputAllocator; }
  1689. };
  1690. IWSCAsyncFor * createWSCAsyncFor(CWSCHelper * _master, CommonXmlWriter &_xmlWriter, ConstPointerArray &_inputRows, PTreeReaderOptions _options)
  1691. {
  1692. return new CWSCAsyncFor(_master, _xmlWriter, _inputRows, _options);
  1693. }