testsocket.cpp 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. #include <platform.h>
  14. #include <stdio.h>
  15. #include "jmisc.hpp"
  16. #include "jlib.hpp"
  17. #include "jsocket.hpp"
  18. #include "jstream.ipp"
  19. #include "portlist.h"
  20. #include "jdebug.hpp"
  21. #include "jthread.hpp"
  22. #include "jfile.hpp"
  23. #include "securesocket.hpp"
  24. bool abortEarly = false;
  25. bool forceHTTP = false;
  26. bool useSSL = false;
  27. bool abortAfterFirst = false;
  28. bool echoResults = false;
  29. bool saveResults = true;
  30. bool showTiming = false;
  31. bool showStatus = true;
  32. bool sendToSocket = false;
  33. bool parallelBlocked = false;
  34. bool justResults = false;
  35. bool multiThread = false;
  36. bool manyResults = false;
  37. bool sendFileAfterQuery = false;
  38. bool doLock = false;
  39. bool roxieLogMode = false;
  40. bool rawOnly = false;
  41. bool rawSend = false;
  42. bool remoteStreamForceResend = false;
  43. bool remoteStreamSendCursor = false;
  44. StringBuffer sendFileName;
  45. StringAttr queryNameOverride;
  46. unsigned delay = 0;
  47. unsigned runningQueries;
  48. unsigned multiThreadMax;
  49. unsigned maxLineSize = 10000000;
  50. Owned<ISocket> persistSocket;
  51. bool persistConnections = false;
  52. Owned<ISecureSocketContext> persistSecureContext;
  53. Owned<ISecureSocket> persistSSock;
  54. int repeats = 0;
  55. StringBuffer queryPrefix;
  56. Semaphore okToSend;
  57. Semaphore done;
  58. Semaphore finishedReading;
  59. FILE * trace;
  60. CriticalSection traceCrit;
  61. //---------------------------------------------------------------------------
  62. void SplitIpPort(StringAttr & ip, unsigned & port, const char * address)
  63. {
  64. const char * colon = strchr(address, ':');
  65. if (colon)
  66. {
  67. ip.set(address,colon-address);
  68. port = atoi(colon+1);
  69. }
  70. else
  71. ip.set(address);
  72. }
  73. void showMessage(const char * text)
  74. {
  75. if (!justResults)
  76. {
  77. if (echoResults)
  78. fwrite(text, strlen(text), 1, stdout);
  79. if (saveResults && trace != NULL)
  80. fwrite(text, strlen(text), 1, trace);
  81. }
  82. }
  83. void sendFile(const char * filename, ISocket * socket)
  84. {
  85. FILE *in = fopen(filename, "rb");
  86. unsigned size = 0;
  87. void * buff = NULL;
  88. if (in)
  89. {
  90. fseek(in, 0, SEEK_END);
  91. size = ftell(in);
  92. fseek(in, 0, SEEK_SET);
  93. buff = malloc(size);
  94. size_t numRead = fread(buff, 1, size, in);
  95. fclose(in);
  96. if (numRead != size)
  97. {
  98. printf("read from file %s failed (%u/%u)\n", filename, (unsigned)numRead, size);
  99. size = 0;
  100. }
  101. }
  102. else
  103. printf("read from file %s failed\n", filename);
  104. unsigned dllLen = size;
  105. _WINREV(dllLen);
  106. socket->write(&dllLen, sizeof(dllLen));
  107. socket->write(buff, size);
  108. free(buff);
  109. }
  110. #define CHUNK_SIZE 152*2000
  111. void sendFileChunk(const char * filename, offset_t offset, ISocket * socket)
  112. {
  113. FILE *in = fopen(filename, "rb");
  114. unsigned size = 0;
  115. void * buff = NULL;
  116. if (in)
  117. {
  118. fseek(in, 0, SEEK_END);
  119. offset_t endOffset = ftell(in);
  120. fseek(in, offset, SEEK_SET);
  121. if (endOffset < offset)
  122. size = 0;
  123. else
  124. size = (unsigned)(endOffset - offset);
  125. if (size > CHUNK_SIZE)
  126. size = CHUNK_SIZE;
  127. buff = malloc(size);
  128. size_t numRead = fread(buff, 1, size, in);
  129. fclose(in);
  130. if (numRead != size)
  131. {
  132. printf("read from file %s failed (%u/%u)\n", filename, (unsigned)numRead, size);
  133. size = 0;
  134. }
  135. }
  136. else
  137. printf("read from file %s failed\n", filename);
  138. if (size > 0)
  139. {
  140. MemoryBuffer sendBuffer;
  141. unsigned rev = size + strlen(filename) + 10;
  142. rev |= 0x80000000;
  143. _WINREV(rev);
  144. sendBuffer.append(rev);
  145. sendBuffer.append('R');
  146. rev = 0; // should put the sequence number here
  147. _WINREV(rev);
  148. sendBuffer.append(rev);
  149. rev = 0; // should put the # of recs in msg here
  150. _WINREV(rev);
  151. sendBuffer.append(rev);
  152. sendBuffer.append(strlen(filename)+1, filename);
  153. sendBuffer.append(size, buff);
  154. socket->write(sendBuffer.toByteArray(), sendBuffer.length());
  155. }
  156. else
  157. {
  158. unsigned zeroLen = 0;
  159. socket->write(&zeroLen, sizeof(zeroLen));
  160. }
  161. free(buff);
  162. }
  163. int readResults(ISocket * socket, bool readBlocked, bool useHTTP, StringBuffer &result, const char *query, size32_t queryLen)
  164. {
  165. if (readBlocked)
  166. socket->set_block_mode(BF_SYNC_TRANSFER_PULL,0,60*1000);
  167. StringBuffer remoteReadCursor;
  168. unsigned len;
  169. bool is_status;
  170. bool isBlockedResult;
  171. for (;;)
  172. {
  173. if (delay)
  174. MilliSleep(delay);
  175. is_status = false;
  176. isBlockedResult = false;
  177. try
  178. {
  179. if (useHTTP)
  180. len = 0x10000;
  181. else if (readBlocked)
  182. len = socket->receive_block_size();
  183. else
  184. {
  185. socket->read(&len, sizeof(len));
  186. _WINREV(len);
  187. }
  188. }
  189. catch(IException * e)
  190. {
  191. if (manyResults)
  192. showMessage("End of result multiple set\n");
  193. else
  194. pexception("failed to read len data", e);
  195. e->Release();
  196. return 1;
  197. }
  198. if (len == 0)
  199. {
  200. if (manyResults)
  201. {
  202. showMessage("----End of result set----\n");
  203. continue;
  204. }
  205. break;
  206. }
  207. bool isSpecial = false;
  208. bool pluginRequest = false;
  209. bool dataBlockRequest = false;
  210. bool remoteReadRequest = false;
  211. if (len & 0x80000000)
  212. {
  213. unsigned char flag;
  214. isSpecial = true;
  215. socket->read(&flag, sizeof(flag));
  216. switch (flag)
  217. {
  218. case '-':
  219. if (echoResults)
  220. fputs("Error:", stdout);
  221. if (saveResults && trace != NULL)
  222. fputs("Error:", trace);
  223. break;
  224. case 'D':
  225. showMessage("request for datablock\n");
  226. dataBlockRequest = true;
  227. break;
  228. case 'P':
  229. showMessage("request for plugin\n");
  230. pluginRequest = true;
  231. break;
  232. case 'S':
  233. if (showStatus)
  234. showMessage("Status:");
  235. is_status=true;
  236. break;
  237. case 'T':
  238. showMessage("Timing:\n");
  239. break;
  240. case 'X':
  241. showMessage("---Compound query finished---\n");
  242. return 1;
  243. case 'R':
  244. isBlockedResult = true;
  245. break;
  246. case 'J':
  247. remoteReadRequest = true;
  248. break;
  249. }
  250. len &= 0x7FFFFFFF;
  251. len--; // flag already read
  252. }
  253. MemoryBuffer mb;
  254. mb.setEndian(__BIG_ENDIAN);
  255. char *mem = (char *)mb.reserveTruncate(len+1);
  256. char * t = mem;
  257. size32_t sendlen = len;
  258. t[len]=0;
  259. try
  260. {
  261. if (useHTTP)
  262. {
  263. try
  264. {
  265. socket->read(t, 0, len, sendlen);
  266. }
  267. catch (IException *E)
  268. {
  269. if (E->errorCode()!= JSOCKERR_graceful_close)
  270. throw;
  271. E->Release();
  272. break;
  273. }
  274. if (!sendlen)
  275. break;
  276. }
  277. else if (readBlocked)
  278. socket->receive_block(t, len);
  279. else
  280. socket->read(t, len);
  281. }
  282. catch(IException * e)
  283. {
  284. pexception("failed to read data", e);
  285. e->Release();
  286. return 1;
  287. }
  288. if (pluginRequest)
  289. {
  290. //Not very robust! A poor man's implementation for testing...
  291. StringBuffer dllname, libname;
  292. const char * dot = strchr(t, '.');
  293. dllname.append("\\edata\\bin\\debug\\").append(t);
  294. libname.append("\\edata\\bin\\debug\\").append(dot-t,t).append(".lib");
  295. sendFile(dllname.str(), socket);
  296. sendFile(libname.str(), socket);
  297. }
  298. else if (dataBlockRequest)
  299. {
  300. //Not very robust! A poor man's implementation for testing...
  301. offset_t offset;
  302. mb.read(offset);
  303. sendFileChunk((const char *)mb.readDirect(offset), offset, socket);
  304. }
  305. else if (remoteReadRequest)
  306. {
  307. Owned<IPropertyTree> requestTree = createPTreeFromJSONString(queryLen, query);
  308. Owned<IPropertyTree> responseTree; // used if response is xml or json
  309. const char *outputFmtStr = requestTree->queryProp("format");
  310. const char *response = nullptr;
  311. if (!outputFmtStr || strieq("xml", outputFmtStr))
  312. {
  313. response = (const char *)mb.readDirect(len);
  314. responseTree.setown(createPTreeFromXMLString(len, response));
  315. assertex(responseTree);
  316. }
  317. else if (strieq("json", outputFmtStr))
  318. {
  319. response = (const char *)mb.readDirect(len);
  320. // JCSMORE - json string coming back from IXmlWriterExt is always rootless the moment, so workaround it by supplying ptr_noRoot to reader
  321. // writer should be fixed.
  322. Owned<IPropertyTree> tree = createPTreeFromJSONString(len, response, ipt_none, (PTreeReaderOptions)(ptr_ignoreWhiteSpace|ptr_noRoot));
  323. responseTree.setown(tree->getPropTree("Response"));
  324. assertex(responseTree);
  325. }
  326. else if (!strieq("binary", outputFmtStr))
  327. throw MakeStringException(0, "Unknown output format: %s", outputFmtStr);
  328. unsigned cursorHandle;
  329. if (responseTree)
  330. cursorHandle = responseTree->getPropInt("cursor");
  331. else
  332. mb.read(cursorHandle);
  333. bool retrySend = false;
  334. if (cursorHandle)
  335. {
  336. PROGLOG("Got handle back: %u; len=%u", cursorHandle, len);
  337. StringBuffer xml;
  338. if (responseTree)
  339. {
  340. if (echoResults && response)
  341. {
  342. fputs(response, stdout);
  343. fflush(stdout);
  344. }
  345. if (!responseTree->getProp("cursorBin", remoteReadCursor))
  346. break;
  347. }
  348. else
  349. {
  350. size32_t dataLen;
  351. mb.read(dataLen);
  352. if (!dataLen)
  353. break;
  354. const void *rowData = mb.readDirect(dataLen);
  355. // JCSMORE - output binary row data?
  356. // cursor
  357. size32_t cursorLen;
  358. mb.read(cursorLen);
  359. if (!cursorLen)
  360. break;
  361. const void *cursor = mb.readDirect(cursorLen);
  362. JBASE64_Encode(cursor, cursorLen, remoteReadCursor);
  363. }
  364. if (remoteStreamForceResend)
  365. cursorHandle = NotFound; // fake that it's a handle dafilesrv doesn't know about
  366. Owned<IPropertyTree> requestTree = createPTree();
  367. requestTree->setPropInt("cursor", cursorHandle);
  368. // Only the handle is needed for continuation, but this tests the behaviour of some clients which may send cursor per request (e.g. to refresh)
  369. if (remoteStreamSendCursor)
  370. requestTree->setProp("cursorBin", remoteReadCursor);
  371. requestTree->setProp("format", outputFmtStr);
  372. StringBuffer requestStr;
  373. toJSON(requestTree, requestStr);
  374. #ifdef _DEBUG
  375. fputs("\nNext request:", stdout);
  376. fputs(requestStr, stdout);
  377. fputs("\n", stdout);
  378. fflush(stdout);
  379. #endif
  380. sendlen = requestStr.length();
  381. _WINREV(sendlen);
  382. try
  383. {
  384. if (!rawSend && !useHTTP)
  385. socket->write(&sendlen, sizeof(sendlen));
  386. socket->write(requestStr.str(), requestStr.length());
  387. }
  388. catch (IJSOCK_Exception *e)
  389. {
  390. retrySend = true;
  391. EXCLOG(e, nullptr);
  392. e->Release();
  393. }
  394. }
  395. else // dafilesrv didn't know who I was, resent query + serialized cursor
  396. retrySend = true;
  397. if (retrySend)
  398. {
  399. PROGLOG("Retry send for handle: %u", cursorHandle);
  400. requestTree->setProp("cursorBin", remoteReadCursor);
  401. StringBuffer requestStr;
  402. toJSON(requestTree, requestStr);
  403. PROGLOG("requestStr = %s", requestStr.str());
  404. sendlen = requestStr.length();
  405. _WINREV(sendlen);
  406. if (!rawSend && !useHTTP)
  407. socket->write(&sendlen, sizeof(sendlen));
  408. socket->write(requestStr.str(), requestStr.length());
  409. }
  410. }
  411. else
  412. {
  413. if (isBlockedResult)
  414. {
  415. t += 8;
  416. t += strlen(t)+1;
  417. sendlen -= (t - mem);
  418. }
  419. if (echoResults && (!is_status || showStatus))
  420. {
  421. fwrite(t, sendlen, 1, stdout);
  422. fflush(stdout);
  423. }
  424. if (!is_status)
  425. result.append(sendlen, t);
  426. }
  427. if (abortAfterFirst)
  428. return 0;
  429. }
  430. return 0;
  431. }
  432. class ReceiveThread : public Thread
  433. {
  434. public:
  435. virtual int run();
  436. };
  437. int ReceiveThread::run()
  438. {
  439. ISocket * socket = ISocket::create(3456);
  440. ISocket * client = socket->accept();
  441. StringBuffer result;
  442. readResults(client, parallelBlocked, false, result, nullptr, 0);
  443. client->Release();
  444. socket->Release();
  445. finishedReading.signal();
  446. return 0;
  447. }
  448. //------------------------------------------------------------------------
  449. /**
  450. * Return: 0 - success
  451. * nonzero - error
  452. */
  453. int doSendQuery(const char * ip, unsigned port, const char * base)
  454. {
  455. Owned<ISocket> socket;
  456. Owned<ISecureSocketContext> secureContext;
  457. __int64 starttime, endtime;
  458. StringBuffer ipstr;
  459. try
  460. {
  461. if (strcmp(ip, ".")==0)
  462. ip = GetCachedHostName();
  463. else
  464. {
  465. const char *dash = strchr(ip, '-');
  466. if (dash && isdigit(dash[1]) && dash>ip && isdigit(dash[-1]))
  467. {
  468. if (persistConnections)
  469. UNIMPLEMENTED;
  470. const char *startrange = dash-1;
  471. while (isdigit(startrange[-1]))
  472. startrange--;
  473. char *endptr;
  474. unsigned firstnum = atoi(startrange);
  475. unsigned lastnum = strtol(dash+1, &endptr, 10);
  476. if (lastnum > firstnum)
  477. {
  478. static unsigned counter;
  479. static CriticalSection counterCrit;
  480. CriticalBlock b(counterCrit);
  481. ipstr.append(startrange - ip, ip).append((counter++ % (lastnum+1-firstnum)) + firstnum).append(endptr);
  482. ip = ipstr.str();
  483. printf("Sending to %s\n", ip);
  484. }
  485. }
  486. }
  487. starttime= get_cycles_now();
  488. if (persistConnections)
  489. {
  490. if (!persistSocket)
  491. {
  492. SocketEndpoint ep(ip,port);
  493. persistSocket.setown(ISocket::connect_timeout(ep, 1000));
  494. if (useSSL)
  495. {
  496. #ifdef _USE_OPENSSL
  497. if (!persistSecureContext)
  498. persistSecureContext.setown(createSecureSocketContext(ClientSocket));
  499. persistSSock.setown(persistSecureContext->createSecureSocket(persistSocket.getClear()));
  500. persistSSock->secure_connect();
  501. persistSocket.setown(persistSSock.getClear());
  502. #else
  503. throw MakeStringException(-1, "OpenSSL disabled in build");
  504. #endif
  505. }
  506. }
  507. socket = persistSocket;
  508. }
  509. else
  510. {
  511. SocketEndpoint ep(ip,port);
  512. socket.setown(ISocket::connect_timeout(ep, 100000));
  513. if (useSSL)
  514. {
  515. #ifdef _USE_OPENSSL
  516. secureContext.setown(createSecureSocketContext(ClientSocket));
  517. Owned<ISecureSocket> ssock = secureContext->createSecureSocket(socket.getClear());
  518. ssock->secure_connect();
  519. socket.setown(ssock.getClear());
  520. #else
  521. throw MakeStringException(1, "OpenSSL disabled in build");
  522. #endif
  523. }
  524. }
  525. }
  526. catch(IException * e)
  527. {
  528. pexception("failed to connect to server", e);
  529. return 1;
  530. }
  531. StringBuffer fullQuery;
  532. bool useHTTP = forceHTTP || strstr(base, "<soap:Envelope") != NULL;
  533. if (useHTTP)
  534. {
  535. StringBuffer newQuery;
  536. Owned<IPTree> p = createPTreeFromXMLString(base, ipt_none, ptr_none);
  537. const char *queryName = p->queryName();
  538. if ((stricmp(queryName, "envelope") != 0) && (stricmp(queryName, "envelope") != 0))
  539. {
  540. if (queryNameOverride.length())
  541. queryName = queryNameOverride;
  542. newQuery.appendf("<Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><Body><%sRequest>", queryName);
  543. Owned<IPTreeIterator> elements = p->getElements("./*");
  544. ForEach(*elements)
  545. {
  546. IPTree &elem = elements->query();
  547. toXML(&elem, newQuery, 0, XML_SingleQuoteAttributeValues);
  548. }
  549. newQuery.appendf("</%sRequest></Body></Envelope>", queryName);
  550. base = newQuery.str();
  551. }
  552. // note - don't support queryname override unless original query is xml
  553. fullQuery.appendf("POST /doc HTTP/1.0\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: %d\r\n\r\n", (int) strlen(base)).append(base);
  554. }
  555. else
  556. {
  557. if (sendToSocket)
  558. {
  559. Thread * receive = new ReceiveThread();
  560. receive->start();
  561. receive->Release();
  562. }
  563. if (doLock)
  564. {
  565. const char *lock = "<control:lock/>";
  566. unsigned locklen = strlen(lock);
  567. _WINREV(locklen);
  568. socket->write(&locklen, sizeof(locklen));
  569. socket->write(lock, strlen(lock));
  570. StringBuffer lockResult;
  571. readResults(socket, false, false, lockResult, nullptr, 0);
  572. }
  573. if (queryNameOverride.length())
  574. {
  575. try
  576. {
  577. Owned<IPTree> p = createPTreeFromXMLString(base, ipt_none, ptr_none);
  578. p->renameProp("/", queryNameOverride);
  579. toXML(p, fullQuery.clear());
  580. }
  581. catch (IException *E)
  582. {
  583. StringBuffer s;
  584. printf("Error: %s", E->errorMessage(s).str());
  585. E->Release();
  586. return 1;
  587. }
  588. }
  589. else
  590. fullQuery.append(base);
  591. }
  592. const char * query = fullQuery.str();
  593. size32_t queryLen=(size32_t)strlen(query);
  594. size32_t len = queryLen;
  595. size32_t sendlen = len;
  596. if (persistConnections)
  597. sendlen |= 0x80000000;
  598. _WINREV(sendlen);
  599. try
  600. {
  601. if (!rawSend && !useHTTP)
  602. socket->write(&sendlen, sizeof(sendlen));
  603. fprintf(stdout, "about to write %u <%s>\n", len, query);
  604. socket->write(query, len);
  605. if (sendFileAfterQuery)
  606. {
  607. FILE *in = fopen(sendFileName.str(), "rb");
  608. if (in)
  609. {
  610. char buffer[1024];
  611. for (;;)
  612. {
  613. len = fread(buffer, 1, sizeof(buffer), in);
  614. sendlen = len;
  615. _WINREV(sendlen);
  616. socket->write(&sendlen, sizeof(sendlen));
  617. if (!len)
  618. break;
  619. socket->write(buffer, len);
  620. }
  621. fclose(in);
  622. }
  623. else
  624. printf("File %s could not be opened\n", sendFileName.str());
  625. }
  626. }
  627. catch(IException * e)
  628. {
  629. pexception("failed to write data", e);
  630. return 1;
  631. }
  632. if (abortEarly)
  633. return 0;
  634. // back-end does some processing.....
  635. StringBuffer result;
  636. int ret = readResults(socket, false, useHTTP, result, query, queryLen);
  637. if ((ret == 0) && !justResults)
  638. {
  639. endtime = get_cycles_now();
  640. CriticalBlock b(traceCrit);
  641. if (trace != NULL)
  642. {
  643. if (rawOnly == false)
  644. {
  645. fprintf(trace, "query: %s\n", query);
  646. if (saveResults)
  647. fprintf(trace, "result: %s\n", result.str());
  648. }
  649. else
  650. {
  651. fprintf(trace, "%s", result.str());
  652. }
  653. if (showTiming && rawOnly == false)
  654. {
  655. fprintf(trace, "Time taken = %.3f msecs\n", (double)(cycle_to_nanosec(endtime - starttime)/1000000));
  656. fputs("----------------------------------------------------------------------------\n", trace);
  657. }
  658. }
  659. }
  660. if (!persistConnections)
  661. {
  662. socket->close();
  663. }
  664. return 0;
  665. }
  666. class QueryThread : public Thread
  667. {
  668. public:
  669. QueryThread(const char * _ip, unsigned _port, const char * _base) : ip(_ip),port(_port),base(_base) {}
  670. virtual int run() { doSendQuery(ip, port, base); done.signal(); okToSend.signal(); return 0; }
  671. protected:
  672. StringAttr ip;
  673. unsigned port;
  674. StringAttr base;
  675. };
  676. int sendQuery(const char * ip, unsigned port, const char * base)
  677. {
  678. if (!multiThread)
  679. return doSendQuery(ip, port, base);
  680. if (multiThreadMax)
  681. okToSend.wait();
  682. runningQueries++;
  683. Thread * thread = new QueryThread(ip, port, base);
  684. thread->start();
  685. thread->Release();
  686. return 0;
  687. }
  688. void usage(int exitCode)
  689. {
  690. printf("testsocket ip<:port> [flags] [query | -f[f] file.sql | -]\n");
  691. printf(" - take query from stdin\n");
  692. printf(" -a abort before input received\n");
  693. printf(" -a1 abort after first packet receieved\n");
  694. printf(" -c test sending response to a socket\n");
  695. printf(" -cb test sending response to a block mode socket\n");
  696. printf(" -d force delay after each packet\n");
  697. printf(" -f take query from file\n");
  698. printf(" -ff take multiple queries from file, one per line\n");
  699. printf(" -tff take multiple queries from file, one per line, preceded by the time at which it should be submitted (relative to time on first line)\n");
  700. printf(" -k don't save the results to result.txt\n");
  701. printf(" -m only save results to result.txt\n");
  702. printf(" -maxLineSize <n> set maximum query line length\n");
  703. printf(" -n multiple results - keep going until socket closes\n");
  704. printf(" -o set output filename\n");
  705. printf(" -or set output filename for raw output\n");
  706. printf(" -persist use persistent connection\n");
  707. printf(" -pr <text>add a prefix to the query\n");
  708. printf(" -q quiet - don't echo query\n");
  709. printf(" -qname xx Use xx as queryname in place of the xml root element name\n");
  710. printf(" -r <n> repeat the query several times\n");
  711. printf(" -rl roxie logfile mode\n");
  712. printf(" -rsr force remote stream resend per continuation request\n");
  713. printf(" -rssc send cursor per continuation request\n");
  714. printf(" -s add stars to indicate transfer packets\n");
  715. printf(" -ss suppress XML Status messages to screen (always suppressed from tracefile)\n");
  716. printf(" -ssl use ssl\n");
  717. printf(" -td add debug timing statistics to trace\n");
  718. printf(" -tf add full timing statistics to trace\n");
  719. printf(" -time add timing to trace\n");
  720. printf(" -u<max> run queries on separate threads\n");
  721. printf(" -cascade cascade query (to all roxie nodes)\n");
  722. printf(" -lock locked cascade query (to all roxie nodes)\n");
  723. printf(" -x raw send\n");
  724. exit(exitCode);
  725. }
  726. int main(int argc, char **argv)
  727. {
  728. InitModuleObjects();
  729. StringAttr outputName("result.txt");
  730. bool fromFile = false;
  731. bool fromStdIn = false;
  732. bool fromMultiFile = false;
  733. bool timedReplay = false;
  734. if (argc < 2 && !(argc==2 && strstr(argv[1], "::")))
  735. usage(1);
  736. int arg = 2;
  737. bool echoSingle = true;
  738. while (arg < argc && *argv[arg]=='-')
  739. {
  740. if (stricmp(argv[arg], "-time") == 0)
  741. {
  742. showTiming = true;
  743. ++arg;
  744. }
  745. else if (stricmp(argv[arg], "-a") == 0)
  746. {
  747. abortEarly = true;
  748. ++arg;
  749. }
  750. else if (stricmp(argv[arg], "-a1") == 0)
  751. {
  752. abortAfterFirst = true;
  753. ++arg;
  754. }
  755. else if (stricmp(argv[arg], "-c") == 0)
  756. {
  757. sendToSocket = true;
  758. ++arg;
  759. }
  760. else if (stricmp(argv[arg], "-cb") == 0)
  761. {
  762. sendToSocket = true;
  763. parallelBlocked = true;
  764. ++arg;
  765. }
  766. else if (stricmp(argv[arg], "-d") == 0)
  767. {
  768. delay = 300;
  769. ++arg;
  770. }
  771. else if (stricmp(argv[arg], "-http") == 0)
  772. {
  773. forceHTTP = true;
  774. ++arg;
  775. }
  776. else if (stricmp(argv[arg], "-ssl") == 0)
  777. {
  778. useSSL = true;
  779. ++arg;
  780. }
  781. else if (stricmp(argv[arg], "-") == 0)
  782. {
  783. fromStdIn = true;
  784. ++arg;
  785. }
  786. else if (stricmp(argv[arg], "-f") == 0)
  787. {
  788. fromFile = true;
  789. ++arg;
  790. }
  791. else if (stricmp(argv[arg], "-x") == 0)
  792. {
  793. rawSend = true;
  794. ++arg;
  795. }
  796. else if (stricmp(argv[arg], "-ff") == 0)
  797. {
  798. fromMultiFile = true;
  799. ++arg;
  800. }
  801. else if (stricmp(argv[arg], "-tff") == 0)
  802. {
  803. fromMultiFile = true;
  804. timedReplay = true;
  805. ++arg;
  806. }
  807. else if (stricmp(argv[arg], "-k") == 0)
  808. {
  809. saveResults = false;
  810. ++arg;
  811. }
  812. else if (stricmp(argv[arg], "-m") == 0)
  813. {
  814. justResults = true;
  815. ++arg;
  816. }
  817. else if (stricmp(argv[arg], "-maxlinesize") == 0)
  818. {
  819. ++arg;
  820. if (arg>=argc)
  821. usage(1);
  822. maxLineSize = atoi(argv[arg]);
  823. ++arg;
  824. }
  825. else if (stricmp(argv[arg], "-n") == 0)
  826. {
  827. manyResults = true;
  828. ++arg;
  829. }
  830. else if (stricmp(argv[arg], "-o") == 0)
  831. {
  832. outputName.set(argv[arg+1]);
  833. arg+=2;
  834. }
  835. else if (stricmp(argv[arg], "-or") == 0)
  836. {
  837. rawOnly = true;
  838. outputName.set(argv[arg+1]);
  839. arg+=2;
  840. }
  841. else if (stricmp(argv[arg], "-persist") == 0)
  842. {
  843. persistConnections = true;
  844. ++arg;
  845. }
  846. else if (stricmp(argv[arg], "-pr") == 0)
  847. {
  848. queryPrefix.append(argv[arg+1]);
  849. arg+=2;
  850. }
  851. else if (stricmp(argv[arg], "-q") == 0)
  852. {
  853. echoSingle = false;
  854. ++arg;
  855. }
  856. else if (stricmp(argv[arg], "-qname") == 0)
  857. {
  858. queryNameOverride.set(argv[arg+1]);
  859. arg+=2;
  860. }
  861. else if (stricmp(argv[arg], "-r") == 0)
  862. {
  863. ++arg;
  864. if (arg>=argc)
  865. usage(1);
  866. repeats = atoi(argv[arg]);
  867. ++arg;
  868. }
  869. else if (stricmp(argv[arg], "-rl") == 0)
  870. {
  871. roxieLogMode = true;
  872. fromMultiFile = true;
  873. ++arg;
  874. }
  875. else if (stricmp(argv[arg], "-ss") == 0)
  876. {
  877. showStatus = false;
  878. ++arg;
  879. }
  880. else if (memicmp(argv[arg], "-u", 2) == 0)
  881. {
  882. multiThread = true;
  883. multiThreadMax = atoi(argv[arg]+2);
  884. if (multiThreadMax)
  885. okToSend.signal(multiThreadMax);
  886. ++arg;
  887. }
  888. else if (stricmp(argv[arg], "-lock") == 0)
  889. {
  890. doLock = true;
  891. ++arg;
  892. }
  893. else if (memicmp(argv[arg], "-z", 2) == 0)
  894. {
  895. sendFileAfterQuery = true;
  896. sendFileName.append(argv[arg+1]);
  897. OwnedIFile f = createIFile(sendFileName.str());
  898. if (!f->exists() || !f->isFile())
  899. {
  900. printf("file %s does not exist\n", sendFileName.str());
  901. exit (EXIT_FAILURE);
  902. }
  903. arg+=2;
  904. }
  905. else if (strieq(argv[arg], "-rsr"))
  906. {
  907. remoteStreamForceResend = true;
  908. ++arg;
  909. }
  910. else if (strieq(argv[arg], "-rssc"))
  911. {
  912. remoteStreamSendCursor = true;
  913. ++arg;
  914. }
  915. else
  916. {
  917. printf("Unknown argument %s, ignored\n", argv[arg]);
  918. ++arg;
  919. }
  920. }
  921. if (persistConnections && multiThread)
  922. {
  923. printf("Multi-thread (-u) not available with -persist - ignored\n");
  924. multiThread = false;
  925. }
  926. StringAttr ip;
  927. unsigned socketPort = (useSSL) ? ROXIE_SSL_SERVER_PORT : ROXIE_SERVER_PORT;
  928. SplitIpPort(ip, socketPort, argv[1]);
  929. int ret = 0;
  930. trace = fopen(outputName, "w");
  931. if (trace == NULL)
  932. {
  933. printf("Can't open %s for writing\n", outputName.str());
  934. }
  935. __int64 starttime,endtime;
  936. starttime = get_cycles_now();
  937. if (arg < argc || fromStdIn)
  938. {
  939. echoResults = echoSingle;
  940. do
  941. {
  942. const char * query = argv[arg];
  943. if (fromMultiFile)
  944. {
  945. FILE *in = fopen(query, "rt");
  946. if (in)
  947. {
  948. CDateTime firstTime;
  949. CDateTime startTime;
  950. bool firstLine = true;
  951. char *buffer = new char[maxLineSize];
  952. for (;;)
  953. {
  954. if (fgets(buffer, maxLineSize, in)==NULL) // buffer overflow possible - do I care?
  955. break;
  956. if (timedReplay)
  957. {
  958. if (firstLine)
  959. {
  960. firstTime.setNow();
  961. firstTime.setTimeString(buffer, &query);
  962. startTime.setNow();
  963. }
  964. else
  965. {
  966. CDateTime queryTime, nowTime;
  967. queryTime.setNow();
  968. queryTime.setTimeString(buffer, &query);
  969. nowTime.setNow();
  970. int sleeptime = (int)((queryTime.getSimple()-firstTime.getSimple()) - (nowTime.getSimple()-startTime.getSimple()));
  971. if (sleeptime < 0)
  972. DBGLOG("Running behind %d seconds", -sleeptime);
  973. else if (sleeptime)
  974. {
  975. DBGLOG("Sleeping %d seconds", sleeptime);
  976. Sleep(sleeptime*1000);
  977. }
  978. StringBuffer targetTime;
  979. queryTime.getTimeString(targetTime);
  980. DBGLOG("Virtual time is %s", targetTime.str());
  981. }
  982. }
  983. else
  984. {
  985. query = buffer;
  986. while (isspace(*query)) query++;
  987. if (roxieLogMode)
  988. {
  989. char *start = (char *) strchr(query, '<');
  990. if (start)
  991. {
  992. char *end = (char *) strchr(start, '"');
  993. if (end && end[1]=='\n')
  994. {
  995. query = start;
  996. *end = 0;
  997. }
  998. }
  999. }
  1000. }
  1001. if (query)
  1002. {
  1003. ret = sendQuery(ip, socketPort, query);
  1004. firstLine = false;
  1005. }
  1006. }
  1007. delete [] buffer;
  1008. fclose(in);
  1009. }
  1010. else
  1011. printf("File %s could not be opened\n", query);
  1012. }
  1013. else if (fromFile || fromStdIn)
  1014. {
  1015. FILE *in = fromStdIn ? stdin : fopen(query, "rt");
  1016. if (in)
  1017. {
  1018. StringBuffer fileContents;
  1019. char buffer[1024];
  1020. int bytes;
  1021. for (;;)
  1022. {
  1023. bytes = fread(buffer, 1, sizeof(buffer), in);
  1024. if (!bytes)
  1025. break;
  1026. fileContents.append(buffer, 0, bytes);
  1027. }
  1028. if (in != stdin)
  1029. fclose(in);
  1030. ret = sendQuery(ip, socketPort, fileContents.str());
  1031. }
  1032. else
  1033. printf("File %s could not be opened\n", query);
  1034. }
  1035. else
  1036. {
  1037. ret = sendQuery(ip, socketPort, query);
  1038. if (sendToSocket)
  1039. finishedReading.wait();
  1040. }
  1041. } while (--repeats > 0);
  1042. }
  1043. else
  1044. usage(2);
  1045. while (runningQueries--)
  1046. done.wait();
  1047. if (persistConnections && persistSocket)
  1048. {
  1049. int sendlen=0;
  1050. persistSocket->write(&sendlen, sizeof(sendlen));
  1051. persistSocket->close();
  1052. }
  1053. endtime = get_cycles_now();
  1054. if (!justResults)
  1055. {
  1056. if (rawOnly == false)
  1057. {
  1058. if (trace != NULL)
  1059. {
  1060. fprintf(trace, "Total Time taken = %.3f msecs\n", (double)(cycle_to_nanosec(endtime - starttime)/1000000));
  1061. fputs("----------------------------------------------------------------------------\n", trace);
  1062. }
  1063. }
  1064. }
  1065. if (trace != NULL)
  1066. {
  1067. fclose(trace);
  1068. }
  1069. #ifdef _DEBUG
  1070. releaseAtoms();
  1071. #endif
  1072. return ret;
  1073. }