testsocket.cpp 36 KB

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