udptrr.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936
  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 <string>
  14. #include <map>
  15. #include <queue>
  16. #include "jthread.hpp"
  17. #include "jlog.hpp"
  18. #include "jisem.hpp"
  19. #include "jsocket.hpp"
  20. #include "udplib.hpp"
  21. #include "udptrr.hpp"
  22. #include "udptrs.hpp"
  23. #include "udpipmap.hpp"
  24. #include "udpmsgpk.hpp"
  25. #include "roxiemem.hpp"
  26. #include "roxie.hpp"
  27. #ifdef _WIN32
  28. #include <io.h>
  29. #include <winsock2.h>
  30. #else
  31. #include <sys/socket.h>
  32. #include <sys/time.h>
  33. #include <sys/resource.h>
  34. #endif
  35. #include <thread>
  36. using roxiemem::DataBuffer;
  37. using roxiemem::IRowManager;
  38. unsigned udpRetryBusySenders = 0; // seems faster with 0 than 1 in my testing on small clusters and sustained throughput
  39. class CReceiveManager : implements IReceiveManager, public CInterface
  40. {
  41. /*
  42. * The ReceiveManager has several threads:
  43. * 1. receive_receive_flow (priority 3)
  44. * - waits for packets on flow port
  45. * - maintains list of nodes that have pending requests
  46. * - sends ok_to_send to one sender at a time
  47. * 2. receive_sniffer (default priority 3, configurable)
  48. * - waits for packets on sniffer port
  49. * - updates information about what other node are currently up to
  50. * - idea is to preferentially send "ok_to_send" to nodes that are not currently sending to someone else
  51. * - doesn't run if no multicast
  52. * - can I instead say "If I get a request to send and I'm sending to someone else, send a "later"?
  53. * 3. receive_data (priority 4)
  54. * - reads data packets off data socket
  55. * - runs at v. high priority
  56. * - used to have an option to perform collation on this thread but a bad idea:
  57. * - can block (ends up in memory manager via attachDataBuffer).
  58. * - Does not apply back pressure
  59. * - Just enqueues them. We don't give permission to send more than the queue can hold.
  60. * 4. PacketCollator (standard priority)
  61. * - dequeues packets
  62. * - collates packets
  63. *
  64. */
  65. /*
  66. * Handling lost packets
  67. *
  68. * We try to make lost packets unlikely by telling agents when to send (and making sure they don't send unless
  69. * there's a good chance that socket buffer will have room). But we can't legislate for network issues.
  70. *
  71. * What packets can be lost?
  72. * 1. Data packets - handled via retrying the whole query (not ideal). But will also leave the inflight count wrong. We correct it any time
  73. * the data socket times out but that may not be good enough.
  74. * 2. RequestToSend - the sender's resend thread checks periodically. There's a short initial timeout for getting a reply (either "request_received"
  75. * or "okToSend"), then a longer timeout for actually sending.
  76. * 3. OkToSend - there is a timeout after which the permission is considered invalid (based on how long it SHOULD take to send them).
  77. * The requestToSend retry mechanism would then make sure retried.
  78. * MORE - if I don't get a response from OkToSend I should assume lost and requeue it.
  79. * 4. complete - covered by same timeout as okToSend. A lost complete will mean incoming data to that node stalls for the duration of this timeout,
  80. * and will also leave inflight count out-of-whack.
  81. * 4. Sniffers - expire anyway
  82. *
  83. */
  84. class UdpSenderEntry // one per node in the system
  85. {
  86. // This is created the first time a message from a previously unseen IP arrives, and remains alive indefinitely
  87. // Note that the various members are accessed by different threads, but no member is accessed from more than one thread
  88. // (except where noted) so protection is not required
  89. // Note that UDP ordering rules mean we can't guarantee that we don't see a "request_to_send" for the next transfer before
  90. // we see the "complete" for the current one. Even if we were sure network stack would not reorder, these come from different
  91. // threads on the sender side and the order is not 100% guaranteed, so we need to cope with it.
  92. // We also need to recover gracefully (and preferably quickly) if any flow or data messages go missing. Currently the sender
  93. // will resend the rts if no ok_to_send within timeout, but there may be a better way?
  94. public:
  95. // Used only by receive_flow thread
  96. IpAddress dest;
  97. ISocket *flowSocket = nullptr;
  98. UdpSenderEntry *nextSender = nullptr; // Used to form list of all senders that have outstanding requests
  99. unsigned timeouts = 0;
  100. // Set by sniffer, used by receive_flow. But races are unimportant
  101. unsigned timeStamp = 0; // When it was marked busy (0 means not busy)
  102. UdpSenderEntry(const IpAddress &_dest, unsigned port) : dest(_dest)
  103. {
  104. SocketEndpoint ep(port, dest);
  105. flowSocket = ISocket::udp_connect(ep);
  106. }
  107. ~UdpSenderEntry()
  108. {
  109. if (flowSocket)
  110. {
  111. flowSocket->close();
  112. flowSocket->Release();
  113. }
  114. }
  115. inline void noteDone()
  116. {
  117. timeouts = 0;
  118. }
  119. inline bool retryOnTimeout()
  120. {
  121. ++timeouts;
  122. if (udpTraceLevel)
  123. {
  124. StringBuffer s;
  125. DBGLOG("Timed out %d times waiting for send_done from %s", timeouts, dest.getIpText(s).str());
  126. }
  127. if (udpMaxRetryTimedoutReqs && (timeouts >= udpMaxRetryTimedoutReqs))
  128. {
  129. if (udpTraceLevel)
  130. DBGLOG("Abandoning");
  131. timeouts = 0;
  132. return false;
  133. }
  134. else
  135. {
  136. if (udpTraceLevel)
  137. DBGLOG("Retrying");
  138. return true;
  139. }
  140. }
  141. void requestToSend(unsigned maxTransfer, const IpAddress &returnAddress)
  142. {
  143. try
  144. {
  145. UdpPermitToSendMsg msg;
  146. msg.cmd = maxTransfer ? flowType::ok_to_send : flowType::request_received;
  147. msg.destNode = returnAddress;
  148. msg.max_data = maxTransfer;
  149. if (udpTraceLevel > 1)
  150. {
  151. StringBuffer ipStr;
  152. DBGLOG("UdpReceiver: sending ok_to_send %d msg to node=%s", maxTransfer, returnAddress.getIpText(ipStr).str());
  153. }
  154. flowSocket->write(&msg, sizeof(UdpPermitToSendMsg));
  155. }
  156. catch(IException *e)
  157. {
  158. StringBuffer d, s;
  159. DBGLOG("UdpReceiver: requestToSend failed node=%s %s", dest.getIpText(d).str(), e->errorMessage(s).str());
  160. e->Release();
  161. }
  162. }
  163. bool is_busy()
  164. {
  165. if (timeStamp)
  166. {
  167. unsigned now = msTick();
  168. if ((now - timeStamp) < 10)
  169. return true;
  170. // MORE - might be interesting to note how often this happens. Why 10 milliseconds?
  171. timeStamp = 0; // No longer considered busy
  172. }
  173. return false;
  174. }
  175. void update(bool busy)
  176. {
  177. if (busy)
  178. timeStamp = msTick();
  179. else
  180. timeStamp = 0;
  181. }
  182. };
  183. IpMapOf<UdpSenderEntry> sendersTable;
  184. class receive_sniffer : public Thread
  185. {
  186. ISocket *sniffer_socket;
  187. unsigned snifferPort;
  188. IpAddress snifferIP;
  189. CReceiveManager &parent;
  190. std::atomic<bool> running = { false };
  191. inline void update(const IpAddress &ip, bool busy)
  192. {
  193. if (udpTraceLevel > 5)
  194. {
  195. StringBuffer s;
  196. DBGLOG("UdpReceive: sniffer sets is_busy[%s] to %d", ip.getIpText(s).str(), busy);
  197. }
  198. parent.sendersTable[ip].update(busy);
  199. }
  200. public:
  201. receive_sniffer(CReceiveManager &_parent, unsigned _snifferPort, const IpAddress &_snifferIP)
  202. : Thread("udplib::receive_sniffer"), parent(_parent), snifferPort(_snifferPort), snifferIP(_snifferIP), running(false)
  203. {
  204. sniffer_socket = ISocket::multicast_create(snifferPort, snifferIP, multicastTTL);
  205. if (check_max_socket_read_buffer(udpFlowSocketsSize) < 0)
  206. throw MakeStringException(ROXIE_UDP_ERROR, "System Socket max read buffer is less than %i", udpFlowSocketsSize);
  207. sniffer_socket->set_receive_buffer_size(udpFlowSocketsSize);
  208. if (udpTraceLevel)
  209. {
  210. StringBuffer ipStr;
  211. snifferIP.getIpText(ipStr);
  212. size32_t actualSize = sniffer_socket->get_receive_buffer_size();
  213. DBGLOG("UdpReceiver: receive_sniffer port open %s:%i sockbuffsize=%d actual %d", ipStr.str(), snifferPort, udpFlowSocketsSize, actualSize);
  214. }
  215. }
  216. ~receive_sniffer()
  217. {
  218. running = false;
  219. if (sniffer_socket) sniffer_socket->close();
  220. join();
  221. if (sniffer_socket) sniffer_socket->Release();
  222. }
  223. virtual int run()
  224. {
  225. DBGLOG("UdpReceiver: sniffer started");
  226. if (udpSnifferReadThreadPriority)
  227. {
  228. #ifdef __linux__
  229. setLinuxThreadPriority(udpSnifferReadThreadPriority);
  230. #else
  231. adjustPriority(1);
  232. #endif
  233. }
  234. while (running)
  235. {
  236. try
  237. {
  238. unsigned int res;
  239. sniff_msg msg;
  240. sniffer_socket->read(&msg, 1, sizeof(msg), res, 5);
  241. update(msg.nodeIp.getNodeAddress(), msg.cmd == sniffType::busy);
  242. }
  243. catch (IException *e)
  244. {
  245. if (running && e->errorCode() != JSOCKERR_timeout_expired)
  246. {
  247. StringBuffer s;
  248. DBGLOG("UdpReceiver: receive_sniffer::run read failed %s", e->errorMessage(s).str());
  249. MilliSleep(1000);
  250. }
  251. e->Release();
  252. }
  253. catch (...)
  254. {
  255. DBGLOG("UdpReceiver: receive_sniffer::run unknown exception port %u", parent.data_port);
  256. if (sniffer_socket) {
  257. sniffer_socket->Release();
  258. sniffer_socket = ISocket::multicast_create(snifferPort, snifferIP, multicastTTL);
  259. }
  260. MilliSleep(1000);
  261. }
  262. }
  263. return 0;
  264. }
  265. virtual void start()
  266. {
  267. if (udpSnifferEnabled)
  268. {
  269. running = true;
  270. Thread::start();
  271. }
  272. }
  273. };
  274. class receive_receive_flow : public Thread
  275. {
  276. CReceiveManager &parent;
  277. Owned<ISocket> flow_socket;
  278. const unsigned flow_port;
  279. const unsigned maxSlotsPerSender;
  280. std::atomic<bool> running = { false };
  281. UdpSenderEntry *pendingRequests = nullptr; // Head of list of people wanting permission to send
  282. UdpSenderEntry *lastPending = nullptr; // Tail of list
  283. UdpSenderEntry *currentRequester = nullptr; // Who currently has permission to send
  284. void enqueueRequest(UdpSenderEntry *requester)
  285. {
  286. if ((lastPending == requester) || (requester->nextSender != nullptr)) // Already on queue
  287. {
  288. if (udpTraceLevel > 1)
  289. {
  290. StringBuffer s;
  291. DBGLOG("UdpReceive: received duplicate request_to_send from node %s", requester->dest.getIpText(s).str());
  292. }
  293. // We can safely ignore these
  294. }
  295. else
  296. {
  297. // Chain it onto list
  298. if (pendingRequests != nullptr)
  299. lastPending->nextSender = requester;
  300. else
  301. pendingRequests = requester;
  302. lastPending = requester;
  303. }
  304. requester->requestToSend(0, myNode.getNodeAddress()); // Acknowledge receipt of the request
  305. }
  306. unsigned okToSend(UdpSenderEntry *requester)
  307. {
  308. assert (!currentRequester);
  309. unsigned max_transfer = parent.free_slots();
  310. if (max_transfer > maxSlotsPerSender)
  311. max_transfer = maxSlotsPerSender;
  312. unsigned timeout = ((max_transfer * DATA_PAYLOAD) / 100) + 10; // in ms assuming mtu package size with 100x margin on 100 Mbit network // MORE - hideous!
  313. currentRequester = requester;
  314. requester->requestToSend(max_transfer, myNode.getNodeAddress());
  315. return timeout;
  316. }
  317. bool noteDone(UdpSenderEntry *requester)
  318. {
  319. if (requester != currentRequester)
  320. {
  321. // This should not happen - I suppose it COULD if we receive a delayed message for a transfer we had earlier given up on.
  322. // Best response is to ignore it if so
  323. DBGLOG("Received completed message is not from current sender!");
  324. // MORE - should we set currentRequester NULL here? debatable.
  325. return false;
  326. }
  327. currentRequester->noteDone();
  328. currentRequester = nullptr;
  329. return true;
  330. }
  331. unsigned timedOut(UdpSenderEntry *requester)
  332. {
  333. // MORE - this will retry indefinitely if agent in question is dead
  334. currentRequester = nullptr;
  335. if (requester->retryOnTimeout())
  336. enqueueRequest(requester);
  337. if (pendingRequests)
  338. return sendNextOk();
  339. else
  340. return 5000;
  341. }
  342. unsigned sendNextOk()
  343. {
  344. assert(pendingRequests != nullptr);
  345. if (udpSnifferEnabled)
  346. {
  347. //find first non-busy sender, and move it to front of sendersTable request chain
  348. int retry = udpRetryBusySenders;
  349. UdpSenderEntry *finger = pendingRequests;
  350. UdpSenderEntry *prev = nullptr;
  351. for (;;)
  352. {
  353. if (finger->is_busy())
  354. {
  355. prev = finger;
  356. finger = finger->nextSender;
  357. if (finger==nullptr)
  358. {
  359. if (retry--)
  360. {
  361. if (udpTraceLevel > 4)
  362. DBGLOG("UdpReceive: All senders busy");
  363. MilliSleep(1);
  364. finger = pendingRequests;
  365. prev = nullptr;
  366. }
  367. else
  368. break; // give up and use first anyway
  369. }
  370. }
  371. else
  372. {
  373. if (finger != pendingRequests)
  374. {
  375. if (finger == lastPending)
  376. lastPending = prev;
  377. assert(prev != nullptr);
  378. prev->nextSender = finger->nextSender;
  379. finger->nextSender = pendingRequests;
  380. pendingRequests = finger;
  381. }
  382. break;
  383. }
  384. }
  385. }
  386. UdpSenderEntry *nextSender = pendingRequests;
  387. // remove from front of queue
  388. if (pendingRequests==lastPending)
  389. lastPending = nullptr;
  390. pendingRequests = nextSender->nextSender;
  391. nextSender->nextSender = nullptr;
  392. return okToSend(nextSender);
  393. }
  394. public:
  395. receive_receive_flow(CReceiveManager &_parent, unsigned flow_p, unsigned _maxSlotsPerSender)
  396. : Thread("UdpLib::receive_receive_flow"), parent(_parent), flow_port(flow_p), maxSlotsPerSender(_maxSlotsPerSender)
  397. {
  398. if (check_max_socket_read_buffer(udpFlowSocketsSize) < 0)
  399. throw MakeStringException(ROXIE_UDP_ERROR, "System Socket max read buffer is less than %i", udpFlowSocketsSize);
  400. flow_socket.setown(ISocket::udp_create(flow_port));
  401. flow_socket->set_receive_buffer_size(udpFlowSocketsSize);
  402. size32_t actualSize = flow_socket->get_receive_buffer_size();
  403. DBGLOG("UdpReceiver: receive_receive_flow created port=%d sockbuffsize=%d actual %d", flow_port, udpFlowSocketsSize, actualSize);
  404. }
  405. ~receive_receive_flow()
  406. {
  407. running = false;
  408. if (flow_socket)
  409. flow_socket->close();
  410. join();
  411. }
  412. virtual void start()
  413. {
  414. running = true;
  415. Thread::start();
  416. }
  417. virtual int run() override
  418. {
  419. DBGLOG("UdpReceiver: receive_receive_flow started");
  420. #ifdef __linux__
  421. setLinuxThreadPriority(3);
  422. #else
  423. adjustPriority(1);
  424. #endif
  425. UdpRequestToSendMsg msg;
  426. unsigned timeoutExpires = msTick() + 5000;
  427. while (running)
  428. {
  429. try
  430. {
  431. const unsigned l = sizeof(msg);
  432. unsigned int res ;
  433. unsigned now = msTick();
  434. if (now >= timeoutExpires)
  435. {
  436. if (currentRequester)
  437. timeoutExpires = now + timedOut(currentRequester);
  438. else
  439. timeoutExpires = now + 5000;
  440. }
  441. else
  442. {
  443. flow_socket->readtms(&msg, l, l, res, timeoutExpires-now);
  444. now = msTick();
  445. assert(res==l);
  446. if (udpTraceLevel > 5)
  447. {
  448. StringBuffer ipStr;
  449. DBGLOG("UdpReceiver: received %s msg from node=%s", flowType::name(msg.cmd), msg.sourceNode.getTraceText(ipStr).str());
  450. }
  451. UdpSenderEntry *sender = &parent.sendersTable[msg.sourceNode.getNodeAddress()];
  452. switch (msg.cmd)
  453. {
  454. case flowType::request_to_send:
  455. if (pendingRequests || currentRequester)
  456. enqueueRequest(sender); // timeoutExpires does not change - there's still an active request
  457. else
  458. timeoutExpires = now + okToSend(sender);
  459. break;
  460. case flowType::send_completed:
  461. parent.inflight += msg.packets;
  462. if (noteDone(sender) && pendingRequests)
  463. timeoutExpires = now + sendNextOk();
  464. else
  465. timeoutExpires = now + 5000;
  466. break;
  467. case flowType::request_to_send_more:
  468. parent.inflight += msg.packets;
  469. if (noteDone(sender))
  470. {
  471. if (pendingRequests)
  472. {
  473. enqueueRequest(sender);
  474. timeoutExpires = now + sendNextOk();
  475. }
  476. else
  477. timeoutExpires = now + okToSend(sender);
  478. }
  479. break;
  480. default:
  481. DBGLOG("UdpReceiver: received unrecognized flow control message cmd=%i", msg.cmd);
  482. }
  483. }
  484. }
  485. catch (IException *e)
  486. {
  487. // MORE - timeouts need some attention
  488. if (e->errorCode() == JSOCKERR_timeout_expired)
  489. {
  490. // A timeout implies that there is an active permission to send, but nothing has happened.
  491. // Could be a really busy (or crashed) agent, could be a lost packet
  492. if (currentRequester)
  493. timeoutExpires = msTick() + timedOut(currentRequester);
  494. }
  495. else if (running)
  496. {
  497. StringBuffer s;
  498. DBGLOG("UdpReceiver: failed %i %s", flow_port, e->errorMessage(s).str());
  499. }
  500. e->Release();
  501. }
  502. catch (...)
  503. {
  504. DBGLOG("UdpReceiver: receive_receive_flow::run unknown exception");
  505. }
  506. }
  507. return 0;
  508. }
  509. };
  510. class receive_data : public Thread
  511. {
  512. CReceiveManager &parent;
  513. ISocket *receive_socket;
  514. std::atomic<bool> running = { false };
  515. Semaphore started;
  516. public:
  517. receive_data(CReceiveManager &_parent) : Thread("UdpLib::receive_data"), parent(_parent)
  518. {
  519. unsigned ip_buffer = parent.input_queue_size*DATA_PAYLOAD*2;
  520. if (ip_buffer < udpFlowSocketsSize) ip_buffer = udpFlowSocketsSize;
  521. if (check_max_socket_read_buffer(ip_buffer) < 0)
  522. throw MakeStringException(ROXIE_UDP_ERROR, "System socket max read buffer is less than %u", ip_buffer);
  523. receive_socket = ISocket::udp_create(parent.data_port);
  524. receive_socket->set_receive_buffer_size(ip_buffer);
  525. size32_t actualSize = receive_socket->get_receive_buffer_size();
  526. DBGLOG("UdpReceiver: rcv_data_socket created port=%d requested sockbuffsize=%d actual sockbuffsize=%d", parent.data_port, ip_buffer, actualSize);
  527. running = false;
  528. }
  529. virtual void start()
  530. {
  531. running = true;
  532. Thread::start();
  533. started.wait();
  534. }
  535. ~receive_data()
  536. {
  537. running = false;
  538. if (receive_socket)
  539. receive_socket->close();
  540. join();
  541. ::Release(receive_socket);
  542. }
  543. virtual int run()
  544. {
  545. DBGLOG("UdpReceiver: receive_data started");
  546. #ifdef __linux__
  547. setLinuxThreadPriority(4);
  548. #else
  549. adjustPriority(2);
  550. #endif
  551. DataBuffer *b = NULL;
  552. started.signal();
  553. while (running)
  554. {
  555. try
  556. {
  557. unsigned int res;
  558. b = bufferManager->allocate();
  559. receive_socket->read(b->data, 1, DATA_PAYLOAD, res, 5);
  560. parent.inflight--;
  561. // MORE - reset it to zero if we fail to read data, or if avail_read returns 0.
  562. UdpPacketHeader &hdr = *(UdpPacketHeader *) b->data;
  563. assert(hdr.length == res && hdr.length > sizeof(hdr));
  564. if (udpTraceLevel > 5) // don't want to interrupt this thread if we can help it
  565. {
  566. StringBuffer s;
  567. DBGLOG("UdpReceiver: %u bytes received, node=%s", res, hdr.node.getTraceText(s).str());
  568. }
  569. parent.input_queue->pushOwn(b);
  570. b = NULL;
  571. }
  572. catch (IException *e)
  573. {
  574. ::Release(b);
  575. b = NULL;
  576. if (udpTraceLevel > 1 && parent.inflight)
  577. {
  578. DBGLOG("resetting inflight to 0 (was %d)", parent.inflight.load(std::memory_order_relaxed));
  579. }
  580. parent.inflight = 0;
  581. if (running && e->errorCode() != JSOCKERR_timeout_expired)
  582. {
  583. StringBuffer s;
  584. DBGLOG("UdpReceiver: receive_data::run read failed port=%u - Exp: %s", parent.data_port, e->errorMessage(s).str());
  585. MilliSleep(1000); // Give a chance for mem free
  586. }
  587. e->Release();
  588. }
  589. catch (...)
  590. {
  591. ::Release(b);
  592. b = NULL;
  593. DBGLOG("UdpReceiver: receive_data::run unknown exception port %u", parent.data_port);
  594. MilliSleep(1000);
  595. }
  596. }
  597. ::Release(b);
  598. return 0;
  599. }
  600. };
  601. class CPacketCollator : public Thread
  602. {
  603. CReceiveManager &parent;
  604. public:
  605. CPacketCollator(CReceiveManager &_parent) : Thread("CPacketCollator"), parent(_parent) {}
  606. virtual int run()
  607. {
  608. DBGLOG("UdpReceiver: CPacketCollator::run");
  609. parent.collatePackets();
  610. return 0;
  611. }
  612. } collatorThread;
  613. friend class receive_receive_flow;
  614. friend class receive_send_flow;
  615. friend class receive_data;
  616. friend class ReceiveFlowManager;
  617. friend class receive_sniffer;
  618. queue_t *input_queue;
  619. int input_queue_size;
  620. receive_receive_flow *receive_flow;
  621. receive_data *data;
  622. receive_sniffer *sniffer;
  623. int receive_flow_port;
  624. int data_port;
  625. std::atomic<bool> running = { false };
  626. typedef std::map<ruid_t, CMessageCollator*> uid_map;
  627. uid_map collators;
  628. SpinLock collatorsLock; // protects access to collators map
  629. // inflight is my best guess at how many packets may be sitting in socket buffers somewhere.
  630. // Incremented when I am notified about packets having been sent, decremented as they are read off the socket.
  631. std::atomic<int> inflight = {0};
  632. int free_slots()
  633. {
  634. int free = input_queue->free_slots(); // May block if collator thread is not removing from my queue fast enough
  635. // Ignore inflight if negative (can happen because we read some inflight before we see the send_done)
  636. int i = inflight.load(std::memory_order_relaxed);
  637. if (i < 0)
  638. {
  639. if (i < -input_queue->capacity())
  640. {
  641. if (udpTraceLevel)
  642. DBGLOG("UdpReceiver: ERROR: inflight has more packets in queue but not counted (%d) than queue capacity (%d)", -i, input_queue->capacity()); // Should never happen
  643. inflight = -input_queue->capacity();
  644. }
  645. i = 0;
  646. }
  647. else if (i >= free)
  648. {
  649. if ((i > free) && (udpTraceLevel))
  650. DBGLOG("UdpReceiver: ERROR: more packets in flight (%d) than slots free (%d)", i, free); // Should never happen
  651. inflight = i = free-1;
  652. }
  653. if (i && udpTraceLevel > 1)
  654. DBGLOG("UdpReceiver: adjusting free_slots to allow for %d in flight", i);
  655. return free - i;
  656. }
  657. public:
  658. IMPLEMENT_IINTERFACE;
  659. CReceiveManager(int server_flow_port, int d_port, int client_flow_port, int snif_port, const IpAddress &multicast_ip, int queue_size, int m_slot_pr_client)
  660. : collatorThread(*this), sendersTable([client_flow_port](const IpAddress &ip) { return new UdpSenderEntry(ip, client_flow_port);})
  661. {
  662. #ifndef _WIN32
  663. setpriority(PRIO_PROCESS, 0, -15);
  664. #endif
  665. receive_flow_port = server_flow_port;
  666. data_port = d_port;
  667. input_queue_size = queue_size;
  668. input_queue = new queue_t(queue_size);
  669. data = new receive_data(*this);
  670. receive_flow = new receive_receive_flow(*this, server_flow_port, m_slot_pr_client);
  671. if (udpSnifferEnabled)
  672. sniffer = new receive_sniffer(*this, snif_port, multicast_ip);
  673. else
  674. sniffer = nullptr;
  675. running = true;
  676. collatorThread.start();
  677. data->start();
  678. receive_flow->start();
  679. if (udpSnifferEnabled)
  680. sniffer->start();
  681. MilliSleep(15);
  682. }
  683. ~CReceiveManager()
  684. {
  685. running = false;
  686. input_queue->interrupt();
  687. collatorThread.join();
  688. delete data;
  689. delete receive_flow;
  690. delete sniffer;
  691. delete input_queue;
  692. }
  693. virtual void detachCollator(const IMessageCollator *msgColl)
  694. {
  695. ruid_t ruid = msgColl->queryRUID();
  696. if (udpTraceLevel >= 2) DBGLOG("UdpReceiver: detach %p %u", msgColl, ruid);
  697. {
  698. SpinBlock b(collatorsLock);
  699. collators.erase(ruid);
  700. }
  701. msgColl->Release();
  702. }
  703. void collatePackets()
  704. {
  705. while(running)
  706. {
  707. DataBuffer *dataBuff = input_queue->pop(true);
  708. collatePacket(dataBuff);
  709. }
  710. }
  711. void collatePacket(DataBuffer *dataBuff)
  712. {
  713. const UdpPacketHeader *pktHdr = (UdpPacketHeader*) dataBuff->data;
  714. if (udpTraceLevel >= 4)
  715. {
  716. StringBuffer s;
  717. DBGLOG("UdpReceiver: CPacketCollator - unQed packet - ruid=" RUIDF " id=0x%.8X mseq=%u pkseq=0x%.8X len=%d node=%s",
  718. pktHdr->ruid, pktHdr->msgId, pktHdr->msgSeq, pktHdr->pktSeq, pktHdr->length, pktHdr->node.getTraceText(s).str());
  719. }
  720. Linked <CMessageCollator> msgColl;
  721. bool isDefault = false;
  722. {
  723. SpinBlock b(collatorsLock);
  724. try
  725. {
  726. msgColl.set(collators[pktHdr->ruid]);
  727. if (!msgColl)
  728. {
  729. msgColl.set(collators[RUID_DISCARD]);
  730. isDefault = true;
  731. unwantedDiscarded++;
  732. }
  733. }
  734. catch (IException *E)
  735. {
  736. EXCLOG(E);
  737. E->Release();
  738. }
  739. catch (...)
  740. {
  741. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in CPacketCollator::run");
  742. EXCLOG(E);
  743. E->Release();
  744. }
  745. }
  746. if (udpTraceLevel && isDefault)
  747. {
  748. StringBuffer s;
  749. DBGLOG("UdpReceiver: CPacketCollator NO msg collator found - using default - ruid=" RUIDF " id=0x%.8X mseq=%u pkseq=0x%.8X node=%s", pktHdr->ruid, pktHdr->msgId, pktHdr->msgSeq, pktHdr->pktSeq, pktHdr->node.getTraceText(s).str());
  750. }
  751. if (msgColl && msgColl->attach_databuffer(dataBuff))
  752. dataBuff = nullptr;
  753. else
  754. dataBuff->Release();
  755. }
  756. virtual IMessageCollator *createMessageCollator(IRowManager *rowManager, ruid_t ruid)
  757. {
  758. CMessageCollator *msgColl = new CMessageCollator(rowManager, ruid);
  759. if (udpTraceLevel >= 2)
  760. DBGLOG("UdpReceiver: createMessageCollator %p %u", msgColl, ruid);
  761. {
  762. SpinBlock b(collatorsLock);
  763. collators[ruid] = msgColl;
  764. }
  765. msgColl->Link();
  766. return msgColl;
  767. }
  768. };
  769. IReceiveManager *createReceiveManager(int server_flow_port, int data_port, int client_flow_port,
  770. int sniffer_port, const IpAddress &sniffer_multicast_ip,
  771. int udpQueueSize, unsigned maxSlotsPerSender)
  772. {
  773. assertex (maxSlotsPerSender <= (unsigned) udpQueueSize);
  774. return new CReceiveManager(server_flow_port, data_port, client_flow_port, sniffer_port, sniffer_multicast_ip, udpQueueSize, maxSlotsPerSender);
  775. }
  776. /*
  777. Thoughts on flow control / streaming:
  778. 1. The "continuation packet" mechanism does have some advantages
  779. - easy recovery from agent failures
  780. - agent recovers easily from Roxie server failures
  781. - flow control is simple (but is it effective?)
  782. 2. Abandoning continuation packet in favour of streaming would give us the following issues:
  783. - would need some flow control to stop getting ahead of a Roxie server that consumed slowly
  784. - flow control is non trivial if you want to avoid tying up a agent thread and want agent to be able to recover from Roxie server failure
  785. - Need to work out how to do GSS - the nextGE info needs to be passed back in the flow control?
  786. - can't easily recover from agent failures if you already started processing
  787. - unless you assume that the results from agent are always deterministic and can retry and skip N
  788. - potentially ties up a agent thread for a while
  789. - do we need to have a larger thread pool but limit how many actually active?
  790. 3. Order of work
  791. - Just adding streaming while ignoring flow control and continuation stuff (i.e. we still stop for permission to continue periodically)
  792. - Shouldn't make anything any _worse_ ...
  793. - except that won't be able to recover from a agent dying mid-stream (at least not without some considerable effort)
  794. - what will happen then?
  795. - May also break server-side caching (that no-one has used AFAIK). Maybe restrict to nohits as we change....
  796. - Add some flow control
  797. - would prevent agent getting too far ahead in cases that are inadequately flow-controlled today
  798. - shouldn't make anything any worse...
  799. - Think about removing continuation mechanism from some cases
  800. Per Gavin, streaming would definitely help for the lowest frequency term. It may help for the others as well if it avoided any significant start up costs - e.g., opening the indexes,
  801. creating the segment monitors, creating the various cursors, and serialising the context (especially because there are likely to be multiple cursors).
  802. To add streaming:
  803. - Need to check for meta availability other than when first received
  804. - when ?
  805. - Need to cope with a getNext() blocking without it causing issues
  806. - perhaps should recode getNext() of variable-size rows first?
  807. More questions:
  808. - Can we afford the memory for the resend info?
  809. - Save maxPacketsPerSender per sender ?
  810. - are we really handling restart and sequence wraparound correctly?
  811. - what about server-side caching? Makes it hard
  812. - but maybe we should only cache tiny replies anyway....
  813. Problems found while testing implemetnation:
  814. - the unpacker cursor read code is crap
  815. - there is a potential to deadlock when need to make a callback agent->server during a streamed result (indexread5 illustrates)
  816. - resolution callback code doesn't really need to be query specific - could go to the default handler
  817. - but other callbacks - ALIVE, EXCEPTION, and debugger are not so clear
  818. - It's not at all clear where to move the code for processing metadata
  819. - callback paradigm would solve both - but it has to be on a client thread (e.g. from within call to next()).
  820. The following are used in "pseudo callback" mode:
  821. #define ROXIE_DEBUGREQUEST 0x3ffffff7u
  822. #define ROXIE_DEBUGCALLBACK 0x3ffffff8u
  823. #define ROXIE_PING 0x3ffffff9u
  824. - goes to own handler anyway
  825. #define ROXIE_TRACEINFO 0x3ffffffau
  826. - could go in meta? Not time critical. Could all go to single handler? (a bit hard since we want to intercept for caller...)
  827. #define ROXIE_FILECALLBACK 0x3ffffffbu
  828. - could go to single handler
  829. #define ROXIE_ALIVE 0x3ffffffcu
  830. - currently getting delayed a bit too much potentially if downstream processing is slow? Do I even need it if streaming?
  831. #define ROXIE_KEYEDLIMIT_EXCEEDED 0x3ffffffdu
  832. - could go in metadata of standard response
  833. #define ROXIE_LIMIT_EXCEEDED 0x3ffffffeu
  834. - ditto
  835. #define ROXIE_EXCEPTION 0x3fffffffu
  836. - ditto
  837. And the continuation metadata.
  838. What if EVERYTHING was a callback? - here's an exception... here's some more rows... here's some tracing... here's some continuation metadata
  839. Somewhere sometime I need to marshall from one thread to another though (maybe more than once unless I can guarantee callback is always very fast)
  840. OR (is it the same) everything is metadata ? Metadata can contain any of the above information (apart from rows - or maybe they are just another type)
  841. If I can't deal quickly with a packet of information, I queue it up? Spanning complicates things though. I need to be able to spot complete portions of metadata
  842. (and in kind-of the same way I need to be able to spot complete rows of data even when they span multiple packets.) I think data is really a bit different from the rest -
  843. you expect it to be continuous and you want the others to interrupt the flow.
  844. If continuation info was restricted to a "yes/no" (i.e. had to be continued on same node as started on) could have simple "Is there any continuation" bit. Others are sent in their
  845. own packets so are a little different. Does that make it harder to recover? Not sure that it does really (just means that the window at which a failure causes a problem starts earlier).
  846. However it may be an issue tying up agent thread for a while (and do we know when to untie it if the Roxie server abandons/restarts?)
  847. Perhaps it makes sense to pause at this point (with streaming disabled and with retry mechanism optional)
  848. */