ccdprotocol.cpp 73 KB

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