udptrr.cpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941
  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, dest.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.getIpAddress(), 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.getIpAddress()); // 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.getIpAddress());
  315. assert(timeout >= 10 && timeout <= 20000);
  316. return timeout;
  317. }
  318. bool noteDone(UdpSenderEntry *requester)
  319. {
  320. if (requester != currentRequester)
  321. {
  322. // This should not happen - I suppose it COULD if we receive a delayed message for a transfer we had earlier given up on.
  323. // Best response is to ignore it if so
  324. DBGLOG("Received completed message is not from current sender!");
  325. // MORE - should we set currentRequester NULL here? debatable.
  326. return false;
  327. }
  328. currentRequester->noteDone();
  329. currentRequester = nullptr;
  330. return true;
  331. }
  332. unsigned timedOut(UdpSenderEntry *requester)
  333. {
  334. // MORE - this will retry indefinitely if agent in question is dead
  335. // As coded, this rescinds the permission to send that just timed out and tells the next person to have a go
  336. // Thus leading to "Received completed message is not from current sender" messages the the send was in flight
  337. currentRequester = nullptr;
  338. if (requester->retryOnTimeout())
  339. enqueueRequest(requester);
  340. if (pendingRequests)
  341. return sendNextOk();
  342. else
  343. return 5000;
  344. }
  345. unsigned sendNextOk()
  346. {
  347. assert(pendingRequests != nullptr);
  348. if (udpSnifferEnabled)
  349. {
  350. //find first non-busy sender, and move it to front of sendersTable request chain
  351. int retry = udpRetryBusySenders;
  352. UdpSenderEntry *finger = pendingRequests;
  353. UdpSenderEntry *prev = nullptr;
  354. for (;;)
  355. {
  356. if (finger->is_busy())
  357. {
  358. prev = finger;
  359. finger = finger->nextSender;
  360. if (finger==nullptr)
  361. {
  362. if (retry--)
  363. {
  364. if (udpTraceLevel > 4)
  365. DBGLOG("UdpReceive: All senders busy");
  366. MilliSleep(1);
  367. finger = pendingRequests;
  368. prev = nullptr;
  369. }
  370. else
  371. break; // give up and use first anyway
  372. }
  373. }
  374. else
  375. {
  376. if (finger != pendingRequests)
  377. {
  378. if (finger == lastPending)
  379. lastPending = prev;
  380. assert(prev != nullptr);
  381. prev->nextSender = finger->nextSender;
  382. finger->nextSender = pendingRequests;
  383. pendingRequests = finger;
  384. }
  385. break;
  386. }
  387. }
  388. }
  389. UdpSenderEntry *nextSender = pendingRequests;
  390. // remove from front of queue
  391. if (pendingRequests==lastPending)
  392. lastPending = nullptr;
  393. pendingRequests = nextSender->nextSender;
  394. nextSender->nextSender = nullptr;
  395. return okToSend(nextSender);
  396. }
  397. public:
  398. receive_receive_flow(CReceiveManager &_parent, unsigned flow_p, unsigned _maxSlotsPerSender)
  399. : Thread("UdpLib::receive_receive_flow"), parent(_parent), flow_port(flow_p), maxSlotsPerSender(_maxSlotsPerSender)
  400. {
  401. if (check_max_socket_read_buffer(udpFlowSocketsSize) < 0)
  402. throw MakeStringException(ROXIE_UDP_ERROR, "System Socket max read buffer is less than %i", udpFlowSocketsSize);
  403. flow_socket.setown(ISocket::udp_create(flow_port));
  404. flow_socket->set_receive_buffer_size(udpFlowSocketsSize);
  405. size32_t actualSize = flow_socket->get_receive_buffer_size();
  406. DBGLOG("UdpReceiver: receive_receive_flow created port=%d sockbuffsize=%d actual %d", flow_port, udpFlowSocketsSize, actualSize);
  407. }
  408. ~receive_receive_flow()
  409. {
  410. running = false;
  411. if (flow_socket)
  412. flow_socket->close();
  413. join();
  414. }
  415. virtual void start()
  416. {
  417. running = true;
  418. Thread::start();
  419. }
  420. virtual int run() override
  421. {
  422. DBGLOG("UdpReceiver: receive_receive_flow started");
  423. #ifdef __linux__
  424. setLinuxThreadPriority(3);
  425. #else
  426. adjustPriority(1);
  427. #endif
  428. UdpRequestToSendMsg msg;
  429. unsigned timeoutExpires = msTick() + 5000;
  430. while (running)
  431. {
  432. try
  433. {
  434. const unsigned l = sizeof(msg);
  435. unsigned int res ;
  436. unsigned now = msTick();
  437. if (now >= timeoutExpires)
  438. {
  439. if (currentRequester)
  440. timeoutExpires = now + timedOut(currentRequester);
  441. else
  442. timeoutExpires = now + 5000;
  443. }
  444. else
  445. {
  446. flow_socket->readtms(&msg, l, l, res, timeoutExpires-now);
  447. unsigned newTimeout = 0;
  448. assert(res==l);
  449. if (udpTraceLevel > 5)
  450. {
  451. StringBuffer ipStr;
  452. DBGLOG("UdpReceiver: received %s msg from node=%s", flowType::name(msg.cmd), msg.sourceNode.getTraceText(ipStr).str());
  453. }
  454. UdpSenderEntry *sender = &parent.sendersTable[msg.sourceNode];
  455. switch (msg.cmd)
  456. {
  457. case flowType::request_to_send:
  458. if (pendingRequests || currentRequester)
  459. enqueueRequest(sender); // timeoutExpires does not change - there's still an active request. We have not given a new permission
  460. else
  461. newTimeout = okToSend(sender);
  462. break;
  463. case flowType::send_completed:
  464. parent.inflight += msg.packets;
  465. if (noteDone(sender) && pendingRequests) // This && looks wrong - noteDone returning false should mean we haven't seen the completed we wanted - so current timeout still applies. Or the one below is wrong...
  466. newTimeout = sendNextOk();
  467. else
  468. newTimeout = 5000;
  469. break;
  470. case flowType::request_to_send_more:
  471. parent.inflight += msg.packets;
  472. if (noteDone(sender))
  473. {
  474. if (pendingRequests)
  475. {
  476. enqueueRequest(sender);
  477. newTimeout = sendNextOk();
  478. }
  479. else
  480. newTimeout = okToSend(sender);
  481. }
  482. break;
  483. default:
  484. DBGLOG("UdpReceiver: received unrecognized flow control message cmd=%i", msg.cmd);
  485. }
  486. if (newTimeout)
  487. timeoutExpires = msTick() + newTimeout;
  488. }
  489. }
  490. catch (IException *e)
  491. {
  492. // MORE - timeouts need some attention
  493. if (e->errorCode() == JSOCKERR_timeout_expired)
  494. {
  495. // A timeout implies that there is an active permission to send, but nothing has happened.
  496. // Could be a really busy (or crashed) agent, could be a lost packet
  497. if (currentRequester)
  498. timeoutExpires = msTick() + timedOut(currentRequester);
  499. }
  500. else if (running)
  501. {
  502. StringBuffer s;
  503. DBGLOG("UdpReceiver: failed %i %s", flow_port, e->errorMessage(s).str());
  504. }
  505. e->Release();
  506. }
  507. catch (...)
  508. {
  509. DBGLOG("UdpReceiver: receive_receive_flow::run unknown exception");
  510. }
  511. }
  512. return 0;
  513. }
  514. };
  515. class receive_data : public Thread
  516. {
  517. CReceiveManager &parent;
  518. ISocket *receive_socket;
  519. std::atomic<bool> running = { false };
  520. Semaphore started;
  521. public:
  522. receive_data(CReceiveManager &_parent) : Thread("UdpLib::receive_data"), parent(_parent)
  523. {
  524. unsigned ip_buffer = parent.input_queue_size*DATA_PAYLOAD*2;
  525. if (ip_buffer < udpFlowSocketsSize) ip_buffer = udpFlowSocketsSize;
  526. if (check_max_socket_read_buffer(ip_buffer) < 0)
  527. throw MakeStringException(ROXIE_UDP_ERROR, "System socket max read buffer is less than %u", ip_buffer);
  528. receive_socket = ISocket::udp_create(parent.data_port);
  529. receive_socket->set_receive_buffer_size(ip_buffer);
  530. size32_t actualSize = receive_socket->get_receive_buffer_size();
  531. DBGLOG("UdpReceiver: rcv_data_socket created port=%d requested sockbuffsize=%d actual sockbuffsize=%d", parent.data_port, ip_buffer, actualSize);
  532. running = false;
  533. }
  534. virtual void start()
  535. {
  536. running = true;
  537. Thread::start();
  538. started.wait();
  539. }
  540. ~receive_data()
  541. {
  542. running = false;
  543. if (receive_socket)
  544. receive_socket->close();
  545. join();
  546. ::Release(receive_socket);
  547. }
  548. virtual int run()
  549. {
  550. DBGLOG("UdpReceiver: receive_data started");
  551. #ifdef __linux__
  552. setLinuxThreadPriority(4);
  553. #else
  554. adjustPriority(2);
  555. #endif
  556. DataBuffer *b = NULL;
  557. started.signal();
  558. while (running)
  559. {
  560. try
  561. {
  562. unsigned int res;
  563. b = bufferManager->allocate();
  564. receive_socket->read(b->data, 1, DATA_PAYLOAD, res, 5);
  565. parent.inflight--;
  566. // MORE - reset it to zero if we fail to read data, or if avail_read returns 0.
  567. UdpPacketHeader &hdr = *(UdpPacketHeader *) b->data;
  568. assert(hdr.length == res && hdr.length > sizeof(hdr));
  569. if (udpTraceLevel > 5) // don't want to interrupt this thread if we can help it
  570. {
  571. StringBuffer s;
  572. DBGLOG("UdpReceiver: %u bytes received, node=%s", res, hdr.node.getTraceText(s).str());
  573. }
  574. parent.input_queue->pushOwn(b);
  575. b = NULL;
  576. }
  577. catch (IException *e)
  578. {
  579. ::Release(b);
  580. b = NULL;
  581. if (udpTraceLevel > 1 && parent.inflight)
  582. {
  583. DBGLOG("resetting inflight to 0 (was %d)", parent.inflight.load(std::memory_order_relaxed));
  584. }
  585. parent.inflight = 0;
  586. if (running && e->errorCode() != JSOCKERR_timeout_expired)
  587. {
  588. StringBuffer s;
  589. DBGLOG("UdpReceiver: receive_data::run read failed port=%u - Exp: %s", parent.data_port, e->errorMessage(s).str());
  590. MilliSleep(1000); // Give a chance for mem free
  591. }
  592. e->Release();
  593. }
  594. catch (...)
  595. {
  596. ::Release(b);
  597. b = NULL;
  598. DBGLOG("UdpReceiver: receive_data::run unknown exception port %u", parent.data_port);
  599. MilliSleep(1000);
  600. }
  601. }
  602. ::Release(b);
  603. return 0;
  604. }
  605. };
  606. class CPacketCollator : public Thread
  607. {
  608. CReceiveManager &parent;
  609. public:
  610. CPacketCollator(CReceiveManager &_parent) : Thread("CPacketCollator"), parent(_parent) {}
  611. virtual int run()
  612. {
  613. DBGLOG("UdpReceiver: CPacketCollator::run");
  614. parent.collatePackets();
  615. return 0;
  616. }
  617. } collatorThread;
  618. friend class receive_receive_flow;
  619. friend class receive_send_flow;
  620. friend class receive_data;
  621. friend class ReceiveFlowManager;
  622. friend class receive_sniffer;
  623. queue_t *input_queue;
  624. int input_queue_size;
  625. receive_receive_flow *receive_flow;
  626. receive_data *data;
  627. receive_sniffer *sniffer;
  628. int receive_flow_port;
  629. int data_port;
  630. std::atomic<bool> running = { false };
  631. typedef std::map<ruid_t, CMessageCollator*> uid_map;
  632. uid_map collators;
  633. SpinLock collatorsLock; // protects access to collators map
  634. // inflight is my best guess at how many packets may be sitting in socket buffers somewhere.
  635. // Incremented when I am notified about packets having been sent, decremented as they are read off the socket.
  636. std::atomic<int> inflight = {0};
  637. int free_slots()
  638. {
  639. int free = input_queue->free_slots(); // May block if collator thread is not removing from my queue fast enough
  640. // Ignore inflight if negative (can happen because we read some inflight before we see the send_done)
  641. int i = inflight.load(std::memory_order_relaxed);
  642. if (i < 0)
  643. {
  644. if (i < -input_queue->capacity())
  645. {
  646. if (udpTraceLevel)
  647. DBGLOG("UdpReceiver: ERROR: inflight has more packets in queue but not counted (%d) than queue capacity (%d)", -i, input_queue->capacity()); // Should never happen
  648. inflight = -input_queue->capacity();
  649. }
  650. i = 0;
  651. }
  652. else if (i >= free)
  653. {
  654. if ((i > free) && (udpTraceLevel))
  655. DBGLOG("UdpReceiver: ERROR: more packets in flight (%d) than slots free (%d)", i, free); // Should never happen
  656. inflight = i = free-1;
  657. }
  658. if (i && udpTraceLevel > 1)
  659. DBGLOG("UdpReceiver: adjusting free_slots to allow for %d in flight", i);
  660. return free - i;
  661. }
  662. public:
  663. IMPLEMENT_IINTERFACE;
  664. 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)
  665. : collatorThread(*this), sendersTable([client_flow_port](const ServerIdentifier &ip) { return new UdpSenderEntry(ip.getIpAddress(), client_flow_port);})
  666. {
  667. #ifndef _WIN32
  668. setpriority(PRIO_PROCESS, 0, -15);
  669. #endif
  670. receive_flow_port = server_flow_port;
  671. data_port = d_port;
  672. input_queue_size = queue_size;
  673. input_queue = new queue_t(queue_size);
  674. data = new receive_data(*this);
  675. receive_flow = new receive_receive_flow(*this, server_flow_port, m_slot_pr_client);
  676. if (udpSnifferEnabled)
  677. sniffer = new receive_sniffer(*this, snif_port, multicast_ip);
  678. else
  679. sniffer = nullptr;
  680. running = true;
  681. collatorThread.start();
  682. data->start();
  683. receive_flow->start();
  684. if (udpSnifferEnabled)
  685. sniffer->start();
  686. MilliSleep(15);
  687. }
  688. ~CReceiveManager()
  689. {
  690. running = false;
  691. input_queue->interrupt();
  692. collatorThread.join();
  693. delete data;
  694. delete receive_flow;
  695. delete sniffer;
  696. delete input_queue;
  697. }
  698. virtual void detachCollator(const IMessageCollator *msgColl)
  699. {
  700. ruid_t ruid = msgColl->queryRUID();
  701. if (udpTraceLevel >= 2) DBGLOG("UdpReceiver: detach %p %u", msgColl, ruid);
  702. {
  703. SpinBlock b(collatorsLock);
  704. collators.erase(ruid);
  705. }
  706. msgColl->Release();
  707. }
  708. void collatePackets()
  709. {
  710. while(running)
  711. {
  712. DataBuffer *dataBuff = input_queue->pop(true);
  713. collatePacket(dataBuff);
  714. }
  715. }
  716. void collatePacket(DataBuffer *dataBuff)
  717. {
  718. const UdpPacketHeader *pktHdr = (UdpPacketHeader*) dataBuff->data;
  719. if (udpTraceLevel >= 4)
  720. {
  721. StringBuffer s;
  722. DBGLOG("UdpReceiver: CPacketCollator - unQed packet - ruid=" RUIDF " id=0x%.8X mseq=%u pkseq=0x%.8X len=%d node=%s",
  723. pktHdr->ruid, pktHdr->msgId, pktHdr->msgSeq, pktHdr->pktSeq, pktHdr->length, pktHdr->node.getTraceText(s).str());
  724. }
  725. Linked <CMessageCollator> msgColl;
  726. bool isDefault = false;
  727. {
  728. SpinBlock b(collatorsLock);
  729. try
  730. {
  731. msgColl.set(collators[pktHdr->ruid]);
  732. if (!msgColl)
  733. {
  734. msgColl.set(collators[RUID_DISCARD]);
  735. isDefault = true;
  736. unwantedDiscarded++;
  737. }
  738. }
  739. catch (IException *E)
  740. {
  741. EXCLOG(E);
  742. E->Release();
  743. }
  744. catch (...)
  745. {
  746. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in CPacketCollator::run");
  747. EXCLOG(E);
  748. E->Release();
  749. }
  750. }
  751. if (udpTraceLevel && isDefault)
  752. {
  753. StringBuffer s;
  754. 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());
  755. }
  756. if (msgColl && msgColl->attach_databuffer(dataBuff))
  757. dataBuff = nullptr;
  758. else
  759. dataBuff->Release();
  760. }
  761. virtual IMessageCollator *createMessageCollator(IRowManager *rowManager, ruid_t ruid)
  762. {
  763. CMessageCollator *msgColl = new CMessageCollator(rowManager, ruid);
  764. if (udpTraceLevel >= 2)
  765. DBGLOG("UdpReceiver: createMessageCollator %p %u", msgColl, ruid);
  766. {
  767. SpinBlock b(collatorsLock);
  768. collators[ruid] = msgColl;
  769. }
  770. msgColl->Link();
  771. return msgColl;
  772. }
  773. };
  774. IReceiveManager *createReceiveManager(int server_flow_port, int data_port, int client_flow_port,
  775. int sniffer_port, const IpAddress &sniffer_multicast_ip,
  776. int udpQueueSize, unsigned maxSlotsPerSender)
  777. {
  778. assertex (maxSlotsPerSender <= (unsigned) udpQueueSize);
  779. return new CReceiveManager(server_flow_port, data_port, client_flow_port, sniffer_port, sniffer_multicast_ip, udpQueueSize, maxSlotsPerSender);
  780. }
  781. /*
  782. Thoughts on flow control / streaming:
  783. 1. The "continuation packet" mechanism does have some advantages
  784. - easy recovery from agent failures
  785. - agent recovers easily from Roxie server failures
  786. - flow control is simple (but is it effective?)
  787. 2. Abandoning continuation packet in favour of streaming would give us the following issues:
  788. - would need some flow control to stop getting ahead of a Roxie server that consumed slowly
  789. - 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
  790. - Need to work out how to do GSS - the nextGE info needs to be passed back in the flow control?
  791. - can't easily recover from agent failures if you already started processing
  792. - unless you assume that the results from agent are always deterministic and can retry and skip N
  793. - potentially ties up a agent thread for a while
  794. - do we need to have a larger thread pool but limit how many actually active?
  795. 3. Order of work
  796. - Just adding streaming while ignoring flow control and continuation stuff (i.e. we still stop for permission to continue periodically)
  797. - Shouldn't make anything any _worse_ ...
  798. - except that won't be able to recover from a agent dying mid-stream (at least not without some considerable effort)
  799. - what will happen then?
  800. - May also break server-side caching (that no-one has used AFAIK). Maybe restrict to nohits as we change....
  801. - Add some flow control
  802. - would prevent agent getting too far ahead in cases that are inadequately flow-controlled today
  803. - shouldn't make anything any worse...
  804. - Think about removing continuation mechanism from some cases
  805. 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,
  806. creating the segment monitors, creating the various cursors, and serialising the context (especially because there are likely to be multiple cursors).
  807. To add streaming:
  808. - Need to check for meta availability other than when first received
  809. - when ?
  810. - Need to cope with a getNext() blocking without it causing issues
  811. - perhaps should recode getNext() of variable-size rows first?
  812. More questions:
  813. - Can we afford the memory for the resend info?
  814. - Save maxPacketsPerSender per sender ?
  815. - are we really handling restart and sequence wraparound correctly?
  816. - what about server-side caching? Makes it hard
  817. - but maybe we should only cache tiny replies anyway....
  818. Problems found while testing implemetnation:
  819. - the unpacker cursor read code is crap
  820. - there is a potential to deadlock when need to make a callback agent->server during a streamed result (indexread5 illustrates)
  821. - resolution callback code doesn't really need to be query specific - could go to the default handler
  822. - but other callbacks - ALIVE, EXCEPTION, and debugger are not so clear
  823. - It's not at all clear where to move the code for processing metadata
  824. - callback paradigm would solve both - but it has to be on a client thread (e.g. from within call to next()).
  825. The following are used in "pseudo callback" mode:
  826. #define ROXIE_DEBUGREQUEST 0x3ffffff7u
  827. #define ROXIE_DEBUGCALLBACK 0x3ffffff8u
  828. #define ROXIE_PING 0x3ffffff9u
  829. - goes to own handler anyway
  830. #define ROXIE_TRACEINFO 0x3ffffffau
  831. - could go in meta? Not time critical. Could all go to single handler? (a bit hard since we want to intercept for caller...)
  832. #define ROXIE_FILECALLBACK 0x3ffffffbu
  833. - could go to single handler
  834. #define ROXIE_ALIVE 0x3ffffffcu
  835. - currently getting delayed a bit too much potentially if downstream processing is slow? Do I even need it if streaming?
  836. #define ROXIE_KEYEDLIMIT_EXCEEDED 0x3ffffffdu
  837. - could go in metadata of standard response
  838. #define ROXIE_LIMIT_EXCEEDED 0x3ffffffeu
  839. - ditto
  840. #define ROXIE_EXCEPTION 0x3fffffffu
  841. - ditto
  842. And the continuation metadata.
  843. What if EVERYTHING was a callback? - here's an exception... here's some more rows... here's some tracing... here's some continuation metadata
  844. 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)
  845. 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)
  846. 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
  847. (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 -
  848. you expect it to be continuous and you want the others to interrupt the flow.
  849. 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
  850. 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).
  851. 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?)
  852. Perhaps it makes sense to pause at this point (with streaming disabled and with retry mechanism optional)
  853. */