ccdprotocol.cpp 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2016 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 "platform.h"
  14. #include "jlib.hpp"
  15. #include "jthread.hpp"
  16. #include "roxie.hpp"
  17. #include "roxiehelper.hpp"
  18. #include "ccdprotocol.hpp"
  19. //================================================================================================================================
  20. IHpccProtocolListener *createProtocolListener(const char *protocol, IHpccProtocolMsgSink *sink, unsigned port, unsigned listenQueue);
  21. class CHpccProtocolPlugin : implements IHpccProtocolPlugin, public CInterface
  22. {
  23. public:
  24. IMPLEMENT_IINTERFACE;
  25. CHpccProtocolPlugin(IHpccProtocolPluginContext &ctx)
  26. {
  27. targetNames.appendListUniq(ctx.ctxQueryProp("@querySets"), ",");
  28. targetAliases.setown(createProperties());
  29. StringArray tempList;
  30. tempList.appendListUniq(ctx.ctxQueryProp("@targetAliases"), ",");
  31. ForEachItemIn(i, tempList)
  32. {
  33. const char *alias = tempList.item(i);
  34. const char *eq = strchr(alias, '=');
  35. if (eq)
  36. {
  37. StringAttr name(alias, eq-alias);
  38. if (!targetNames.contains(name))
  39. targetAliases->setProp(name.str(), ++eq);
  40. }
  41. }
  42. maxBlockSize = ctx.ctxGetPropInt("@maxBlockSize", 10000000);
  43. defaultXmlReadFlags = ctx.ctxGetPropBool("@defaultStripLeadingWhitespace", true) ? ptr_ignoreWhiteSpace : ptr_none;
  44. trapTooManyActiveQueries = ctx.ctxGetPropBool("@trapTooManyActiveQueries", true);
  45. numRequestArrayThreads = ctx.ctxGetPropInt("@requestArrayThreads", 5);
  46. }
  47. IHpccProtocolListener *createListener(const char *protocol, IHpccProtocolMsgSink *sink, unsigned port, unsigned listenQueue, const char *config)
  48. {
  49. return createProtocolListener(protocol, sink, port, listenQueue);
  50. }
  51. public:
  52. StringArray targetNames;
  53. Owned<IProperties> targetAliases;
  54. PTreeReaderOptions defaultXmlReadFlags;
  55. unsigned maxBlockSize;
  56. unsigned numRequestArrayThreads;
  57. bool trapTooManyActiveQueries;
  58. };
  59. Owned<CHpccProtocolPlugin> global;
  60. class ProtocolListener : public Thread, implements IHpccProtocolListener, implements IThreadFactory
  61. {
  62. public:
  63. IMPLEMENT_IINTERFACE;
  64. ProtocolListener(IHpccProtocolMsgSink *_sink) : Thread("RoxieListener")
  65. {
  66. running = false;
  67. sink.setown(dynamic_cast<IHpccNativeProtocolMsgSink*>(_sink));
  68. }
  69. virtual IHpccProtocolMsgSink *queryMsgSink()
  70. {
  71. return sink;
  72. }
  73. static void updateAffinity()
  74. {
  75. #ifdef CPU_ZERO
  76. if (sched_getaffinity(0, sizeof(cpu_set_t), &cpuMask))
  77. {
  78. if (traceLevel)
  79. DBGLOG("Unable to get CPU affinity - thread affinity settings will be ignored");
  80. cpuCores = 0;
  81. lastCore = 0;
  82. CPU_ZERO(&cpuMask);
  83. }
  84. else
  85. {
  86. #if __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 6)
  87. cpuCores = CPU_COUNT(&cpuMask);
  88. #else
  89. cpuCores = 0;
  90. unsigned setSize = CPU_SETSIZE;
  91. while (setSize--)
  92. {
  93. if (CPU_ISSET(setSize, &cpuMask))
  94. ++cpuCores;
  95. }
  96. #endif /* GLIBC */
  97. if (traceLevel)
  98. traceAffinity(&cpuMask);
  99. }
  100. #endif
  101. }
  102. virtual void start()
  103. {
  104. // Note we allow a few additional threads than requested - these are the threads that return "Too many active queries" responses
  105. pool.setown(createThreadPool("RoxieSocketWorkerPool", this, NULL, sink->getPoolSize()+5, INFINITE));
  106. assertex(!running);
  107. Thread::start();
  108. started.wait();
  109. }
  110. virtual bool stop(unsigned timeout)
  111. {
  112. if (running)
  113. {
  114. running = false;
  115. join();
  116. Release();
  117. }
  118. return pool->joinAll(false, timeout);
  119. }
  120. virtual bool suspend(bool suspendIt)
  121. {
  122. return sink->suspend(suspendIt);
  123. }
  124. void setThreadAffinity(int numCores)
  125. {
  126. #ifdef CPU_ZERO
  127. // Note - strictly speaking not threadsafe but any race conditions are (a) unlikely and (b) harmless
  128. if (cpuCores)
  129. {
  130. if (numCores > 0 && numCores < cpuCores)
  131. {
  132. cpu_set_t threadMask;
  133. CPU_ZERO(&threadMask);
  134. unsigned cores = 0;
  135. unsigned offset = lastCore;
  136. unsigned core;
  137. for (core = 0; core < CPU_SETSIZE; core++)
  138. {
  139. unsigned useCore = (core + offset) % CPU_SETSIZE;
  140. if (CPU_ISSET(useCore, &cpuMask))
  141. {
  142. CPU_SET(useCore, &threadMask);
  143. cores++;
  144. if (cores == numCores)
  145. {
  146. lastCore = useCore+1;
  147. break;
  148. }
  149. }
  150. }
  151. if (traceLevel > 3)
  152. traceAffinity(&threadMask);
  153. pthread_setaffinity_np(GetCurrentThreadId(), sizeof(cpu_set_t), &threadMask);
  154. }
  155. else
  156. {
  157. if (traceLevel > 3)
  158. traceAffinity(&cpuMask);
  159. pthread_setaffinity_np(GetCurrentThreadId(), sizeof(cpu_set_t), &cpuMask);
  160. }
  161. }
  162. #endif
  163. }
  164. protected:
  165. bool running;
  166. Semaphore started;
  167. Owned<IThreadPool> pool;
  168. Linked<IHpccNativeProtocolMsgSink> sink;
  169. #ifdef CPU_ZERO
  170. static cpu_set_t cpuMask;
  171. static unsigned cpuCores;
  172. static unsigned lastCore;
  173. private:
  174. static void traceAffinity(cpu_set_t *mask)
  175. {
  176. StringBuffer trace;
  177. for (unsigned core = 0; core < CPU_SETSIZE; core++)
  178. {
  179. if (CPU_ISSET(core, mask))
  180. trace.appendf(",%d", core);
  181. }
  182. if (trace.length())
  183. DBGLOG("Process affinity is set to use core(s) %s", trace.str()+1);
  184. }
  185. #endif
  186. };
  187. #ifdef CPU_ZERO
  188. cpu_set_t ProtocolListener::cpuMask;
  189. unsigned ProtocolListener::cpuCores;
  190. unsigned ProtocolListener::lastCore;
  191. #endif
  192. class ProtocolSocketListener : public ProtocolListener
  193. {
  194. unsigned port;
  195. unsigned listenQueue;
  196. Owned<ISocket> socket;
  197. SocketEndpoint ep;
  198. public:
  199. ProtocolSocketListener(IHpccProtocolMsgSink *_sink, unsigned _port, unsigned _listenQueue)
  200. : ProtocolListener(_sink)
  201. {
  202. port = _port;
  203. listenQueue = _listenQueue;
  204. ep.set(port, queryHostIP());
  205. }
  206. IHpccProtocolMsgSink *queryMsgSink()
  207. {
  208. return sink.get();
  209. }
  210. virtual bool stop(unsigned timeout)
  211. {
  212. if (socket)
  213. socket->cancel_accept();
  214. return ProtocolListener::stop(timeout);
  215. }
  216. virtual void disconnectQueue()
  217. {
  218. // This is for dali queues only
  219. }
  220. virtual void stopListening()
  221. {
  222. // Not threadsafe, but we only call this when generating a core file... what's the worst that can happen?
  223. try
  224. {
  225. DBGLOG("Closing listening socket %d", port);
  226. socket.clear();
  227. DBGLOG("Closed listening socket %d", port);
  228. }
  229. catch(...)
  230. {
  231. }
  232. }
  233. virtual void runOnce(const char *query);
  234. virtual int run()
  235. {
  236. DBGLOG("ProtocolSocketListener (%d threads) listening to socket on port %d", sink->getPoolSize(), port);
  237. socket.setown(ISocket::create(port, listenQueue));
  238. running = true;
  239. started.signal();
  240. while (running)
  241. {
  242. ISocket *client = socket->accept(true);
  243. if (client)
  244. {
  245. client->set_linger(-1);
  246. pool->start(client);
  247. }
  248. }
  249. DBGLOG("ProtocolSocketListener closed query socket");
  250. return 0;
  251. }
  252. virtual IPooledThread *createNew();
  253. virtual const SocketEndpoint &queryEndpoint() const
  254. {
  255. return ep;
  256. }
  257. virtual unsigned queryPort() const
  258. {
  259. return port;
  260. }
  261. };
  262. class ProtocolQueryWorker : public CInterface, implements IPooledThread
  263. {
  264. public:
  265. IMPLEMENT_IINTERFACE;
  266. ProtocolQueryWorker(ProtocolListener *_listener) : listener(_listener)
  267. {
  268. qstart = msTick();
  269. time(&startTime);
  270. }
  271. // interface IPooledThread
  272. virtual void init(void *)
  273. {
  274. qstart = msTick();
  275. time(&startTime);
  276. }
  277. virtual bool canReuse()
  278. {
  279. return true;
  280. }
  281. virtual bool stop()
  282. {
  283. ERRLOG("RoxieQueryWorker stopped with queries active");
  284. return true;
  285. }
  286. protected:
  287. ProtocolListener *listener;
  288. unsigned qstart;
  289. time_t startTime;
  290. };
  291. enum class AdaptiveRoot {NamedArray, RootArray, FirstRow};
  292. class AdaptiveRESTJsonWriter : public CommonJsonWriter
  293. {
  294. AdaptiveRoot model;
  295. unsigned depth = 0;
  296. public:
  297. AdaptiveRESTJsonWriter(AdaptiveRoot _model, unsigned _flags, unsigned _initialIndent, IXmlStreamFlusher *_flusher) :
  298. CommonJsonWriter(_flags, _initialIndent, _flusher), model(_model)
  299. {
  300. }
  301. virtual void outputBeginArray(const char *fieldname)
  302. {
  303. prepareBeginArray(fieldname);
  304. if (model == AdaptiveRoot::NamedArray || arrays.length()>1)
  305. appendJSONName(out, fieldname).append('[');
  306. else if (model == AdaptiveRoot::RootArray)
  307. out.append('[');
  308. }
  309. void outputEndArray(const char *fieldname)
  310. {
  311. arrays.pop();
  312. checkFormat(false, true, -1);
  313. if (arrays.length() || model != AdaptiveRoot::FirstRow)
  314. out.append(']');
  315. const char * sep = (fieldname) ? strchr(fieldname, '/') : NULL;
  316. while (sep)
  317. {
  318. out.append('}');
  319. sep = strchr(sep+1, '/');
  320. }
  321. }
  322. void outputBeginNested(const char *fieldname, bool nestChildren)
  323. {
  324. CommonJsonWriter::outputBeginNested(fieldname, nestChildren);
  325. if (model == AdaptiveRoot::FirstRow)
  326. depth++;
  327. }
  328. void outputEndNested(const char *fieldname)
  329. {
  330. CommonJsonWriter::outputEndNested(fieldname);
  331. if (model == AdaptiveRoot::FirstRow)
  332. {
  333. depth--;
  334. if (fieldname && streq(fieldname, "Row") && depth==0)
  335. {
  336. flush(true);
  337. flusher = nullptr;
  338. }
  339. }
  340. }
  341. };
  342. class AdaptiveRESTXmlWriter : public CommonXmlWriter
  343. {
  344. StringAttr tag;
  345. AdaptiveRoot model = AdaptiveRoot::NamedArray;
  346. unsigned depth = 0;
  347. public:
  348. AdaptiveRESTXmlWriter(AdaptiveRoot _model, const char *tagname, unsigned _flags, unsigned _initialIndent, IXmlStreamFlusher *_flusher) :
  349. CommonXmlWriter(_flags, _initialIndent, _flusher), tag(tagname), model(_model)
  350. {
  351. }
  352. void outputBeginNested(const char *fieldname, bool nestChildren)
  353. {
  354. if (model == AdaptiveRoot::FirstRow)
  355. {
  356. if (!depth && tag.length())
  357. fieldname = tag.str();
  358. depth++;
  359. }
  360. CommonXmlWriter::outputBeginNested(fieldname, nestChildren);
  361. }
  362. void outputEndNested(const char *fieldname)
  363. {
  364. if (model == AdaptiveRoot::FirstRow)
  365. {
  366. depth--;
  367. if (!depth)
  368. {
  369. CommonXmlWriter::outputEndNested(tag.length() ? tag.str() : fieldname);
  370. flush(true);
  371. flusher = nullptr;
  372. return;
  373. }
  374. }
  375. CommonXmlWriter::outputEndNested(fieldname);
  376. }
  377. };
  378. IXmlWriterExt * createAdaptiveRESTWriterExt(AdaptiveRoot model, const char *tagname, unsigned _flags, unsigned _initialIndent, IXmlStreamFlusher *_flusher, XMLWriterType xmlType)
  379. {
  380. if (xmlType==WTJSON)
  381. return new AdaptiveRESTJsonWriter(model, _flags, _initialIndent, _flusher);
  382. return new AdaptiveRESTXmlWriter(model, tagname, _flags, _initialIndent, _flusher);
  383. }
  384. //================================================================================================================
  385. class CHpccNativeResultsWriter : implements IHpccNativeProtocolResultsWriter, public CInterface
  386. {
  387. protected:
  388. SafeSocket *client;
  389. CriticalSection resultsCrit;
  390. IPointerArrayOf<FlushingStringBuffer> resultMap;
  391. StringAttr queryName;
  392. StringAttr tagName;
  393. StringAttr resultFilter;
  394. const IContextLogger &logctx;
  395. Owned<FlushingStringBuffer> probe;
  396. TextMarkupFormat mlFmt;
  397. PTreeReaderOptions xmlReadFlags;
  398. bool isBlocked;
  399. bool isRaw;
  400. bool isHTTP;
  401. bool trim; // MORE - this is never set!
  402. bool adaptiveRoot = false;
  403. bool onlyUseFirstRow = false;
  404. public:
  405. IMPLEMENT_IINTERFACE;
  406. CHpccNativeResultsWriter(const char *queryname, SafeSocket *_client, bool _isBlocked, TextMarkupFormat _mlFmt, bool _isRaw, bool _isHTTP, const IContextLogger &_logctx, PTreeReaderOptions _xmlReadFlags) :
  407. client(_client), queryName(queryname), logctx(_logctx), mlFmt(_mlFmt), xmlReadFlags(_xmlReadFlags), isBlocked(_isBlocked), isRaw(_isRaw), isHTTP(_isHTTP)
  408. {
  409. }
  410. ~CHpccNativeResultsWriter()
  411. {
  412. }
  413. inline void setAdaptiveRoot(){adaptiveRoot = true; client->setAdaptiveRoot(true);}
  414. inline void setTagName(const char *tag){tagName.set(tag);}
  415. inline void setOnlyUseFirstRow(){onlyUseFirstRow = true;}
  416. inline void setResultFilter(const char *_resultFilter){resultFilter.set(_resultFilter);}
  417. virtual FlushingStringBuffer *queryResult(unsigned sequence)
  418. {
  419. CriticalBlock procedure(resultsCrit);
  420. while (!resultMap.isItem(sequence))
  421. resultMap.append(NULL);
  422. FlushingStringBuffer *result = resultMap.item(sequence);
  423. if (!result)
  424. {
  425. if (mlFmt==MarkupFmt_JSON)
  426. result = new FlushingJsonBuffer(client, isBlocked, isHTTP, logctx);
  427. else
  428. result = new FlushingStringBuffer(client, isBlocked, mlFmt, isRaw, isHTTP, logctx);
  429. result->isSoap = isHTTP;
  430. result->trim = trim;
  431. result->queryName.set(queryName);
  432. resultMap.replace(result, sequence);
  433. }
  434. return result;
  435. }
  436. virtual FlushingStringBuffer *createFlushingBuffer()
  437. {
  438. return new FlushingStringBuffer(client, isBlocked, mlFmt, isRaw, isHTTP, logctx);
  439. }
  440. bool checkAdaptiveResult(const char *name)
  441. {
  442. if (!adaptiveRoot)
  443. return false;
  444. if (!resultFilter || !*resultFilter)
  445. return true;
  446. return (streq(resultFilter, name));
  447. }
  448. virtual IXmlWriter *addDataset(const char *name, unsigned sequence, const char *elementName, bool &appendRawData, unsigned writeFlags, bool _extend, const IProperties *xmlns)
  449. {
  450. FlushingStringBuffer *response = queryResult(sequence);
  451. if (response)
  452. {
  453. appendRawData = response->isRaw;
  454. bool adaptive = checkAdaptiveResult(name);
  455. if (adaptive)
  456. {
  457. elementName = nullptr;
  458. if (response->mlFmt!=MarkupFmt_JSON && !onlyUseFirstRow && tagName.length())
  459. elementName = tagName.str();
  460. }
  461. response->startDataset(elementName, name, sequence, _extend, xmlns, adaptive);
  462. if (response->mlFmt==MarkupFmt_XML || response->mlFmt==MarkupFmt_JSON)
  463. {
  464. if (response->mlFmt==MarkupFmt_JSON)
  465. writeFlags |= XWFnoindent;
  466. AdaptiveRoot rootType = AdaptiveRoot::NamedArray;
  467. if (adaptive)
  468. {
  469. if (onlyUseFirstRow)
  470. rootType = AdaptiveRoot::FirstRow;
  471. else
  472. rootType = AdaptiveRoot::RootArray;
  473. }
  474. Owned<IXmlWriter> xmlwriter = createAdaptiveRESTWriterExt(rootType, tagName, writeFlags, 1, response, (response->mlFmt==MarkupFmt_JSON) ? WTJSON : WTStandard);
  475. xmlwriter->outputBeginArray("Row");
  476. return xmlwriter.getClear();
  477. }
  478. }
  479. return NULL;
  480. }
  481. virtual void finalizeXmlRow(unsigned sequence)
  482. {
  483. if (mlFmt==MarkupFmt_XML || mlFmt==MarkupFmt_JSON)
  484. {
  485. FlushingStringBuffer *r = queryResult(sequence);
  486. if (r)
  487. {
  488. r->incrementRowCount();
  489. r->flush(false);
  490. }
  491. }
  492. }
  493. inline void startScalar(FlushingStringBuffer *r, const char *name, unsigned sequence)
  494. {
  495. if (checkAdaptiveResult(name))
  496. {
  497. r->startScalar(name, sequence, true, tagName.length() ? tagName.str() : name);
  498. return;
  499. }
  500. r->startScalar(name, sequence);
  501. }
  502. virtual void appendRaw(unsigned sequence, unsigned len, const char *data)
  503. {
  504. FlushingStringBuffer *r = queryResult(sequence);
  505. if (r)
  506. r->append(len, data);
  507. }
  508. virtual void appendRawRow(unsigned sequence, unsigned len, const char *data)
  509. {
  510. FlushingStringBuffer *r = queryResult(sequence);
  511. if (r)
  512. {
  513. r->append(len, data);
  514. r->incrementRowCount();
  515. r->flush(false);
  516. }
  517. }
  518. virtual void appendSimpleRow(unsigned sequence, const char *str)
  519. {
  520. FlushingStringBuffer *r = queryResult(sequence);
  521. if (r)
  522. r->append(str);
  523. }
  524. virtual void setResultBool(const char *name, unsigned sequence, bool value)
  525. {
  526. FlushingStringBuffer *r = queryResult(sequence);
  527. if (r)
  528. {
  529. startScalar(r, name, sequence);
  530. if (isRaw)
  531. r->append(sizeof(value), (char *)&value);
  532. else
  533. r->append(value ? "true" : "false");
  534. }
  535. }
  536. virtual void setResultData(const char *name, unsigned sequence, int len, const void * data)
  537. {
  538. FlushingStringBuffer *r = queryResult(sequence);
  539. if (r)
  540. {
  541. startScalar(r, name, sequence);
  542. r->encodeData(data, len);
  543. }
  544. }
  545. virtual void setResultRaw(const char *name, unsigned sequence, int len, const void * data)
  546. {
  547. FlushingStringBuffer *r = queryResult(sequence);
  548. if (r)
  549. {
  550. startScalar(r, name, sequence);
  551. if (isRaw)
  552. r->append(len, (const char *) data);
  553. else
  554. UNIMPLEMENTED;
  555. }
  556. }
  557. virtual void setResultSet(const char *name, unsigned sequence, bool isAll, size32_t len, const void * data, ISetToXmlTransformer * transformer)
  558. {
  559. FlushingStringBuffer *r = queryResult(sequence);
  560. if (r)
  561. {
  562. startScalar(r, name, sequence);
  563. if (isRaw)
  564. r->append(len, (char *)data);
  565. else if (mlFmt==MarkupFmt_XML)
  566. {
  567. assertex(transformer);
  568. CommonXmlWriter writer(xmlReadFlags|XWFnoindent, 0);
  569. transformer->toXML(isAll, len, (byte *)data, writer);
  570. r->append(writer.str());
  571. }
  572. else if (mlFmt==MarkupFmt_JSON)
  573. {
  574. assertex(transformer);
  575. CommonJsonWriter writer(xmlReadFlags|XWFnoindent, 0);
  576. transformer->toXML(isAll, len, (byte *)data, writer);
  577. r->append(writer.str());
  578. }
  579. else
  580. {
  581. assertex(transformer);
  582. r->append('[');
  583. if (isAll)
  584. r->appendf("*]");
  585. else
  586. {
  587. SimpleOutputWriter x;
  588. transformer->toXML(isAll, len, (const byte *) data, x);
  589. r->appendf("%s]", x.str());
  590. }
  591. }
  592. }
  593. }
  594. virtual void setResultDecimal(const char *name, unsigned sequence, int len, int precision, bool isSigned, const void *val)
  595. {
  596. FlushingStringBuffer *r = queryResult(sequence);
  597. if (r)
  598. {
  599. startScalar(r, name, sequence);
  600. if (isRaw)
  601. r->append(len, (char *)val);
  602. else
  603. {
  604. StringBuffer s;
  605. if (isSigned)
  606. outputXmlDecimal(val, len, precision, NULL, s);
  607. else
  608. outputXmlUDecimal(val, len, precision, NULL, s);
  609. r->append(s);
  610. }
  611. }
  612. }
  613. virtual void setResultInt(const char *name, unsigned sequence, __int64 value, unsigned size)
  614. {
  615. FlushingStringBuffer *r = queryResult(sequence);
  616. if (r)
  617. {
  618. if (isRaw)
  619. {
  620. startScalar(r, name, sequence);
  621. r->append(sizeof(value), (char *)&value);
  622. }
  623. else
  624. r->setScalarInt(name, sequence, value, size);
  625. }
  626. }
  627. virtual void setResultUInt(const char *name, unsigned sequence, unsigned __int64 value, unsigned size)
  628. {
  629. FlushingStringBuffer *r = queryResult(sequence);
  630. if (r)
  631. {
  632. if (isRaw)
  633. {
  634. startScalar(r, name, sequence);
  635. r->append(sizeof(value), (char *)&value);
  636. }
  637. else
  638. r->setScalarUInt(name, sequence, value, size);
  639. }
  640. }
  641. virtual void setResultReal(const char *name, unsigned sequence, double value)
  642. {
  643. FlushingStringBuffer *r = queryResult(sequence);
  644. if (r)
  645. {
  646. startScalar(r, name, sequence);
  647. r->append(value);
  648. }
  649. }
  650. virtual void setResultString(const char *name, unsigned sequence, int len, const char * str)
  651. {
  652. FlushingStringBuffer *r = queryResult(sequence);
  653. if (r)
  654. {
  655. startScalar(r, name, sequence);
  656. if (r->isRaw)
  657. {
  658. r->append(len, str);
  659. }
  660. else
  661. {
  662. r->encodeString(str, len);
  663. }
  664. }
  665. }
  666. virtual void setResultUnicode(const char *name, unsigned sequence, int len, UChar const * str)
  667. {
  668. FlushingStringBuffer *r = queryResult(sequence);
  669. if (r)
  670. {
  671. startScalar(r, name, sequence);
  672. if (r->isRaw)
  673. {
  674. r->append(len*2, (const char *) str);
  675. }
  676. else
  677. {
  678. rtlDataAttr buff;
  679. unsigned bufflen = 0;
  680. rtlUnicodeToCodepageX(bufflen, buff.refstr(), len, str, "utf-8");
  681. r->encodeString(buff.getstr(), bufflen, true); // output as UTF-8
  682. }
  683. }
  684. }
  685. virtual void setResultVarString(const char * name, unsigned sequence, const char * value)
  686. {
  687. setResultString(name, sequence, strlen(value), value);
  688. }
  689. virtual void setResultVarUnicode(const char * name, unsigned sequence, UChar const * value)
  690. {
  691. setResultUnicode(name, sequence, rtlUnicodeStrlen(value), value);
  692. }
  693. virtual void flush()
  694. {
  695. ForEachItemIn(seq, resultMap)
  696. {
  697. FlushingStringBuffer *result = resultMap.item(seq);
  698. if (result)
  699. result->flush(true);
  700. }
  701. }
  702. virtual void finalize(unsigned seqNo, const char *delim, const char *filter)
  703. {
  704. bool needDelimiter = false;
  705. ForEachItemIn(seq, resultMap)
  706. {
  707. FlushingStringBuffer *result = resultMap.item(seq);
  708. if (result && (!filter || !*filter || streq(filter, result->queryResultName())))
  709. {
  710. result->flush(true);
  711. for(;;)
  712. {
  713. size32_t length;
  714. void *payload = result->getPayload(length);
  715. if (!length)
  716. break;
  717. if (needDelimiter)
  718. {
  719. StringAttr s(delim); //write() will take ownership of buffer
  720. size32_t len = s.length();
  721. client->write((void *)s.detach(), len, true);
  722. needDelimiter=false;
  723. }
  724. client->write(payload, length, true);
  725. }
  726. if (delim)
  727. needDelimiter=true;
  728. }
  729. }
  730. }
  731. virtual void appendProbeGraph(const char *xml)
  732. {
  733. if (!xml)
  734. {
  735. if (probe)
  736. probe.clear();
  737. return;
  738. }
  739. if (!probe)
  740. {
  741. probe.setown(new FlushingStringBuffer(client, isBlocked, MarkupFmt_XML, false, isHTTP, logctx));
  742. probe->startDataset("_Probe", NULL, (unsigned) -1); // initialize it
  743. }
  744. probe->append("\n");
  745. probe->append(xml);
  746. }
  747. };
  748. class CHpccXmlResultsWriter : public CHpccNativeResultsWriter
  749. {
  750. public:
  751. CHpccXmlResultsWriter(const char *queryname, SafeSocket *_client, bool _isHTTP, const IContextLogger &_logctx, PTreeReaderOptions _xmlReadFlags) :
  752. CHpccNativeResultsWriter(queryname, _client, false, MarkupFmt_XML, false, _isHTTP, _logctx, _xmlReadFlags)
  753. {
  754. }
  755. virtual void addContent(TextMarkupFormat fmt, const char *content, const char *name)
  756. {
  757. StringBuffer xml;
  758. if (!content || !*content)
  759. return;
  760. if (fmt==MarkupFmt_JSON)
  761. {
  762. Owned<IPropertyTree> convertPT = createPTreeFromXMLString(content);
  763. if (name && *name)
  764. appendXMLOpenTag(xml, name);
  765. toXML(convertPT, xml, 0, 0);
  766. if (name && *name)
  767. appendXMLCloseTag(xml, name);
  768. }
  769. }
  770. virtual void finalize(unsigned seqNo)
  771. {
  772. if (!isHTTP)
  773. {
  774. flush();
  775. return;
  776. }
  777. CriticalBlock b(resultsCrit);
  778. CriticalBlock b1(client->queryCrit());
  779. StringBuffer responseHead, responseTail;
  780. responseHead.append("<Results><Result>");
  781. unsigned len = responseHead.length();
  782. client->write(responseHead.detach(), len, true);
  783. ForEachItemIn(seq, resultMap)
  784. {
  785. FlushingStringBuffer *result = resultMap.item(seq);
  786. if (result)
  787. {
  788. result->flush(true);
  789. for(;;)
  790. {
  791. size32_t length;
  792. void *payload = result->getPayload(length);
  793. if (!length)
  794. break;
  795. client->write(payload, length, true);
  796. }
  797. }
  798. }
  799. responseTail.append("</Result></Results>");
  800. len = responseTail.length();
  801. client->write(responseTail.detach(), len, true);
  802. }
  803. };
  804. class CHpccJsonResultsWriter : public CHpccNativeResultsWriter
  805. {
  806. public:
  807. CHpccJsonResultsWriter(const char *queryname, SafeSocket *_client, const IContextLogger &_logctx, PTreeReaderOptions _xmlReadFlags) :
  808. CHpccNativeResultsWriter(queryname, _client, false, MarkupFmt_JSON, false, true, _logctx, _xmlReadFlags)
  809. {
  810. }
  811. virtual FlushingStringBuffer *createFlushingBuffer()
  812. {
  813. return new FlushingJsonBuffer(client, isBlocked, isHTTP, logctx);
  814. }
  815. virtual void finalize(unsigned seqNo)
  816. {
  817. CriticalBlock b(resultsCrit);
  818. CriticalBlock b1(client->queryCrit());
  819. StringBuffer responseHead, responseTail;
  820. appendJSONName(responseHead, "Results").append(" {");
  821. unsigned len = responseHead.length();
  822. client->write(responseHead.detach(), len, true);
  823. bool needDelimiter = false;
  824. ForEachItemIn(seq, resultMap)
  825. {
  826. FlushingStringBuffer *result = resultMap.item(seq);
  827. if (result)
  828. {
  829. result->flush(true);
  830. for(;;)
  831. {
  832. size32_t length;
  833. void *payload = result->getPayload(length);
  834. if (!length)
  835. break;
  836. if (needDelimiter)
  837. {
  838. StringAttr s(","); //write() will take ownership of buffer
  839. size32_t len = s.length();
  840. client->write((void *)s.detach(), len, true);
  841. needDelimiter=false;
  842. }
  843. client->write(payload, length, true);
  844. }
  845. needDelimiter=true;
  846. }
  847. }
  848. responseTail.append("}");
  849. len = responseTail.length();
  850. client->write(responseTail.detach(), len, true);
  851. }
  852. };
  853. class CHpccNativeProtocolResponse : implements IHpccNativeProtocolResponse, public CInterface
  854. {
  855. protected:
  856. SafeSocket *client;
  857. StringAttr queryName;
  858. StringArray resultFilter;
  859. StringBuffer rootTag;
  860. const IContextLogger &logctx;
  861. TextMarkupFormat mlFmt;
  862. PTreeReaderOptions xmlReadFlags;
  863. Owned<CHpccNativeResultsWriter> results; //hpcc results section
  864. IPointerArrayOf<FlushingStringBuffer> contentsMap; //other sections
  865. CriticalSection contentsCrit;
  866. unsigned protocolFlags;
  867. bool isHTTP;
  868. public:
  869. IMPLEMENT_IINTERFACE;
  870. CHpccNativeProtocolResponse(const char *queryname, SafeSocket *_client, TextMarkupFormat _mlFmt, unsigned flags, bool _isHTTP, const IContextLogger &_logctx, PTreeReaderOptions _xmlReadFlags, const char *_resultFilterString, const char *_rootTag) :
  871. client(_client), queryName(queryname), logctx(_logctx), mlFmt(_mlFmt), xmlReadFlags(_xmlReadFlags), protocolFlags(flags), isHTTP(_isHTTP), rootTag(_rootTag)
  872. {
  873. resultFilter.appendList(_resultFilterString, ".");
  874. if (!rootTag.length() && resultFilter.length())
  875. rootTag.set(resultFilter.item(0)).replace(' ', '_');
  876. }
  877. ~CHpccNativeProtocolResponse()
  878. {
  879. }
  880. virtual unsigned getFlags()
  881. {
  882. return protocolFlags;
  883. }
  884. inline bool getIsRaw()
  885. {
  886. return (protocolFlags & HPCC_PROTOCOL_NATIVE_RAW);
  887. }
  888. inline bool getIsBlocked()
  889. {
  890. return (protocolFlags & HPCC_PROTOCOL_BLOCKED);
  891. }
  892. inline bool getTrim()
  893. {
  894. return (protocolFlags & HPCC_PROTOCOL_TRIM);
  895. }
  896. virtual FlushingStringBuffer *queryAppendContentBuffer()
  897. {
  898. CriticalBlock procedure(contentsCrit);
  899. FlushingStringBuffer *content;
  900. if (mlFmt==MarkupFmt_JSON)
  901. content = new FlushingJsonBuffer(client, getIsBlocked(), isHTTP, logctx);
  902. else
  903. content = new FlushingStringBuffer(client, getIsBlocked(), mlFmt, getIsRaw(), isHTTP, logctx);
  904. content->isSoap = isHTTP;
  905. content->trim = getTrim();
  906. content->queryName.set(queryName);
  907. if (!isHTTP)
  908. content->startBlock();
  909. contentsMap.append(content);
  910. return content;
  911. }
  912. virtual IHpccProtocolResultsWriter *queryHpccResultsSection()
  913. {
  914. if (!results)
  915. {
  916. results.setown(new CHpccNativeResultsWriter(queryName, client, getIsBlocked(), mlFmt, getIsRaw(), isHTTP, logctx, xmlReadFlags));
  917. if (rootTag.length())
  918. results->setTagName(rootTag);
  919. if (resultFilter.length())
  920. {
  921. results->setAdaptiveRoot();
  922. results->setResultFilter(resultFilter.item(0));
  923. }
  924. if (resultFilter.isItem(1) && strieq("row", resultFilter.item(1)))
  925. results->setOnlyUseFirstRow();
  926. }
  927. return results;
  928. }
  929. virtual void appendContent(TextMarkupFormat mlFmt, const char *content, const char *name=NULL)
  930. {
  931. throwUnexpected();
  932. }
  933. virtual IXmlWriter *writeAppendContent(const char *name = NULL)
  934. {
  935. throwUnexpected();
  936. }
  937. virtual void finalize(unsigned seqNo)
  938. {
  939. flush();
  940. if (!isHTTP)
  941. {
  942. unsigned replyLen = 0;
  943. client->write(&replyLen, sizeof(replyLen));
  944. }
  945. }
  946. virtual bool checkConnection()
  947. {
  948. if (client)
  949. return client->checkConnection();
  950. else
  951. return true;
  952. }
  953. virtual void sendHeartBeat()
  954. {
  955. if (client)
  956. client->sendHeartBeat(logctx);
  957. }
  958. virtual SafeSocket *querySafeSocket()
  959. {
  960. return client;
  961. }
  962. virtual void flush()
  963. {
  964. if (results)
  965. results->flush();
  966. ForEachItemIn(i, contentsMap)
  967. contentsMap.item(i)->flush(true);
  968. }
  969. virtual void appendProbeGraph(const char *xml)
  970. {
  971. if (results)
  972. results->appendProbeGraph(xml);
  973. }
  974. };
  975. class CHpccJsonResponse : public CHpccNativeProtocolResponse
  976. {
  977. public:
  978. CHpccJsonResponse(const char *queryname, SafeSocket *_client, unsigned flags, bool _isHttp, const IContextLogger &_logctx, PTreeReaderOptions _xmlReadFlags, const char *_resultFilter, const char *_rootTag) :
  979. CHpccNativeProtocolResponse(queryname, _client, MarkupFmt_JSON, flags, _isHttp, _logctx, _xmlReadFlags, _resultFilter, _rootTag)
  980. {
  981. }
  982. virtual IHpccProtocolResultsWriter *getHpccResultsSection()
  983. {
  984. if (!results)
  985. results.setown(new CHpccJsonResultsWriter(queryName, client, logctx, xmlReadFlags));
  986. return results;
  987. }
  988. virtual void appendContent(TextMarkupFormat mlFmt, const char *content, const char *name=NULL)
  989. {
  990. if (mlFmt!=MarkupFmt_XML && mlFmt!=MarkupFmt_JSON)
  991. return;
  992. StringBuffer json;
  993. if (mlFmt==MarkupFmt_XML)
  994. {
  995. Owned<IPropertyTree> convertPT = createPTreeFromXMLString(StringBuffer("<Control>").append(content).append("</Control>"));
  996. toJSON(convertPT, json, 0, 0);
  997. content = json.str();
  998. }
  999. FlushingStringBuffer *contentBuffer = queryAppendContentBuffer();
  1000. StringBuffer tag;
  1001. if (name && *name)
  1002. appendJSONName(tag, name);
  1003. contentBuffer->append(tag);
  1004. contentBuffer->append(content);
  1005. }
  1006. virtual IXmlWriter *writeAppendContent(const char *name = NULL)
  1007. {
  1008. FlushingStringBuffer *content = queryAppendContentBuffer();
  1009. if (name && *name)
  1010. {
  1011. StringBuffer tag;
  1012. appendJSONName(tag, name);
  1013. content->append(tag);
  1014. }
  1015. Owned<IXmlWriter> xmlwriter = createIXmlWriterExt(XWFnoindent, 1, content, WTJSON);
  1016. return xmlwriter.getClear();
  1017. }
  1018. virtual void outputContent()
  1019. {
  1020. CriticalBlock b1(client->queryCrit());
  1021. bool needDelimiter = false;
  1022. ForEachItemIn(seq, contentsMap)
  1023. {
  1024. FlushingStringBuffer *content = contentsMap.item(seq);
  1025. if (content)
  1026. {
  1027. content->flush(true);
  1028. for(;;)
  1029. {
  1030. size32_t length;
  1031. void *payload = content->getPayload(length);
  1032. if (!length)
  1033. break;
  1034. if (needDelimiter)
  1035. {
  1036. StringAttr s(","); //write() will take ownership of buffer
  1037. size32_t len = s.length();
  1038. client->write((void *)s.detach(), len, true);
  1039. needDelimiter=false;
  1040. }
  1041. client->write(payload, length, true);
  1042. }
  1043. needDelimiter=true;
  1044. }
  1045. }
  1046. }
  1047. virtual void finalize(unsigned seqNo)
  1048. {
  1049. if (!isHTTP)
  1050. {
  1051. CHpccNativeProtocolResponse::finalize(seqNo);
  1052. return;
  1053. }
  1054. CriticalBlock b(contentsCrit);
  1055. StringBuffer responseHead, responseTail;
  1056. if (!resultFilter.ordinality() && !(protocolFlags & HPCC_PROTOCOL_CONTROL))
  1057. {
  1058. StringBuffer name(queryName.get());
  1059. if (isHTTP)
  1060. name.append("Response");
  1061. appendJSONName(responseHead, name.str()).append(" {");
  1062. appendJSONValue(responseHead, "sequence", seqNo);
  1063. appendJSONName(responseHead, "Results").append(" {");
  1064. unsigned len = responseHead.length();
  1065. client->write(responseHead.detach(), len, true);
  1066. }
  1067. if (!resultFilter.ordinality())
  1068. outputContent();
  1069. if (results)
  1070. results->finalize(seqNo, ",", resultFilter.ordinality() ? resultFilter.item(0) : NULL);
  1071. if (!resultFilter.ordinality() && !(protocolFlags & HPCC_PROTOCOL_CONTROL))
  1072. {
  1073. responseTail.append("}}");
  1074. unsigned len = responseTail.length();
  1075. client->write(responseTail.detach(), len, true);
  1076. }
  1077. }
  1078. };
  1079. class CHpccXmlResponse : public CHpccNativeProtocolResponse
  1080. {
  1081. public:
  1082. CHpccXmlResponse(const char *queryname, SafeSocket *_client, unsigned flags, bool _isHTTP, const IContextLogger &_logctx, PTreeReaderOptions _xmlReadFlags, const char *_resultFilter, const char *_rootTag) :
  1083. CHpccNativeProtocolResponse(queryname, _client, MarkupFmt_XML, flags, _isHTTP, _logctx, _xmlReadFlags, _resultFilter, _rootTag)
  1084. {
  1085. }
  1086. virtual IHpccProtocolResultsWriter *getHpccResultsSection()
  1087. {
  1088. if (!results)
  1089. results.setown(new CHpccXmlResultsWriter(queryName, client, isHTTP, logctx, xmlReadFlags));
  1090. return results;
  1091. }
  1092. virtual void appendContent(TextMarkupFormat mlFmt, const char *content, const char *name=NULL)
  1093. {
  1094. if (mlFmt!=MarkupFmt_XML && mlFmt!=MarkupFmt_JSON)
  1095. return;
  1096. StringBuffer xml;
  1097. if (mlFmt==MarkupFmt_JSON)
  1098. {
  1099. Owned<IPropertyTree> convertPT = createPTreeFromJSONString(content);
  1100. toXML(convertPT, xml, 0, 0);
  1101. content = xml.str();
  1102. }
  1103. FlushingStringBuffer *contentBuffer = queryAppendContentBuffer();
  1104. if (name && *name)
  1105. {
  1106. StringBuffer tag;
  1107. appendXMLOpenTag(tag, name);
  1108. contentBuffer->append(tag.append('\n'));
  1109. appendXMLCloseTag(tag.clear(), name);
  1110. contentBuffer->setTail(tag.append('\n'));
  1111. }
  1112. contentBuffer->append(content);
  1113. }
  1114. virtual IXmlWriter *writeAppendContent(const char *name = NULL)
  1115. {
  1116. FlushingStringBuffer *content = queryAppendContentBuffer();
  1117. StringBuffer tag;
  1118. if (name && *name)
  1119. {
  1120. appendXMLOpenTag(tag, name);
  1121. content->append(tag);
  1122. appendXMLCloseTag(tag.clear(), name);
  1123. content->setTail(tag);
  1124. }
  1125. Owned<IXmlWriter> xmlwriter = createIXmlWriterExt(0, 1, content, WTStandard);
  1126. return xmlwriter.getClear();
  1127. }
  1128. virtual void outputContent()
  1129. {
  1130. CriticalBlock b1(client->queryCrit());
  1131. bool needDelimiter = false;
  1132. ForEachItemIn(seq, contentsMap)
  1133. {
  1134. FlushingStringBuffer *content = contentsMap.item(seq);
  1135. if (content)
  1136. {
  1137. content->flush(true);
  1138. if (!this->isHTTP)
  1139. continue;
  1140. for(;;)
  1141. {
  1142. size32_t length;
  1143. void *payload = content->getPayload(length);
  1144. if (!length)
  1145. break;
  1146. client->write(payload, length, true);
  1147. }
  1148. }
  1149. }
  1150. }
  1151. virtual void finalize(unsigned seqNo)
  1152. {
  1153. if (!isHTTP)
  1154. {
  1155. CHpccNativeProtocolResponse::finalize(seqNo);
  1156. return;
  1157. }
  1158. CriticalBlock b(contentsCrit);
  1159. StringBuffer responseHead, responseTail;
  1160. if (!resultFilter.ordinality() && !(protocolFlags & HPCC_PROTOCOL_CONTROL))
  1161. {
  1162. responseHead.append("<").append(queryName);
  1163. responseHead.append("Response").append(" xmlns=\"urn:hpccsystems:ecl:").appendLower(queryName.length(), queryName.str()).append('\"');
  1164. responseHead.append(" sequence=\"").append(seqNo).append("\"><Results><Result>");
  1165. unsigned len = responseHead.length();
  1166. client->write(responseHead.detach(), len, true);
  1167. }
  1168. if (!resultFilter.ordinality())
  1169. outputContent();
  1170. if (results)
  1171. results->finalize(seqNo, NULL, resultFilter.ordinality() ? resultFilter.item(0) : NULL);
  1172. if (!resultFilter.ordinality() && !(protocolFlags & HPCC_PROTOCOL_CONTROL))
  1173. {
  1174. responseTail.append("</Result></Results></").append(queryName);
  1175. if (isHTTP)
  1176. responseTail.append("Response");
  1177. responseTail.append('>');
  1178. unsigned len = responseTail.length();
  1179. client->write(responseTail.detach(), len, true);
  1180. }
  1181. }
  1182. };
  1183. IHpccProtocolResponse *createProtocolResponse(const char *queryname, SafeSocket *client, HttpHelper &httpHelper, const IContextLogger &logctx, unsigned protocolFlags, PTreeReaderOptions xmlReadFlags)
  1184. {
  1185. StringAttr filter, tag;
  1186. httpHelper.getResultFilterAndTag(filter, tag);
  1187. if (protocolFlags & HPCC_PROTOCOL_NATIVE_RAW || protocolFlags & HPCC_PROTOCOL_NATIVE_ASCII)
  1188. return new CHpccNativeProtocolResponse(queryname, client, MarkupFmt_Unknown, protocolFlags, false, logctx, xmlReadFlags, filter, tag);
  1189. else if (httpHelper.queryResponseMlFormat()==MarkupFmt_JSON)
  1190. return new CHpccJsonResponse(queryname, client, protocolFlags, httpHelper.isHttp(), logctx, xmlReadFlags, filter, tag);
  1191. return new CHpccXmlResponse(queryname, client, protocolFlags, httpHelper.isHttp(), logctx, xmlReadFlags, filter, tag);
  1192. }
  1193. class CHttpRequestAsyncFor : public CInterface, public CAsyncFor
  1194. {
  1195. private:
  1196. const char *queryName, *queryText, *querySetName;
  1197. const IContextLogger &logctx;
  1198. IArrayOf<IPropertyTree> &requestArray;
  1199. Linked<IHpccProtocolMsgSink> sink;
  1200. Linked<IHpccProtocolMsgContext> msgctx;
  1201. SafeSocket &client;
  1202. HttpHelper &httpHelper;
  1203. PTreeReaderOptions xmlReadFlags;
  1204. unsigned &memused;
  1205. unsigned &slaveReplyLen;
  1206. CriticalSection crit;
  1207. unsigned flags;
  1208. public:
  1209. CHttpRequestAsyncFor(const char *_queryName, IHpccProtocolMsgSink *_sink, IHpccProtocolMsgContext *_msgctx, IArrayOf<IPropertyTree> &_requestArray,
  1210. SafeSocket &_client, HttpHelper &_httpHelper, unsigned _flags, unsigned &_memused, unsigned &_slaveReplyLen, const char *_queryText, const IContextLogger &_logctx, PTreeReaderOptions _xmlReadFlags, const char *_querySetName)
  1211. : sink(_sink), msgctx(_msgctx), requestArray(_requestArray), client(_client), httpHelper(_httpHelper), memused(_memused),
  1212. slaveReplyLen(_slaveReplyLen), logctx(_logctx), xmlReadFlags(_xmlReadFlags), querySetName(_querySetName), flags(_flags)
  1213. {
  1214. queryName = _queryName;
  1215. queryText = _queryText;
  1216. }
  1217. void onException(IException *E)
  1218. {
  1219. //if (!logctx.isBlind())
  1220. // logctx.CTXLOG("FAILED: %s", queryText);
  1221. StringBuffer error("EXCEPTION: ");
  1222. E->errorMessage(error);
  1223. DBGLOG("%s", error.str());
  1224. client.checkSendHttpException(httpHelper, E, queryName);
  1225. E->Release();
  1226. }
  1227. void Do(unsigned idx)
  1228. {
  1229. try
  1230. {
  1231. IPropertyTree &request = requestArray.item(idx);
  1232. Owned<IHpccProtocolResponse> protocol = createProtocolResponse(request.queryName(), &client, httpHelper, logctx, flags, xmlReadFlags);
  1233. sink->onQueryMsg(msgctx, &request, protocol, flags, xmlReadFlags, querySetName, idx, memused, slaveReplyLen);
  1234. }
  1235. catch (IException * E)
  1236. {
  1237. onException(E);
  1238. }
  1239. catch (...)
  1240. {
  1241. onException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception"));
  1242. }
  1243. }
  1244. };
  1245. enum class WhiteSpaceHandling
  1246. {
  1247. Default,
  1248. Strip,
  1249. Preserve
  1250. };
  1251. class QueryNameExtractor : implements IPTreeNotifyEvent, public CInterface
  1252. {
  1253. public:
  1254. TextMarkupFormat mlFmt;
  1255. StringAttr prefix;
  1256. StringAttr name;
  1257. unsigned headerDepth;
  1258. bool isSoap;
  1259. bool isRequestArray;
  1260. bool isRequest = false;
  1261. WhiteSpaceHandling whitespace=WhiteSpaceHandling::Default;
  1262. bool more;
  1263. public:
  1264. IMPLEMENT_IINTERFACE;
  1265. QueryNameExtractor(TextMarkupFormat _mlFmt) : mlFmt(_mlFmt), headerDepth(0), isSoap(false), isRequestArray(false), more(true)
  1266. {
  1267. }
  1268. void extractName(HttpHelper &httpHelper, const char *msg, const IContextLogger &logctx, const char *peer, unsigned port)
  1269. {
  1270. StringAttr urlName;
  1271. if (httpHelper.queryQueryName()) //"Adaptive REST" query name and attrs can come from URL
  1272. {
  1273. urlName.set(httpHelper.queryQueryName());
  1274. if (httpHelper.isMappedToInputParameter()) //this type of content can't have roxie level attrs in
  1275. {
  1276. name.set(urlName);
  1277. return;
  1278. }
  1279. }
  1280. Owned<IPullPTreeReader> parser;
  1281. if (mlFmt==MarkupFmt_JSON)
  1282. parser.setown(createPullJSONStringReader(msg, *this));
  1283. else if (mlFmt==MarkupFmt_XML)
  1284. parser.setown(createPullXMLStringReader(msg, *this));
  1285. if (!parser)
  1286. return;
  1287. while (more && parser->next());
  1288. if (urlName.length())
  1289. {
  1290. name.set(urlName);
  1291. return;
  1292. }
  1293. if (name.isEmpty())
  1294. {
  1295. const char *fmt = mlFmt==MarkupFmt_XML ? "XML" : "JSON";
  1296. IException *E = MakeStringException(-1, "ERROR: Invalid %s queryName not found - received from %s:%d - %s", fmt, peer, port, msg);
  1297. logctx.logOperatorException(E, __FILE__, __LINE__, "Invalid query %s", fmt);
  1298. throw E;
  1299. }
  1300. String nameStr(name.get());
  1301. if (nameStr.endsWith("RequestArray"))
  1302. {
  1303. isRequestArray = true;
  1304. name.set(nameStr.str(), nameStr.length() - strlen("RequestArray"));
  1305. }
  1306. else if (nameStr.endsWith("Request"))
  1307. {
  1308. isRequest = true;
  1309. name.set(nameStr.str(), nameStr.length() - strlen("Request"));
  1310. }
  1311. }
  1312. virtual void beginNode(const char *tag, offset_t startOffset)
  1313. {
  1314. if (streq(tag, "__object__"))
  1315. return;
  1316. const char *local = strchr(tag, ':');
  1317. if (local)
  1318. local++;
  1319. else
  1320. local = tag;
  1321. if (mlFmt==MarkupFmt_XML)
  1322. {
  1323. if (!isSoap && streq(local, "Envelope"))
  1324. {
  1325. isSoap=true;
  1326. return;
  1327. }
  1328. if (isSoap && streq(local, "Header"))
  1329. {
  1330. headerDepth++;
  1331. return;
  1332. }
  1333. if (isSoap && !headerDepth && streq(local, "Body"))
  1334. return;
  1335. }
  1336. if (!headerDepth)
  1337. {
  1338. name.set(local);
  1339. if (tag!=local)
  1340. prefix.set(tag, local-tag-1);
  1341. }
  1342. }
  1343. virtual void newAttribute(const char *attr, const char *value)
  1344. {
  1345. if (!name.isEmpty() && strieq(attr, "@stripWhitespaceFromStoredDataset"))
  1346. {
  1347. whitespace = strToBool(value) ? WhiteSpaceHandling::Strip : WhiteSpaceHandling::Preserve;
  1348. more = false;
  1349. }
  1350. }
  1351. virtual void beginNodeContent(const char *tag)
  1352. {
  1353. if (!name.isEmpty())
  1354. more = false;
  1355. }
  1356. virtual void endNode(const char *tag, unsigned length, const void *value, bool binary, offset_t endOffset)
  1357. {
  1358. if (!name.isEmpty())
  1359. more = false;
  1360. else if (headerDepth) //will never be true if !isSoap
  1361. {
  1362. const char *local = strchr(tag, ':');
  1363. if (local)
  1364. local++;
  1365. else
  1366. local = tag;
  1367. if (streq(local, "Header"))
  1368. headerDepth--;
  1369. }
  1370. }
  1371. };
  1372. static Owned<IActiveQueryLimiterFactory> queryLimiterFactory;
  1373. class RoxieSocketWorker : public ProtocolQueryWorker
  1374. {
  1375. SocketEndpoint ep;
  1376. Owned<SafeSocket> client;
  1377. Owned<IHpccNativeProtocolMsgSink> sink;
  1378. public:
  1379. RoxieSocketWorker(ProtocolSocketListener *_pool, SocketEndpoint &_ep)
  1380. : ProtocolQueryWorker(_pool), ep(_ep)
  1381. {
  1382. sink.set(dynamic_cast<IHpccNativeProtocolMsgSink*>(_pool->queryMsgSink()));
  1383. }
  1384. // interface IPooledThread
  1385. virtual void init(void *_r)
  1386. {
  1387. client.setown(new CSafeSocket((ISocket *) _r));
  1388. ProtocolQueryWorker::init(_r);
  1389. }
  1390. virtual void main()
  1391. {
  1392. doMain("");
  1393. }
  1394. virtual void runOnce(const char *query)
  1395. {
  1396. doMain(query);
  1397. }
  1398. private:
  1399. static void sendHttpServerTooBusy(SafeSocket &client, const IContextLogger &logctx)
  1400. {
  1401. StringBuffer message;
  1402. message.append("HTTP/1.0 503 Server Too Busy\r\n\r\n");
  1403. message.append("Server too busy, please try again later");
  1404. StringBuffer err("Too many active queries"); // write out Too many active queries - make searching for this error consistent
  1405. if (!global->trapTooManyActiveQueries)
  1406. {
  1407. err.appendf(" %s", message.str());
  1408. logctx.CTXLOG("%s", err.str());
  1409. }
  1410. else
  1411. {
  1412. IException *E = MakeStringException(ROXIE_TOO_MANY_QUERIES, "%s", err.str());
  1413. logctx.logOperatorException(E, __FILE__, __LINE__, "%s", message.str());
  1414. E->Release();
  1415. }
  1416. try
  1417. {
  1418. client.write(message.str(), message.length());
  1419. }
  1420. catch (IException *E)
  1421. {
  1422. logctx.logOperatorException(E, __FILE__, __LINE__, "Exception caught in sendHttpServerTooBusy");
  1423. E->Release();
  1424. }
  1425. catch (...)
  1426. {
  1427. logctx.logOperatorException(NULL, __FILE__, __LINE__, "sendHttpServerTooBusy write failed (Unknown exception)");
  1428. }
  1429. }
  1430. void skipProtocolRoot(Owned<IPropertyTree> &queryPT, HttpHelper &httpHelper, const char *queryName)
  1431. {
  1432. if (queryPT)
  1433. {
  1434. const char *tagName = queryPT->queryName();
  1435. if (httpHelper.isHttp())
  1436. {
  1437. if (httpHelper.queryRequestMlFormat()==MarkupFmt_JSON)
  1438. {
  1439. if (strieq(tagName, "__array__"))
  1440. throw MakeStringException(ROXIE_DATA_ERROR, "JSON request array not implemented");
  1441. if (strieq(tagName, "__object__"))
  1442. {
  1443. queryPT.setown(queryPT->getPropTree("*[1]"));
  1444. if (!queryPT)
  1445. throw MakeStringException(ROXIE_DATA_ERROR, "Malformed JSON request (missing Body)");
  1446. }
  1447. }
  1448. else
  1449. {
  1450. if (strieq(tagName, "envelope"))
  1451. queryPT.setown(queryPT->getPropTree("Body/*"));
  1452. else if (!strnicmp(httpHelper.queryContentType(), "application/soap", strlen("application/soap")))
  1453. throw MakeStringException(ROXIE_DATA_ERROR, "Malformed SOAP request");
  1454. if (!queryPT)
  1455. throw MakeStringException(ROXIE_DATA_ERROR, "Malformed SOAP request (missing Body)");
  1456. queryPT->removeProp("@xmlns:m");
  1457. queryPT->renameProp("/", queryName); // reset the name of the tree
  1458. }
  1459. }
  1460. }
  1461. else
  1462. throw MakeStringException(ROXIE_DATA_ERROR, "Malformed request");
  1463. }
  1464. void sanitizeQuery(Owned<IPropertyTree> &queryPT, StringAttr &queryName, StringBuffer &saniText, HttpHelper &httpHelper, const char *&uid, bool &isBlind, bool &isDebug)
  1465. {
  1466. if (queryPT)
  1467. {
  1468. // convert to XML with attribute values in single quotes - makes replaying queries easier
  1469. uid = queryPT->queryProp("@uid");
  1470. if (!uid)
  1471. uid = queryPT->queryProp("_TransactionId");
  1472. isBlind = queryPT->getPropBool("@blind", false) || queryPT->getPropBool("_blind", false);
  1473. isDebug = queryPT->getPropBool("@debug") || queryPT->getPropBool("_Probe", false);
  1474. toXML(queryPT, saniText, 0, isBlind ? (XML_SingleQuoteAttributeValues | XML_Sanitize) : XML_SingleQuoteAttributeValues);
  1475. }
  1476. }
  1477. void createQueryPTree(Owned<IPropertyTree> &queryPT, HttpHelper &httpHelper, const char *text, byte flags, byte options, const char *queryName)
  1478. {
  1479. StringBuffer logxml;
  1480. if (httpHelper.queryRequestMlFormat()==MarkupFmt_URL)
  1481. {
  1482. queryPT.setown(httpHelper.createPTreeFromParameters(flags));
  1483. toXML(queryPT, logxml);
  1484. DBGLOG("%s", logxml.str());
  1485. return;
  1486. }
  1487. if (httpHelper.queryRequestMlFormat()==MarkupFmt_JSON)
  1488. queryPT.setown(createPTreeFromJSONString(text, flags, (PTreeReaderOptions) options));
  1489. else
  1490. queryPT.setown(createPTreeFromXMLString(text, flags, (PTreeReaderOptions) options));
  1491. queryPT.setown(httpHelper.checkAddWrapperForAdaptiveInput(queryPT.getClear(), flags));
  1492. skipProtocolRoot(queryPT, httpHelper, queryName);
  1493. if (queryPT->hasProp("_stripWhitespaceFromStoredDataset"))
  1494. {
  1495. bool stripTag = queryPT->getPropBool("_stripWhitespaceFromStoredDataset");
  1496. bool stripFlag = (options & ptr_ignoreWhiteSpace) != 0;
  1497. if (stripTag != stripFlag)
  1498. {
  1499. if (stripTag)
  1500. options |= ptr_ignoreWhiteSpace;
  1501. else
  1502. options &= ~ptr_ignoreWhiteSpace;
  1503. //The tag _stripWhitespaceFromStoredDataset can appear anywhere at the same level as query inputs
  1504. //it can't be checked until after parsing the full request, so if it changes the parse flags
  1505. //we have to parse the request again now
  1506. createQueryPTree(queryPT, httpHelper, text, flags, options, queryName);
  1507. }
  1508. }
  1509. }
  1510. void doMain(const char *runQuery)
  1511. {
  1512. StringBuffer rawText(runQuery);
  1513. unsigned memused = 0;
  1514. IpAddress peer;
  1515. bool continuationNeeded = false;
  1516. bool isStatus = false;
  1517. Owned<IHpccProtocolMsgContext> msgctx = sink->createMsgContext(startTime);
  1518. IContextLogger &logctx = *msgctx->queryLogContext();
  1519. readAnother:
  1520. unsigned slavesReplyLen = 0;
  1521. StringArray allTargets;
  1522. sink->getTargetNames(allTargets);
  1523. HttpHelper httpHelper(&allTargets);
  1524. try
  1525. {
  1526. if (client)
  1527. {
  1528. client->querySocket()->getPeerAddress(peer);
  1529. if (!client->readBlock(rawText.clear(), WAIT_FOREVER, &httpHelper, continuationNeeded, isStatus, global->maxBlockSize))
  1530. {
  1531. if (traceLevel > 8)
  1532. {
  1533. StringBuffer b;
  1534. DBGLOG("No data reading query from socket");
  1535. }
  1536. client.clear();
  1537. return;
  1538. }
  1539. }
  1540. if (continuationNeeded)
  1541. {
  1542. qstart = msTick();
  1543. time(&startTime);
  1544. }
  1545. }
  1546. catch (IException * E)
  1547. {
  1548. if (traceLevel > 0)
  1549. {
  1550. StringBuffer b;
  1551. DBGLOG("Error reading query from socket: %s", E->errorMessage(b).str());
  1552. }
  1553. E->Release();
  1554. client.clear();
  1555. return;
  1556. }
  1557. bool isHTTP = httpHelper.isHttp();
  1558. TextMarkupFormat mlResponseFmt = MarkupFmt_Unknown;
  1559. TextMarkupFormat mlRequestFmt = MarkupFmt_Unknown;
  1560. if (!isStatus)
  1561. {
  1562. if (!isHTTP)
  1563. mlResponseFmt = mlRequestFmt = MarkupFmt_XML;
  1564. else
  1565. {
  1566. mlResponseFmt = httpHelper.queryResponseMlFormat();
  1567. mlRequestFmt = httpHelper.queryRequestMlFormat();
  1568. }
  1569. }
  1570. bool failed = false;
  1571. bool isRequest = false;
  1572. bool isRequestArray = false;
  1573. bool isBlind = false;
  1574. bool isDebug = false;
  1575. unsigned protocolFlags = isHTTP ? 0 : HPCC_PROTOCOL_NATIVE;
  1576. Owned<IPropertyTree> queryPT;
  1577. StringBuffer sanitizedText;
  1578. StringBuffer peerStr;
  1579. peer.getIpText(peerStr);
  1580. const char *uid = "-";
  1581. StringAttr queryName;
  1582. StringAttr queryPrefix;
  1583. WhiteSpaceHandling whitespace = WhiteSpaceHandling::Default;
  1584. try
  1585. {
  1586. if (httpHelper.isHttpGet() || httpHelper.isFormPost())
  1587. {
  1588. queryName.set(httpHelper.queryQueryName());
  1589. if (httpHelper.isControlUrl())
  1590. queryPrefix.set("control");
  1591. }
  1592. else if (mlRequestFmt==MarkupFmt_XML || mlRequestFmt==MarkupFmt_JSON)
  1593. {
  1594. QueryNameExtractor extractor(mlRequestFmt);
  1595. extractor.extractName(httpHelper, rawText.str(), logctx, peerStr, ep.port);
  1596. queryName.set(extractor.name);
  1597. queryPrefix.set(extractor.prefix);
  1598. whitespace = extractor.whitespace;
  1599. isRequest = extractor.isRequest;
  1600. isRequestArray = extractor.isRequestArray;
  1601. if (httpHelper.isHttp())
  1602. httpHelper.setUseEnvelope(extractor.isSoap);
  1603. }
  1604. if (streq(queryPrefix.str(), "control"))
  1605. {
  1606. if (httpHelper.isHttp())
  1607. client->setHttpMode(queryName, false, httpHelper);
  1608. bool aclupdate = strieq(queryName, "aclupdate"); //ugly
  1609. byte iptFlags = aclupdate ? ipt_caseInsensitive : 0;
  1610. createQueryPTree(queryPT, httpHelper, rawText, iptFlags, (PTreeReaderOptions)(ptr_ignoreWhiteSpace|ptr_ignoreNameSpaces), queryName);
  1611. //IPropertyTree *root = queryPT;
  1612. if (!strchr(queryName, ':'))
  1613. {
  1614. VStringBuffer fullname("control:%s", queryName.str()); //just easier to keep for debugging and internal checking
  1615. queryPT->renameProp("/", fullname);
  1616. }
  1617. Owned<IHpccProtocolResponse> protocol = createProtocolResponse(queryPT->queryName(), client, httpHelper, logctx, protocolFlags | HPCC_PROTOCOL_CONTROL, global->defaultXmlReadFlags);
  1618. sink->onControlMsg(msgctx, queryPT, protocol);
  1619. protocol->finalize(0);
  1620. if (streq(queryName, "lock") || streq(queryName, "childlock"))
  1621. goto readAnother;
  1622. }
  1623. else if (isStatus)
  1624. {
  1625. client->write("OK", 2);
  1626. }
  1627. else
  1628. {
  1629. StringBuffer querySetName;
  1630. if (isHTTP)
  1631. {
  1632. client->setHttpMode(queryName, isRequestArray, httpHelper);
  1633. querySetName.set(httpHelper.queryTarget());
  1634. if (querySetName.length())
  1635. {
  1636. const char *target = global->targetAliases->queryProp(querySetName.str());
  1637. if (target)
  1638. querySetName.set(target);
  1639. }
  1640. }
  1641. msgctx->initQuery(querySetName, queryName); //needed here to allow checking hash options
  1642. if (whitespace == WhiteSpaceHandling::Default) //value in the request wins
  1643. whitespace = msgctx->getStripWhitespace() ? WhiteSpaceHandling::Strip : WhiteSpaceHandling::Preserve; //might be changed by hash option, returns default otherwise
  1644. unsigned readFlags = (unsigned) global->defaultXmlReadFlags | ptr_ignoreNameSpaces;
  1645. readFlags &= ~ptr_ignoreWhiteSpace;
  1646. readFlags |= (whitespace == WhiteSpaceHandling::Strip ? ptr_ignoreWhiteSpace : ptr_none);
  1647. try
  1648. {
  1649. createQueryPTree(queryPT, httpHelper, rawText.str(), ipt_caseInsensitive, (PTreeReaderOptions)readFlags, queryName);
  1650. }
  1651. catch (IException *E)
  1652. {
  1653. logctx.logOperatorException(E, __FILE__, __LINE__, "Invalid XML received from %s:%d - %s", peerStr.str(), listener->queryPort(), rawText.str());
  1654. logctx.CTXLOG("ERROR: Invalid XML received from %s:%d - %s", peerStr.str(), listener->queryPort(), rawText.str());
  1655. throw;
  1656. }
  1657. uid = NULL;
  1658. sanitizeQuery(queryPT, queryName, sanitizedText, httpHelper, uid, isBlind, isDebug);
  1659. if (uid)
  1660. msgctx->setTransactionId(uid);
  1661. else
  1662. uid = "-";
  1663. sink->checkAccess(peer, queryName, sanitizedText, isBlind);
  1664. if (isDebug)
  1665. msgctx->verifyAllowDebug();
  1666. isBlind = msgctx->checkSetBlind(isBlind);
  1667. if (msgctx->logFullQueries())
  1668. {
  1669. StringBuffer soapStr;
  1670. (isRequest) ? soapStr.append("SoapRequest") : (isRequestArray) ? soapStr.append("SoapRequest") : soapStr.clear();
  1671. logctx.CTXLOG("%s %s:%d %s %s %s", isBlind ? "BLIND:" : "QUERY:", peerStr.str(), listener->queryPort(), uid, soapStr.str(), sanitizedText.str());
  1672. }
  1673. if (strieq(queryPrefix.str(), "debug"))
  1674. {
  1675. FlushingStringBuffer response(client, false, MarkupFmt_XML, false, isHTTP, logctx);
  1676. response.startDataset("Debug", NULL, (unsigned) -1);
  1677. CommonXmlWriter out(0, 1);
  1678. sink->onDebugMsg(msgctx, uid, queryPT, out);
  1679. response.append(out.str());
  1680. }
  1681. Owned<IActiveQueryLimiter> l;
  1682. if (queryLimiterFactory)
  1683. l.setown(queryLimiterFactory->create(listener));
  1684. if (l && !l->isAccepted())
  1685. {
  1686. if (isHTTP)
  1687. {
  1688. sendHttpServerTooBusy(*client, logctx);
  1689. logctx.CTXLOG("FAILED: %s", sanitizedText.str());
  1690. logctx.CTXLOG("EXCEPTION: Too many active queries");
  1691. }
  1692. else
  1693. {
  1694. IException *e = MakeStringException(ROXIE_TOO_MANY_QUERIES, "Too many active queries");
  1695. if (msgctx->trapTooManyActiveQueries())
  1696. logctx.logOperatorException(e, __FILE__, __LINE__, NULL);
  1697. throw e;
  1698. }
  1699. }
  1700. else
  1701. {
  1702. int bindCores = queryPT->getPropInt("@bindCores", msgctx->getBindCores());
  1703. if (bindCores > 0)
  1704. listener->setThreadAffinity(bindCores);
  1705. IArrayOf<IPropertyTree> requestArray;
  1706. if (isHTTP)
  1707. {
  1708. if (isRequestArray)
  1709. {
  1710. StringBuffer reqIterString;
  1711. reqIterString.append(queryName).append("Request");
  1712. Owned<IPropertyTreeIterator> reqIter = queryPT->getElements(reqIterString.str());
  1713. ForEach(*reqIter)
  1714. {
  1715. IPropertyTree *fixedreq = createPTree(queryName, ipt_caseInsensitive);
  1716. Owned<IPropertyTreeIterator> iter = reqIter->query().getElements("*");
  1717. ForEach(*iter)
  1718. {
  1719. fixedreq->addPropTree(iter->query().queryName(), LINK(&iter->query()));
  1720. }
  1721. requestArray.append(*fixedreq);
  1722. }
  1723. }
  1724. else
  1725. {
  1726. IPropertyTree *fixedreq = createPTree(queryName, ipt_caseInsensitive);
  1727. Owned<IPropertyTreeIterator> iter = queryPT->getElements("*");
  1728. ForEach(*iter)
  1729. {
  1730. fixedreq->addPropTree(iter->query().queryName(), LINK(&iter->query()));
  1731. }
  1732. requestArray.append(*fixedreq);
  1733. }
  1734. if (httpHelper.getTrim())
  1735. protocolFlags |= HPCC_PROTOCOL_TRIM;
  1736. }
  1737. else
  1738. {
  1739. const char *format = queryPT->queryProp("@format");
  1740. if (format)
  1741. {
  1742. if (stricmp(format, "raw") == 0)
  1743. {
  1744. protocolFlags |= HPCC_PROTOCOL_NATIVE_RAW;
  1745. if (client) //not stand alone roxie exe
  1746. protocolFlags |= HPCC_PROTOCOL_BLOCKED;
  1747. mlResponseFmt = MarkupFmt_Unknown;
  1748. }
  1749. else if (stricmp(format, "bxml") == 0)
  1750. {
  1751. protocolFlags |= HPCC_PROTOCOL_BLOCKED;
  1752. mlResponseFmt = MarkupFmt_XML;
  1753. }
  1754. else if (stricmp(format, "ascii") == 0)
  1755. {
  1756. protocolFlags |= HPCC_PROTOCOL_NATIVE_ASCII;
  1757. mlResponseFmt = MarkupFmt_Unknown;
  1758. }
  1759. else if (stricmp(format, "xml") != 0) // xml is the default
  1760. throw MakeStringException(ROXIE_INVALID_INPUT, "Unsupported format specified: %s", format);
  1761. }
  1762. if (queryPT->getPropBool("@trim", false))
  1763. protocolFlags |= HPCC_PROTOCOL_TRIM;
  1764. msgctx->setIntercept(queryPT->getPropBool("@log", false));
  1765. msgctx->setTraceLevel(queryPT->getPropInt("@traceLevel", logctx.queryTraceLevel()));
  1766. }
  1767. msgctx->noteQueryActive();
  1768. if (isHTTP)
  1769. {
  1770. CHttpRequestAsyncFor af(queryName, sink, msgctx, requestArray, *client, httpHelper, protocolFlags, memused, slavesReplyLen, sanitizedText, logctx, (PTreeReaderOptions)readFlags, querySetName);
  1771. af.For(requestArray.length(), global->numRequestArrayThreads);
  1772. }
  1773. else
  1774. {
  1775. Owned<IHpccProtocolResponse> protocol = createProtocolResponse(queryPT->queryName(), client, httpHelper, logctx, protocolFlags, (PTreeReaderOptions)readFlags);
  1776. sink->onQueryMsg(msgctx, queryPT, protocol, protocolFlags, (PTreeReaderOptions)readFlags, querySetName, 0, memused, slavesReplyLen);
  1777. }
  1778. }
  1779. }
  1780. }
  1781. catch (IException * E)
  1782. {
  1783. failed = true;
  1784. logctx.CTXLOG("FAILED: %s", sanitizedText.str());
  1785. StringBuffer error;
  1786. E->errorMessage(error);
  1787. logctx.CTXLOG("EXCEPTION: %s", error.str());
  1788. unsigned code = E->errorCode();
  1789. if (QUERYINTERFACE(E, ISEH_Exception))
  1790. code = ROXIE_INTERNAL_ERROR;
  1791. else if (QUERYINTERFACE(E, IOutOfMemException))
  1792. code = ROXIE_MEMORY_ERROR;
  1793. if (client)
  1794. {
  1795. if (isHTTP)
  1796. client->checkSendHttpException(httpHelper, E, queryName);
  1797. else
  1798. client->sendException("Roxie", code, error.str(), (protocolFlags & HPCC_PROTOCOL_NATIVE_RAW), logctx);
  1799. }
  1800. else
  1801. {
  1802. fprintf(stderr, "EXCEPTION: %s\n", error.str());
  1803. }
  1804. E->Release();
  1805. }
  1806. #ifndef _DEBUG
  1807. catch(...)
  1808. {
  1809. failed = true;
  1810. logctx.CTXLOG("FAILED: %s", sanitizedText.str());
  1811. logctx.CTXLOG("EXCEPTION: Unknown exception");
  1812. {
  1813. if (isHTTP)
  1814. {
  1815. Owned<IException> E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception");
  1816. client->checkSendHttpException(httpHelper, E, queryName);
  1817. }
  1818. else
  1819. client->sendException("Roxie", ROXIE_INTERNAL_ERROR, "Unknown exception", (protocolFlags & HPCC_PROTOCOL_BLOCKED), logctx);
  1820. }
  1821. }
  1822. #endif
  1823. if (isHTTP)
  1824. {
  1825. try
  1826. {
  1827. client->flush();
  1828. }
  1829. catch (IException * E)
  1830. {
  1831. StringBuffer error("RoxieSocketWorker failed to write to socket ");
  1832. E->errorMessage(error);
  1833. logctx.CTXLOG("%s", error.str());
  1834. E->Release();
  1835. }
  1836. catch(...)
  1837. {
  1838. logctx.CTXLOG("RoxieSocketWorker failed to write to socket (Unknown exception)");
  1839. }
  1840. }
  1841. unsigned bytesOut = client? client->bytesOut() : 0;
  1842. unsigned elapsed = msTick() - qstart;
  1843. sink->noteQuery(msgctx.get(), peerStr, failed, bytesOut, elapsed, memused, slavesReplyLen, continuationNeeded);
  1844. if (continuationNeeded)
  1845. {
  1846. rawText.clear();
  1847. goto readAnother;
  1848. }
  1849. else
  1850. {
  1851. try
  1852. {
  1853. if (client && !isHTTP && !isStatus)
  1854. {
  1855. if (msgctx->getIntercept())
  1856. {
  1857. FlushingStringBuffer response(client, (protocolFlags & HPCC_PROTOCOL_BLOCKED), mlResponseFmt, (protocolFlags & HPCC_PROTOCOL_NATIVE_RAW), false, logctx);
  1858. response.startDataset("Tracing", NULL, (unsigned) -1);
  1859. msgctx->outputLogXML(response);
  1860. }
  1861. unsigned replyLen = 0;
  1862. client->write(&replyLen, sizeof(replyLen));
  1863. }
  1864. client.clear();
  1865. }
  1866. catch (IException * E)
  1867. {
  1868. StringBuffer error("RoxieSocketWorker failed to close socket ");
  1869. E->errorMessage(error);
  1870. logctx.CTXLOG("%s", error.str()); // MORE - audience?
  1871. E->Release();
  1872. }
  1873. catch(...)
  1874. {
  1875. logctx.CTXLOG("RoxieSocketWorker failed to close socket (Unknown exception)"); // MORE - audience?
  1876. }
  1877. }
  1878. }
  1879. };
  1880. IPooledThread *ProtocolSocketListener::createNew()
  1881. {
  1882. return new RoxieSocketWorker(this, ep);
  1883. }
  1884. void ProtocolSocketListener::runOnce(const char *query)
  1885. {
  1886. Owned<RoxieSocketWorker> p = new RoxieSocketWorker(this, ep);
  1887. p->runOnce(query);
  1888. }
  1889. IHpccProtocolListener *createProtocolListener(const char *protocol, IHpccProtocolMsgSink *sink, unsigned port, unsigned listenQueue)
  1890. {
  1891. if (traceLevel)
  1892. DBGLOG("Creating Roxie socket listener, protocol %s, pool size %d, listen queue %d%s", protocol, sink->getPoolSize(), listenQueue, sink->getIsSuspended() ? " SUSPENDED":"");
  1893. return new ProtocolSocketListener(sink, port, listenQueue);
  1894. }
  1895. extern IHpccProtocolPlugin *loadHpccProtocolPlugin(IHpccProtocolPluginContext *ctx, IActiveQueryLimiterFactory *_limiterFactory)
  1896. {
  1897. if (!queryLimiterFactory)
  1898. queryLimiterFactory.set(_limiterFactory);
  1899. if (global)
  1900. return global.getLink();
  1901. if (!ctx)
  1902. return NULL;
  1903. global.setown(new CHpccProtocolPlugin(*ctx));
  1904. return global.getLink();
  1905. }
  1906. //================================================================================================================================