udpsha.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  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 "udplib.hpp"
  14. #include "udpsha.hpp"
  15. #include "jsocket.hpp"
  16. #include "jlog.hpp"
  17. #include "roxie.hpp"
  18. #include "roxiemem.hpp"
  19. #ifdef _WIN32
  20. #include <winsock2.h>
  21. #else
  22. #include <sys/socket.h>
  23. #endif
  24. using roxiemem::DataBuffer;
  25. using roxiemem::IDataBufferManager;
  26. IDataBufferManager *bufferManager;
  27. bool udpTraceFlow = false;
  28. bool udpTraceTimeouts = false;
  29. unsigned udpTraceLevel = 0;
  30. unsigned udpFlowSocketsSize = 131072;
  31. unsigned udpLocalWriteSocketSize = 1024000;
  32. unsigned udpStatsReportInterval = 60000;
  33. unsigned multicastTTL = 1;
  34. MODULE_INIT(INIT_PRIORITY_STANDARD)
  35. {
  36. bufferManager = roxiemem::createDataBufferManager(roxiemem::DATA_ALIGNMENT_SIZE);
  37. return true;
  38. }
  39. MODULE_EXIT()
  40. {
  41. bufferManager->Release();
  42. }
  43. const IpAddress ServerIdentifier::getIpAddress() const
  44. {
  45. IpAddress ret;
  46. ret.setIP4(netAddress);
  47. return ret;
  48. }
  49. bool ServerIdentifier::isMe() const
  50. {
  51. return *this==myNode;
  52. }
  53. ServerIdentifier myNode;
  54. //---------------------------------------------------------------------------------------------
  55. void queue_t::set_queue_size(unsigned _limit)
  56. {
  57. limit = _limit;
  58. }
  59. queue_t::queue_t(unsigned _limit)
  60. {
  61. set_queue_size(_limit);
  62. }
  63. queue_t::~queue_t()
  64. {
  65. while (head)
  66. {
  67. auto p = head;
  68. head = head->msgNext;
  69. ::Release(p);
  70. }
  71. }
  72. unsigned queue_t::available()
  73. {
  74. CriticalBlock b(c_region);
  75. if (count < limit)
  76. return limit - count;
  77. return 0;
  78. }
  79. int queue_t::free_slots()
  80. {
  81. int res=0;
  82. while (res <= 0)
  83. {
  84. c_region.enter();
  85. res = limit - count;
  86. if (res <= 0)
  87. signal_free_sl++;
  88. c_region.leave();
  89. if (res <= 0)
  90. {
  91. while (!free_sl.wait(3000))
  92. {
  93. if (udpTraceLevel >= 1)
  94. DBGLOG("queue_t::free_slots blocked for 3 seconds waiting for free_sl semaphore");
  95. }
  96. }
  97. }
  98. return res;
  99. }
  100. void queue_t::interrupt()
  101. {
  102. data_avail.interrupt();
  103. }
  104. void queue_t::pushOwn(DataBuffer *buf)
  105. {
  106. // Could probably be done lock-free, which given one thread using this is high priority might avoid some
  107. // potential priority-inversion issues. Or we might consider using PI-aware futexes here?
  108. assert(!buf->msgNext);
  109. {
  110. CriticalBlock b(c_region);
  111. if (tail)
  112. {
  113. assert(head);
  114. assert(!tail->msgNext);
  115. tail->msgNext = buf;
  116. }
  117. else
  118. {
  119. assert(!head);
  120. head = buf;
  121. }
  122. tail = buf;
  123. count++;
  124. #ifdef _DEBUG
  125. if (count > limit)
  126. DBGLOG("queue_t::pushOwn set count to %u", count);
  127. #endif
  128. }
  129. data_avail.signal();
  130. }
  131. DataBuffer *queue_t::pop(bool block)
  132. {
  133. if (!data_avail.wait(block ? INFINITE : 0))
  134. return nullptr;
  135. DataBuffer *ret = nullptr;
  136. unsigned signalFreeSlots = 0;
  137. {
  138. CriticalBlock b(c_region);
  139. if (!count)
  140. return nullptr;
  141. count--;
  142. ret = head;
  143. head = head->msgNext;
  144. if (!head)
  145. {
  146. assert(!count);
  147. tail = nullptr;
  148. }
  149. ret->msgNext = nullptr;
  150. if (count < limit && signal_free_sl)
  151. {
  152. signal_free_sl--;
  153. signalFreeSlots++;
  154. }
  155. }
  156. if (signalFreeSlots)
  157. free_sl.signal(signalFreeSlots);
  158. return ret;
  159. }
  160. unsigned queue_t::removeData(const void *key, PKT_CMP_FUN pkCmpFn)
  161. {
  162. unsigned removed = 0;
  163. unsigned signalFreeSlots = 0;
  164. {
  165. CriticalBlock b(c_region);
  166. if (count)
  167. {
  168. DataBuffer *prev = nullptr;
  169. DataBuffer *finger = head;
  170. while (finger)
  171. {
  172. if (!key || !pkCmpFn || pkCmpFn((const void*) finger, key))
  173. {
  174. auto temp = finger;
  175. finger = finger->msgNext;
  176. if (prev==nullptr)
  177. {
  178. assert(head==temp);
  179. head = finger;
  180. }
  181. else
  182. prev->msgNext = finger;
  183. if (temp==tail)
  184. tail = prev;
  185. ::Release(temp);
  186. count--;
  187. if (count < limit && signal_free_sl)
  188. {
  189. signal_free_sl--;
  190. signalFreeSlots++;
  191. }
  192. removed++;
  193. }
  194. else
  195. {
  196. prev = finger;
  197. finger = finger->msgNext;
  198. }
  199. }
  200. }
  201. }
  202. if (signalFreeSlots)
  203. free_sl.signal(signalFreeSlots);
  204. return removed;
  205. }
  206. bool queue_t::dataQueued(const void *key, PKT_CMP_FUN pkCmpFn)
  207. {
  208. CriticalBlock b(c_region);
  209. DataBuffer *finger = head;
  210. while (finger)
  211. {
  212. if (pkCmpFn((const void*) finger, key))
  213. return true;
  214. finger = finger->msgNext;
  215. }
  216. return false;
  217. }
  218. #ifndef _WIN32
  219. #define HOSTENT hostent
  220. #include <netdb.h>
  221. #endif
  222. int check_set(const char *path, int value)
  223. {
  224. #ifdef __linux__
  225. FILE *f = fopen(path,"r");
  226. char res[32];
  227. char *r = 0;
  228. int si = 0;
  229. if (f) {
  230. r = fgets(res, sizeof(res), f);
  231. fclose(f);
  232. }
  233. if (r)
  234. si = atoi(r);
  235. if (!si)
  236. {
  237. OWARNLOG("WARNING: Failed to read value for %s", path);
  238. return 0;
  239. }
  240. else if (si<value)
  241. return -1;
  242. #endif
  243. return 0;
  244. }
  245. int check_max_socket_read_buffer(int size) {
  246. return check_set("/proc/sys/net/core/rmem_max", size);
  247. }
  248. int check_max_socket_write_buffer(int size) {
  249. return check_set("/proc/sys/net/core/wmem_max", size);
  250. }
  251. #if defined( __linux__) || defined(__APPLE__)
  252. void setLinuxThreadPriority(int level)
  253. {
  254. pthread_t self = pthread_self();
  255. int policy;
  256. sched_param param;
  257. int rc;
  258. if (( rc = pthread_getschedparam(self, &policy, &param)) != 0)
  259. DBGLOG("pthread_getschedparam error: %d", rc);
  260. if (level < 0)
  261. UNIMPLEMENTED;
  262. else if (!level)
  263. {
  264. param.sched_priority = 0;
  265. policy = SCHED_OTHER;
  266. }
  267. else
  268. {
  269. policy = SCHED_RR;
  270. param.sched_priority = level;
  271. }
  272. if(( rc = pthread_setschedparam(self, policy, &param)) != 0)
  273. DBGLOG("pthread_setschedparam error: %d policy=%i pr=%i id=%" I64F "i TID=%i", rc, policy, param.sched_priority, (unsigned __int64) self, threadLogID());
  274. else
  275. DBGLOG("priority set id=%" I64F "i policy=%i pri=%i TID=%i", (unsigned __int64) self, policy, param.sched_priority, threadLogID());
  276. }
  277. #endif
  278. extern UDPLIB_API void queryMemoryPoolStats(StringBuffer &memStats)
  279. {
  280. if (bufferManager)
  281. bufferManager->poolStats(memStats);
  282. }
  283. RelaxedAtomic<unsigned> packetsOOO;
  284. bool PacketTracker::noteSeen(UdpPacketHeader &hdr)
  285. {
  286. bool resent = false;
  287. sequence_t seq = hdr.sendSeq;
  288. if (hdr.pktSeq & UDP_PACKET_RESENT)
  289. resent = true;
  290. // Four cases: less than lastUnseen, equal to, within TRACKER_BITS of, or higher
  291. // Be careful to think about wrapping. Less than and higher can't really be distinguished, but we treat resent differently from original
  292. bool duplicate = false;
  293. unsigned delta = seq - base;
  294. if (udpTraceLevel > 5)
  295. {
  296. DBGLOG("PacketTracker::noteSeen %" SEQF "u: delta %d", hdr.sendSeq, delta);
  297. dump();
  298. }
  299. if (delta < TRACKER_BITS)
  300. {
  301. unsigned idx = (seq / 64) % TRACKER_DWORDS;
  302. unsigned bit = seq % 64;
  303. __uint64 bitm = U64C(1)<<bit;
  304. duplicate = (seen[idx] & bitm) != 0;
  305. seen[idx] |= bitm;
  306. if (seq==base)
  307. {
  308. while (seen[idx] & bitm)
  309. {
  310. // Important to update in this order, so that during the window where they are inconsistent we have
  311. // false negatives rather than false positives
  312. seen[idx] &= ~bitm;
  313. base++;
  314. idx = (base / 64) % TRACKER_DWORDS;
  315. bit = base % 64;
  316. bitm = U64C(1)<<bit;
  317. }
  318. }
  319. // calculate new hwm, with some care for wrapping
  320. if ((int) (seq - hwm) > 0)
  321. hwm = seq;
  322. else if (!resent)
  323. packetsOOO++;
  324. }
  325. else if (resent)
  326. // Don't treat a resend that goes out of range as indicative of a restart - it probably just means
  327. // that the resend was not needed and the original moved things on when it arrived
  328. duplicate = true;
  329. else
  330. {
  331. // We've gone forwards too far to track, or backwards because server restarted
  332. // We have taken steps to try to avoid the former...
  333. // In theory could try to preserve SOME information in the former case, but as it shouldn't happen, can we be bothered?
  334. #ifdef _DEBUG
  335. if (udpResendEnabled)
  336. {
  337. DBGLOG("Received packet %" SEQF "u will cause loss of information in PacketTracker", seq);
  338. dump();
  339. }
  340. //assert(false);
  341. #endif
  342. memset(seen, 0, sizeof(seen));
  343. base = seq+1;
  344. hwm = seq;
  345. }
  346. return duplicate;
  347. }
  348. const PacketTracker PacketTracker::copy() const
  349. {
  350. // This is called within a critical section. Would be better if we could avoid having to do so,
  351. // but we want to be able to read a consistent set of values
  352. PacketTracker ret;
  353. ret.base = base;
  354. ret.hwm = hwm;
  355. memcpy(ret.seen, seen, sizeof(seen));
  356. return ret;
  357. }
  358. bool PacketTracker::hasSeen(sequence_t seq) const
  359. {
  360. // Accessed only on sender side where these are not modified, so no need for locking
  361. // Careful about wrapping!
  362. unsigned delta = seq - base;
  363. if (udpTraceLevel > 5)
  364. {
  365. DBGLOG("PacketTracker::hasSeen - have I seen %" SEQF "u, %d", seq, delta);
  366. dump();
  367. }
  368. if (delta < TRACKER_BITS)
  369. {
  370. unsigned idx = (seq / 64) % TRACKER_DWORDS;
  371. unsigned bit = seq % 64;
  372. return (seen[idx] & (U64C(1)<<bit)) != 0;
  373. }
  374. else if (delta > INT_MAX) // Or we could just make delta a signed int? But code above would have to check >0
  375. return true;
  376. else
  377. return false;
  378. }
  379. bool PacketTracker::canRecord(sequence_t seq) const
  380. {
  381. // Careful about wrapping!
  382. unsigned delta = seq - base;
  383. if (udpTraceLevel > 5)
  384. {
  385. DBGLOG("PacketTracker::hasSeen - can I record %" SEQF "u, %d", seq, delta);
  386. dump();
  387. }
  388. return (delta < TRACKER_BITS);
  389. }
  390. bool PacketTracker::hasGaps() const
  391. {
  392. return base!=hwm+1;
  393. }
  394. void PacketTracker::dump() const
  395. {
  396. DBGLOG("PacketTracker base=%" SEQF "u, hwm=%" SEQF "u, seen[0]=%" I64F "x", base, hwm, seen[0]);
  397. }
  398. #ifdef _USE_CPPUNIT
  399. #include "unittests.hpp"
  400. class PacketTrackerTest : public CppUnit::TestFixture
  401. {
  402. CPPUNIT_TEST_SUITE(PacketTrackerTest);
  403. CPPUNIT_TEST(testNoteSeen);
  404. CPPUNIT_TEST(testReplay);
  405. CPPUNIT_TEST_SUITE_END();
  406. void testNoteSeen()
  407. {
  408. PacketTracker p;
  409. UdpPacketHeader hdr;
  410. hdr.pktSeq = 0;
  411. // Some simple tests
  412. CPPUNIT_ASSERT(!p.hasSeen(0));
  413. CPPUNIT_ASSERT(!p.hasSeen(1));
  414. hdr.sendSeq = 0;
  415. CPPUNIT_ASSERT(!p.noteSeen(hdr));
  416. CPPUNIT_ASSERT(p.hasSeen(0));
  417. CPPUNIT_ASSERT(!p.hasSeen(1));
  418. CPPUNIT_ASSERT(!p.hasSeen(2000));
  419. CPPUNIT_ASSERT(!p.hasSeen(2001));
  420. hdr.pktSeq = UDP_PACKET_RESENT;
  421. CPPUNIT_ASSERT(p.noteSeen(hdr));
  422. hdr.pktSeq = 0;
  423. hdr.sendSeq = 2000;
  424. CPPUNIT_ASSERT(!p.noteSeen(hdr));
  425. CPPUNIT_ASSERT(p.hasSeen(0));
  426. CPPUNIT_ASSERT(p.hasSeen(1));
  427. CPPUNIT_ASSERT(p.hasSeen(2000));
  428. CPPUNIT_ASSERT(!p.hasSeen(2001));
  429. hdr.sendSeq = 0;
  430. CPPUNIT_ASSERT(!p.noteSeen(hdr));
  431. CPPUNIT_ASSERT(p.hasSeen(0));
  432. CPPUNIT_ASSERT(!p.hasSeen(1));
  433. CPPUNIT_ASSERT(!p.hasSeen(2000));
  434. CPPUNIT_ASSERT(!p.hasSeen(2001));
  435. PacketTracker p2;
  436. hdr.sendSeq = 1;
  437. CPPUNIT_ASSERT(!p2.noteSeen(hdr));
  438. CPPUNIT_ASSERT(!p2.hasSeen(0));
  439. CPPUNIT_ASSERT(p2.hasSeen(1));
  440. hdr.sendSeq = TRACKER_BITS-1; // This is the highest value we can record without losing information
  441. CPPUNIT_ASSERT(!p2.noteSeen(hdr));
  442. CPPUNIT_ASSERT(!p2.hasSeen(0));
  443. CPPUNIT_ASSERT(p2.hasSeen(1));
  444. CPPUNIT_ASSERT(p2.hasSeen(TRACKER_BITS-1));
  445. CPPUNIT_ASSERT(!p2.hasSeen(TRACKER_BITS));
  446. CPPUNIT_ASSERT(!p2.hasSeen(TRACKER_BITS+1));
  447. hdr.sendSeq = TRACKER_BITS;
  448. p2.noteSeen(hdr);
  449. CPPUNIT_ASSERT(p2.hasSeen(0));
  450. CPPUNIT_ASSERT(p2.hasSeen(1));
  451. CPPUNIT_ASSERT(p2.hasSeen(TRACKER_BITS-1));
  452. CPPUNIT_ASSERT(p2.hasSeen(TRACKER_BITS));
  453. CPPUNIT_ASSERT(!p2.hasSeen(TRACKER_BITS+1));
  454. CPPUNIT_ASSERT(!p2.hasSeen(TRACKER_BITS+2));
  455. }
  456. void t(PacketTracker &p, sequence_t seq, unsigned pseq)
  457. {
  458. UdpPacketHeader hdr;
  459. hdr.sendSeq = seq;
  460. hdr.pktSeq = pseq;
  461. if (seq==29)
  462. CPPUNIT_ASSERT(p.noteSeen(hdr) == false);
  463. else
  464. p.noteSeen(hdr);
  465. }
  466. void testReplay()
  467. {
  468. PacketTracker p;
  469. t(p,1,0x1);
  470. t(p,2,0x2);
  471. t(p,3,0x3);
  472. t(p,4,0x4);
  473. t(p,5,0x5);
  474. t(p,6,0x6);
  475. t(p,7,0x7);
  476. t(p,8,0x8);
  477. t(p,9,0x9);
  478. t(p,11,0xb);
  479. t(p,12,0xc);
  480. t(p,13,0xd);
  481. t(p,14,0xe);
  482. t(p,15,0xf);
  483. t(p,16,0x10);
  484. t(p,17,0x11);
  485. t(p,18,0x12);
  486. t(p,19,0x13);
  487. t(p,20,0x14);
  488. t(p,21,0x15);
  489. t(p,22,0x16);
  490. t(p,23,0x17);
  491. t(p,24,0x18);
  492. t(p,25,0x19);
  493. t(p,26,0x1a);
  494. t(p,27,0x1b);
  495. t(p,28,0x1c);
  496. t(p,50,0x40000032);
  497. t(p,51,0x40000033);
  498. t(p,52,0x40000034);
  499. t(p,53,0x40000035);
  500. t(p,54,0x40000036);
  501. t(p,55,0x40000037);
  502. t(p,56,0x40000038);
  503. t(p,57,0x40000039);
  504. t(p,58,0x4000003a);
  505. t(p,59,0x4000003b);
  506. t(p,60,0x4000003c);
  507. t(p,61,0x4000003d);
  508. t(p,62,0xc0000000);
  509. t(p,63,0x4000003e);
  510. t(p,64,0x4000003f);
  511. t(p,65,0x40000040);
  512. t(p,66,0x40000041);
  513. t(p,67,0x40000042);
  514. t(p,68,0x40000043);
  515. t(p,69,0x40000044);
  516. t(p,70,0x40000045);
  517. t(p,71,0x40000046);
  518. t(p,72,0x40000047);
  519. t(p,73,0x40000048);
  520. t(p,74,0x40000049);
  521. t(p,75,0x4000004a);
  522. t(p,76,0x4000004b);
  523. t(p,77,0x4000004c);
  524. t(p,78,0x4000004d);
  525. t(p,79,0x4000004e);
  526. t(p,80,0x4000004f);
  527. t(p,81,0x40000050);
  528. t(p,82,0x40000051);
  529. t(p,83,0x40000052);
  530. t(p,84,0x40000053);
  531. t(p,85,0x40000054);
  532. t(p,86,0x40000055);
  533. t(p,87,0x40000056);
  534. t(p,88,0x40000057);
  535. t(p,89,0x40000058);
  536. t(p,90,0x40000059);
  537. t(p,91,0x4000005a);
  538. t(p,92,0x4000005b);
  539. t(p,93,0x4000005c);
  540. t(p,0,0x40000000);
  541. t(p,1,0x40000001);
  542. t(p,2,0x40000002);
  543. t(p,3,0x40000003);
  544. t(p,4,0x40000004);
  545. t(p,5,0x40000005);
  546. t(p,6,0x40000006);
  547. t(p,7,0x40000007);
  548. t(p,8,0x40000008);
  549. t(p,9,0x40000009);
  550. t(p,10,0x4000000a);
  551. t(p,11,0x4000000b);
  552. t(p,12,0x4000000c);
  553. t(p,13,0x4000000d);
  554. t(p,14,0x4000000e);
  555. t(p,15,0x4000000f);
  556. t(p,16,0x40000010);
  557. t(p,17,0x40000011);
  558. t(p,18,0x40000012);
  559. t(p,19,0x40000013);
  560. t(p,20,0x40000014);
  561. t(p,21,0x40000015);
  562. t(p,22,0x40000016);
  563. t(p,23,0x40000017);
  564. t(p,24,0x40000018);
  565. t(p,25,0x40000019);
  566. t(p,26,0x4000001a);
  567. t(p,27,0x4000001b);
  568. t(p,28,0x4000001c);
  569. t(p,29,0x4000001d);
  570. }
  571. };
  572. CPPUNIT_TEST_SUITE_REGISTRATION( PacketTrackerTest );
  573. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( PacketTrackerTest, "PacketTrackerTest" );
  574. #endif
  575. /*
  576. Crazy thoughts on network-wide flow control
  577. Avoid sending data that clashes with other outbound or inbound data
  578. is outbound really an issue?
  579. if only inbound, should be easier
  580. can have each inbound node police its own, for a start
  581. udplib already tries to do this
  582. when sending permission to send, best to pick someone that is not sending to anyone else
  583. udplib already tries to do this
  584. but it can still lead to idleness - id node 1 sending to node 2, and node2 to node 1, node3 can't find anyone idle.
  585. If you do need global:
  586. Every bit of data getting sent (perhaps over a certain size threshold?) gets permission from central traffic cop
  587. Outbound packet says source node, target node size
  588. Reply says source,target,size
  589. Cop allows immediately if nothing inflight between those pairs
  590. Cop assumes completion
  591. Cop redundancy
  592. - a backup cop is listening in?
  593. - use multicast for requests and replies?
  594. - no reply implies what?
  595. - backup cop just needs heartbeat from active cop
  596. - permission expires
  597. - multiple cops for blocks of targets?
  598. - but I want global view of who is sending
  599. */