testsocket.cpp 37 KB

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