Path.hpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  1. /*
  2. * Copyright (c)2019 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2023-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #ifndef ZT_PATH_HPP
  14. #define ZT_PATH_HPP
  15. #include <stdint.h>
  16. #include <string.h>
  17. #include <stdlib.h>
  18. #include <stdexcept>
  19. #include <algorithm>
  20. #include "Constants.hpp"
  21. #include "InetAddress.hpp"
  22. #include "SharedPtr.hpp"
  23. #include "AtomicCounter.hpp"
  24. #include "Utils.hpp"
  25. #include "RingBuffer.hpp"
  26. #include "Packet.hpp"
  27. #include "../osdep/Phy.hpp"
  28. /**
  29. * Maximum return value of preferenceRank()
  30. */
  31. #define ZT_PATH_MAX_PREFERENCE_RANK ((ZT_INETADDRESS_MAX_SCOPE << 1) | 1)
  32. namespace ZeroTier {
  33. class RuntimeEnvironment;
  34. /**
  35. * A path across the physical network
  36. */
  37. class Path
  38. {
  39. friend class SharedPtr<Path>;
  40. Phy<Path *> *_phy;
  41. public:
  42. /**
  43. * Efficient unique key for paths in a Hashtable
  44. */
  45. class HashKey
  46. {
  47. public:
  48. HashKey() {}
  49. HashKey(const int64_t l,const InetAddress &r)
  50. {
  51. if (r.ss_family == AF_INET) {
  52. _k[0] = (uint64_t)reinterpret_cast<const struct sockaddr_in *>(&r)->sin_addr.s_addr;
  53. _k[1] = (uint64_t)reinterpret_cast<const struct sockaddr_in *>(&r)->sin_port;
  54. _k[2] = (uint64_t)l;
  55. } else if (r.ss_family == AF_INET6) {
  56. memcpy(_k,reinterpret_cast<const struct sockaddr_in6 *>(&r)->sin6_addr.s6_addr,16);
  57. _k[2] = ((uint64_t)reinterpret_cast<const struct sockaddr_in6 *>(&r)->sin6_port << 32) ^ (uint64_t)l;
  58. } else {
  59. memcpy(_k,&r,std::min(sizeof(_k),sizeof(InetAddress)));
  60. _k[2] += (uint64_t)l;
  61. }
  62. }
  63. inline unsigned long hashCode() const { return (unsigned long)(_k[0] + _k[1] + _k[2]); }
  64. inline bool operator==(const HashKey &k) const { return ( (_k[0] == k._k[0]) && (_k[1] == k._k[1]) && (_k[2] == k._k[2]) ); }
  65. inline bool operator!=(const HashKey &k) const { return (!(*this == k)); }
  66. private:
  67. uint64_t _k[3];
  68. };
  69. Path() :
  70. _lastOut(0),
  71. _lastIn(0),
  72. _lastTrustEstablishedPacketReceived(0),
  73. _lastPathQualityComputeTime(0),
  74. _localSocket(-1),
  75. _latency(0xffff),
  76. _addr(),
  77. _ipScope(InetAddress::IP_SCOPE_NONE),
  78. _lastAck(0),
  79. _lastThroughputEstimation(0),
  80. _lastQoSMeasurement(0),
  81. _lastQoSRecordPurge(0),
  82. _unackedBytes(0),
  83. _expectingAckAsOf(0),
  84. _packetsReceivedSinceLastAck(0),
  85. _packetsReceivedSinceLastQoS(0),
  86. _maxLifetimeThroughput(0),
  87. _lastComputedMeanThroughput(0),
  88. _bytesAckedSinceLastThroughputEstimation(0),
  89. _lastComputedMeanLatency(0.0),
  90. _lastComputedPacketDelayVariance(0.0),
  91. _lastComputedPacketErrorRatio(0.0),
  92. _lastComputedPacketLossRatio(0),
  93. _lastComputedStability(0.0),
  94. _lastComputedRelativeQuality(0),
  95. _lastComputedThroughputDistCoeff(0.0),
  96. _lastAllocation(0)
  97. {
  98. memset(_ifname, 0, 16);
  99. memset(_addrString, 0, sizeof(_addrString));
  100. }
  101. Path(const int64_t localSocket,const InetAddress &addr) :
  102. _lastOut(0),
  103. _lastIn(0),
  104. _lastTrustEstablishedPacketReceived(0),
  105. _lastPathQualityComputeTime(0),
  106. _localSocket(localSocket),
  107. _latency(0xffff),
  108. _addr(addr),
  109. _ipScope(addr.ipScope()),
  110. _lastAck(0),
  111. _lastThroughputEstimation(0),
  112. _lastQoSMeasurement(0),
  113. _lastQoSRecordPurge(0),
  114. _unackedBytes(0),
  115. _expectingAckAsOf(0),
  116. _packetsReceivedSinceLastAck(0),
  117. _packetsReceivedSinceLastQoS(0),
  118. _maxLifetimeThroughput(0),
  119. _lastComputedMeanThroughput(0),
  120. _bytesAckedSinceLastThroughputEstimation(0),
  121. _lastComputedMeanLatency(0.0),
  122. _lastComputedPacketDelayVariance(0.0),
  123. _lastComputedPacketErrorRatio(0.0),
  124. _lastComputedPacketLossRatio(0),
  125. _lastComputedStability(0.0),
  126. _lastComputedRelativeQuality(0),
  127. _lastComputedThroughputDistCoeff(0.0),
  128. _lastAllocation(0)
  129. {
  130. memset(_ifname, 0, 16);
  131. memset(_addrString, 0, sizeof(_addrString));
  132. if (_localSocket != -1) {
  133. _phy->getIfName((PhySocket *) ((uintptr_t) _localSocket), _ifname, 16);
  134. }
  135. }
  136. /**
  137. * Called when a packet is received from this remote path, regardless of content
  138. *
  139. * @param t Time of receive
  140. */
  141. inline void received(const uint64_t t) { _lastIn = t; }
  142. /**
  143. * Set time last trusted packet was received (done in Peer::received())
  144. */
  145. inline void trustedPacketReceived(const uint64_t t) { _lastTrustEstablishedPacketReceived = t; }
  146. /**
  147. * Send a packet via this path (last out time is also updated)
  148. *
  149. * @param RR Runtime environment
  150. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  151. * @param data Packet data
  152. * @param len Packet length
  153. * @param now Current time
  154. * @return True if transport reported success
  155. */
  156. bool send(const RuntimeEnvironment *RR,void *tPtr,const void *data,unsigned int len,int64_t now);
  157. /**
  158. * Manually update last sent time
  159. *
  160. * @param t Time of send
  161. */
  162. inline void sent(const int64_t t) { _lastOut = t; }
  163. /**
  164. * Update path latency with a new measurement
  165. *
  166. * @param l Measured latency
  167. */
  168. inline void updateLatency(const unsigned int l, int64_t now)
  169. {
  170. unsigned int pl = _latency;
  171. if (pl < 0xffff) {
  172. _latency = (pl + l) / 2;
  173. }
  174. else {
  175. _latency = l;
  176. }
  177. _latencySamples.push(l);
  178. }
  179. /**
  180. * @return Local socket as specified by external code
  181. */
  182. inline int64_t localSocket() const { return _localSocket; }
  183. /**
  184. * @return Physical address
  185. */
  186. inline const InetAddress &address() const { return _addr; }
  187. /**
  188. * @return IP scope -- faster shortcut for address().ipScope()
  189. */
  190. inline InetAddress::IpScope ipScope() const { return _ipScope; }
  191. /**
  192. * @return True if path has received a trust established packet (e.g. common network membership) in the past ZT_TRUST_EXPIRATION ms
  193. */
  194. inline bool trustEstablished(const int64_t now) const { return ((now - _lastTrustEstablishedPacketReceived) < ZT_TRUST_EXPIRATION); }
  195. /**
  196. * @return Preference rank, higher == better
  197. */
  198. inline unsigned int preferenceRank() const
  199. {
  200. // This causes us to rank paths in order of IP scope rank (see InetAdddress.hpp) but
  201. // within each IP scope class to prefer IPv6 over IPv4.
  202. return ( ((unsigned int)_ipScope << 1) | (unsigned int)(_addr.ss_family == AF_INET6) );
  203. }
  204. /**
  205. * Check whether this address is valid for a ZeroTier path
  206. *
  207. * This checks the address type and scope against address types and scopes
  208. * that we currently support for ZeroTier communication.
  209. *
  210. * @param a Address to check
  211. * @return True if address is good for ZeroTier path use
  212. */
  213. static inline bool isAddressValidForPath(const InetAddress &a)
  214. {
  215. if ((a.ss_family == AF_INET)||(a.ss_family == AF_INET6)) {
  216. switch(a.ipScope()) {
  217. /* Note: we don't do link-local at the moment. Unfortunately these
  218. * cause several issues. The first is that they usually require a
  219. * device qualifier, which we don't handle yet and can't portably
  220. * push in PUSH_DIRECT_PATHS. The second is that some OSes assign
  221. * these very ephemerally or otherwise strangely. So we'll use
  222. * private, pseudo-private, shared (e.g. carrier grade NAT), or
  223. * global IP addresses. */
  224. case InetAddress::IP_SCOPE_PRIVATE:
  225. case InetAddress::IP_SCOPE_PSEUDOPRIVATE:
  226. case InetAddress::IP_SCOPE_SHARED:
  227. case InetAddress::IP_SCOPE_GLOBAL:
  228. if (a.ss_family == AF_INET6) {
  229. // TEMPORARY HACK: for now, we are going to blacklist he.net IPv6
  230. // tunnels due to very spotty performance and low MTU issues over
  231. // these IPv6 tunnel links.
  232. const uint8_t *ipd = reinterpret_cast<const uint8_t *>(reinterpret_cast<const struct sockaddr_in6 *>(&a)->sin6_addr.s6_addr);
  233. if ((ipd[0] == 0x20)&&(ipd[1] == 0x01)&&(ipd[2] == 0x04)&&(ipd[3] == 0x70))
  234. return false;
  235. }
  236. return true;
  237. default:
  238. return false;
  239. }
  240. }
  241. return false;
  242. }
  243. /**
  244. * @return Latency or 0xffff if unknown
  245. */
  246. inline unsigned int latency() const { return _latency; }
  247. /**
  248. * @return Path quality -- lower is better
  249. */
  250. inline long quality(const int64_t now) const
  251. {
  252. const int l = (long)_latency;
  253. const int age = (long)std::min((now - _lastIn),(int64_t)(ZT_PATH_HEARTBEAT_PERIOD * 10)); // set an upper sanity limit to avoid overflow
  254. return (((age < (ZT_PATH_HEARTBEAT_PERIOD + 5000)) ? l : (l + 0xffff + age)) * (long)((ZT_INETADDRESS_MAX_SCOPE - _ipScope) + 1));
  255. }
  256. /**
  257. * Record statistics on outgoing packets. Used later to estimate QoS metrics.
  258. *
  259. * @param now Current time
  260. * @param packetId ID of packet
  261. * @param payloadLength Length of payload
  262. * @param verb Packet verb
  263. */
  264. inline void recordOutgoingPacket(int64_t now, int64_t packetId, uint16_t payloadLength, Packet::Verb verb)
  265. {
  266. Mutex::Lock _l(_statistics_m);
  267. if (verb != Packet::VERB_ACK && verb != Packet::VERB_QOS_MEASUREMENT) {
  268. if ((packetId & (ZT_PATH_QOS_ACK_PROTOCOL_DIVISOR - 1)) == 0) {
  269. _unackedBytes += payloadLength;
  270. // Take note that we're expecting a VERB_ACK on this path as of a specific time
  271. _expectingAckAsOf = ackAge(now) > ZT_PATH_ACK_INTERVAL ? _expectingAckAsOf : now;
  272. if (_outQoSRecords.size() < ZT_PATH_MAX_OUTSTANDING_QOS_RECORDS) {
  273. _outQoSRecords[packetId] = now;
  274. }
  275. }
  276. }
  277. }
  278. /**
  279. * Record statistics on incoming packets. Used later to estimate QoS metrics.
  280. *
  281. * @param now Current time
  282. * @param packetId ID of packet
  283. * @param payloadLength Length of payload
  284. * @param verb Packet verb
  285. */
  286. inline void recordIncomingPacket(int64_t now, int64_t packetId, uint16_t payloadLength, Packet::Verb verb)
  287. {
  288. Mutex::Lock _l(_statistics_m);
  289. if (verb != Packet::VERB_ACK && verb != Packet::VERB_QOS_MEASUREMENT) {
  290. if ((packetId & (ZT_PATH_QOS_ACK_PROTOCOL_DIVISOR - 1)) == 0) {
  291. _inACKRecords[packetId] = payloadLength;
  292. _packetsReceivedSinceLastAck++;
  293. _inQoSRecords[packetId] = now;
  294. _packetsReceivedSinceLastQoS++;
  295. }
  296. _packetValiditySamples.push(true);
  297. }
  298. }
  299. /**
  300. * Record that we've received a VERB_ACK on this path, also compute throughput if required.
  301. *
  302. * @param now Current time
  303. * @param ackedBytes Number of bytes acknowledged by other peer
  304. */
  305. inline void receivedAck(int64_t now, int32_t ackedBytes)
  306. {
  307. _expectingAckAsOf = 0;
  308. _unackedBytes = (ackedBytes > _unackedBytes) ? 0 : _unackedBytes - ackedBytes;
  309. int64_t timeSinceThroughputEstimate = (now - _lastThroughputEstimation);
  310. if (timeSinceThroughputEstimate >= ZT_PATH_THROUGHPUT_MEASUREMENT_INTERVAL) {
  311. uint64_t throughput = (uint64_t)((float)(_bytesAckedSinceLastThroughputEstimation * 8) / ((float)timeSinceThroughputEstimate / (float)1000));
  312. _throughputSamples.push(throughput);
  313. _maxLifetimeThroughput = throughput > _maxLifetimeThroughput ? throughput : _maxLifetimeThroughput;
  314. _lastThroughputEstimation = now;
  315. _bytesAckedSinceLastThroughputEstimation = 0;
  316. } else {
  317. _bytesAckedSinceLastThroughputEstimation += ackedBytes;
  318. }
  319. }
  320. /**
  321. * @return Number of bytes this peer is responsible for ACKing since last ACK
  322. */
  323. inline int32_t bytesToAck()
  324. {
  325. Mutex::Lock _l(_statistics_m);
  326. int32_t bytesToAck = 0;
  327. std::map<uint64_t,uint16_t>::iterator it = _inACKRecords.begin();
  328. while (it != _inACKRecords.end()) {
  329. bytesToAck += it->second;
  330. it++;
  331. }
  332. return bytesToAck;
  333. }
  334. /**
  335. * @return Number of bytes thus far sent that have not been acknowledged by the remote peer
  336. */
  337. inline int64_t unackedSentBytes()
  338. {
  339. return _unackedBytes;
  340. }
  341. /**
  342. * Account for the fact that an ACK was just sent. Reset counters, timers, and clear statistics buffers
  343. *
  344. * @param Current time
  345. */
  346. inline void sentAck(int64_t now)
  347. {
  348. Mutex::Lock _l(_statistics_m);
  349. _inACKRecords.clear();
  350. _packetsReceivedSinceLastAck = 0;
  351. _lastAck = now;
  352. }
  353. /**
  354. * Receive QoS data, match with recorded egress times from this peer, compute latency
  355. * estimates.
  356. *
  357. * @param now Current time
  358. * @param count Number of records
  359. * @param rx_id table of packet IDs
  360. * @param rx_ts table of holding times
  361. */
  362. inline void receivedQoS(int64_t now, int count, uint64_t *rx_id, uint16_t *rx_ts)
  363. {
  364. Mutex::Lock _l(_statistics_m);
  365. // Look up egress times and compute latency values for each record
  366. std::map<uint64_t,uint64_t>::iterator it;
  367. for (int j=0; j<count; j++) {
  368. it = _outQoSRecords.find(rx_id[j]);
  369. if (it != _outQoSRecords.end()) {
  370. uint16_t rtt = (uint16_t)(now - it->second);
  371. uint16_t rtt_compensated = rtt - rx_ts[j];
  372. uint16_t latency = rtt_compensated / 2;
  373. updateLatency(latency, now);
  374. _outQoSRecords.erase(it);
  375. }
  376. }
  377. }
  378. /**
  379. * Generate the contents of a VERB_QOS_MEASUREMENT packet.
  380. *
  381. * @param now Current time
  382. * @param qosBuffer destination buffer
  383. * @return Size of payload
  384. */
  385. inline int32_t generateQoSPacket(int64_t now, char *qosBuffer)
  386. {
  387. Mutex::Lock _l(_statistics_m);
  388. int32_t len = 0;
  389. std::map<uint64_t,uint64_t>::iterator it = _inQoSRecords.begin();
  390. int i=0;
  391. while (i<_packetsReceivedSinceLastQoS && it != _inQoSRecords.end()) {
  392. uint64_t id = it->first;
  393. memcpy(qosBuffer, &id, sizeof(uint64_t));
  394. qosBuffer+=sizeof(uint64_t);
  395. uint16_t holdingTime = (uint16_t)(now - it->second);
  396. memcpy(qosBuffer, &holdingTime, sizeof(uint16_t));
  397. qosBuffer+=sizeof(uint16_t);
  398. len+=sizeof(uint64_t)+sizeof(uint16_t);
  399. _inQoSRecords.erase(it++);
  400. i++;
  401. }
  402. return len;
  403. }
  404. /**
  405. * Account for the fact that a VERB_QOS_MEASUREMENT was just sent. Reset timers.
  406. *
  407. * @param Current time
  408. */
  409. inline void sentQoS(int64_t now) {
  410. _packetsReceivedSinceLastQoS = 0;
  411. _lastQoSMeasurement = now;
  412. }
  413. /**
  414. * @param now Current time
  415. * @return Whether an ACK (VERB_ACK) packet needs to be emitted at this time
  416. */
  417. inline bool needsToSendAck(int64_t now) {
  418. return ((now - _lastAck) >= ZT_PATH_ACK_INTERVAL ||
  419. (_packetsReceivedSinceLastAck == ZT_PATH_QOS_TABLE_SIZE)) && _packetsReceivedSinceLastAck;
  420. }
  421. /**
  422. * @param now Current time
  423. * @return Whether a QoS (VERB_QOS_MEASUREMENT) packet needs to be emitted at this time
  424. */
  425. inline bool needsToSendQoS(int64_t now) {
  426. return ((_packetsReceivedSinceLastQoS >= ZT_PATH_QOS_TABLE_SIZE) ||
  427. ((now - _lastQoSMeasurement) > ZT_PATH_QOS_INTERVAL)) && _packetsReceivedSinceLastQoS;
  428. }
  429. /**
  430. * How much time has elapsed since we've been expecting a VERB_ACK on this path. This value
  431. * is used to determine a more relevant path "age". This lets us penalize paths which are no
  432. * longer ACKing, but not those that simple aren't being used to carry traffic at the
  433. * current time.
  434. */
  435. inline int64_t ackAge(int64_t now) { return _expectingAckAsOf ? now - _expectingAckAsOf : 0; }
  436. /**
  437. * The maximum observed throughput (in bits/s) for this path
  438. */
  439. inline uint64_t maxLifetimeThroughput() { return _maxLifetimeThroughput; }
  440. /**
  441. * @return The mean throughput (in bits/s) of this link
  442. */
  443. inline uint64_t meanThroughput() { return _lastComputedMeanThroughput; }
  444. /**
  445. * Assign a new relative quality value for this path in the aggregate link
  446. *
  447. * @param rq Quality of this path in comparison to other paths available to this peer
  448. */
  449. inline void updateRelativeQuality(float rq) { _lastComputedRelativeQuality = rq; }
  450. /**
  451. * @return Quality of this path compared to others in the aggregate link
  452. */
  453. inline float relativeQuality() { return _lastComputedRelativeQuality; }
  454. /**
  455. * Assign a new allocation value for this path in the aggregate link
  456. *
  457. * @param allocation Percentage of traffic to be sent over this path to a peer
  458. */
  459. inline void updateComponentAllocationOfAggregateLink(unsigned char allocation) { _lastAllocation = allocation; }
  460. /**
  461. * @return Percentage of traffic allocated to this path in the aggregate link
  462. */
  463. inline unsigned char allocation() { return _lastAllocation; }
  464. /**
  465. * @return Stability estimates can become expensive to compute, we cache the most recent result.
  466. */
  467. inline float lastComputedStability() { return _lastComputedStability; }
  468. /**
  469. * @return A pointer to a cached copy of the human-readable name of the interface this Path's localSocket is bound to
  470. */
  471. inline char *getName() { return _ifname; }
  472. /**
  473. * @return Packet delay variance
  474. */
  475. inline float packetDelayVariance() { return _lastComputedPacketDelayVariance; }
  476. /**
  477. * @return Previously-computed mean latency
  478. */
  479. inline float meanLatency() { return _lastComputedMeanLatency; }
  480. /**
  481. * @return Packet loss rate (PLR)
  482. */
  483. inline float packetLossRatio() { return _lastComputedPacketLossRatio; }
  484. /**
  485. * @return Packet error ratio (PER)
  486. */
  487. inline float packetErrorRatio() { return _lastComputedPacketErrorRatio; }
  488. /**
  489. * Record an invalid incoming packet. This packet failed MAC/compression/cipher checks and will now
  490. * contribute to a Packet Error Ratio (PER).
  491. */
  492. inline void recordInvalidPacket() { _packetValiditySamples.push(false); }
  493. /**
  494. * @return A pointer to a cached copy of the address string for this Path (For debugging only)
  495. */
  496. inline char *getAddressString() { return _addrString; }
  497. /**
  498. * @return The current throughput disturbance coefficient
  499. */
  500. inline float throughputDisturbanceCoefficient() { return _lastComputedThroughputDistCoeff; }
  501. /**
  502. * Compute and cache stability and performance metrics. The resultant stability coefficient is a measure of how "well behaved"
  503. * this path is. This figure is substantially different from (but required for the estimation of the path's overall "quality".
  504. *
  505. * @param now Current time
  506. */
  507. inline void processBackgroundPathMeasurements(const int64_t now)
  508. {
  509. if (now - _lastPathQualityComputeTime > ZT_PATH_QUALITY_COMPUTE_INTERVAL) {
  510. Mutex::Lock _l(_statistics_m);
  511. _lastPathQualityComputeTime = now;
  512. address().toString(_addrString);
  513. _lastComputedMeanLatency = _latencySamples.mean();
  514. _lastComputedPacketDelayVariance = _latencySamples.stddev(); // Similar to "jitter" (SEE: RFC 3393, RFC 4689)
  515. _lastComputedMeanThroughput = (uint64_t)_throughputSamples.mean();
  516. // If no packet validity samples, assume PER==0
  517. _lastComputedPacketErrorRatio = 1 - (_packetValiditySamples.count() ? _packetValiditySamples.mean() : 1);
  518. // Compute path stability
  519. // Normalize measurements with wildly different ranges into a reasonable range
  520. float normalized_pdv = Utils::normalize(_lastComputedPacketDelayVariance, 0, ZT_PATH_MAX_PDV, 0, 10);
  521. float normalized_la = Utils::normalize(_lastComputedMeanLatency, 0, ZT_PATH_MAX_MEAN_LATENCY, 0, 10);
  522. float throughput_cv = _throughputSamples.mean() > 0 ? _throughputSamples.stddev() / _throughputSamples.mean() : 1;
  523. // Form an exponential cutoff and apply contribution weights
  524. float pdv_contrib = expf((-1.0f)*normalized_pdv) * (float)ZT_PATH_CONTRIB_PDV;
  525. float latency_contrib = expf((-1.0f)*normalized_la) * (float)ZT_PATH_CONTRIB_LATENCY;
  526. // Throughput Disturbance Coefficient
  527. float throughput_disturbance_contrib = expf((-1.0f)*throughput_cv) * (float)ZT_PATH_CONTRIB_THROUGHPUT_DISTURBANCE;
  528. _throughputDisturbanceSamples.push(throughput_cv);
  529. _lastComputedThroughputDistCoeff = _throughputDisturbanceSamples.mean();
  530. // Obey user-defined ignored contributions
  531. pdv_contrib = ZT_PATH_CONTRIB_PDV > 0.0 ? pdv_contrib : 1;
  532. latency_contrib = ZT_PATH_CONTRIB_LATENCY > 0.0 ? latency_contrib : 1;
  533. throughput_disturbance_contrib = ZT_PATH_CONTRIB_THROUGHPUT_DISTURBANCE > 0.0 ? throughput_disturbance_contrib : 1;
  534. // Stability
  535. _lastComputedStability = pdv_contrib + latency_contrib + throughput_disturbance_contrib;
  536. _lastComputedStability *= 1 - _lastComputedPacketErrorRatio;
  537. // Prevent QoS records from sticking around for too long
  538. std::map<uint64_t,uint64_t>::iterator it = _outQoSRecords.begin();
  539. while (it != _outQoSRecords.end()) {
  540. // Time since egress of tracked packet
  541. if ((now - it->second) >= ZT_PATH_QOS_TIMEOUT) {
  542. _outQoSRecords.erase(it++);
  543. } else { it++; }
  544. }
  545. }
  546. }
  547. /**
  548. * @return True if this path is alive (receiving heartbeats)
  549. */
  550. inline bool alive(const int64_t now) const { return ((now - _lastIn) < (ZT_PATH_HEARTBEAT_PERIOD + 5000)); }
  551. /**
  552. * @return True if this path needs a heartbeat
  553. */
  554. inline bool needsHeartbeat(const int64_t now) const { return ((now - _lastOut) >= ZT_PATH_HEARTBEAT_PERIOD); }
  555. /**
  556. * @return Last time we sent something
  557. */
  558. inline int64_t lastOut() const { return _lastOut; }
  559. /**
  560. * @return Last time we received anything
  561. */
  562. inline int64_t lastIn() const { return _lastIn; }
  563. /**
  564. * @return Time last trust-established packet was received
  565. */
  566. inline int64_t lastTrustEstablishedPacketReceived() const { return _lastTrustEstablishedPacketReceived; }
  567. private:
  568. Mutex _statistics_m;
  569. volatile int64_t _lastOut;
  570. volatile int64_t _lastIn;
  571. volatile int64_t _lastTrustEstablishedPacketReceived;
  572. volatile int64_t _lastPathQualityComputeTime;
  573. int64_t _localSocket;
  574. volatile unsigned int _latency;
  575. InetAddress _addr;
  576. InetAddress::IpScope _ipScope; // memoize this since it's a computed value checked often
  577. AtomicCounter __refCount;
  578. std::map<uint64_t,uint64_t> _outQoSRecords; // id:egress_time
  579. std::map<uint64_t,uint64_t> _inQoSRecords; // id:now
  580. std::map<uint64_t,uint16_t> _inACKRecords; // id:len
  581. int64_t _lastAck;
  582. int64_t _lastThroughputEstimation;
  583. int64_t _lastQoSMeasurement;
  584. int64_t _lastQoSRecordPurge;
  585. int64_t _unackedBytes;
  586. int64_t _expectingAckAsOf;
  587. int16_t _packetsReceivedSinceLastAck;
  588. int16_t _packetsReceivedSinceLastQoS;
  589. uint64_t _maxLifetimeThroughput;
  590. uint64_t _lastComputedMeanThroughput;
  591. uint64_t _bytesAckedSinceLastThroughputEstimation;
  592. float _lastComputedMeanLatency;
  593. float _lastComputedPacketDelayVariance;
  594. float _lastComputedPacketErrorRatio;
  595. float _lastComputedPacketLossRatio;
  596. // cached estimates
  597. float _lastComputedStability;
  598. float _lastComputedRelativeQuality;
  599. float _lastComputedThroughputDistCoeff;
  600. unsigned char _lastAllocation;
  601. // cached human-readable strings for tracing purposes
  602. char _ifname[16];
  603. char _addrString[256];
  604. RingBuffer<uint64_t,ZT_PATH_QUALITY_METRIC_WIN_SZ> _throughputSamples;
  605. RingBuffer<uint32_t,ZT_PATH_QUALITY_METRIC_WIN_SZ> _latencySamples;
  606. RingBuffer<bool,ZT_PATH_QUALITY_METRIC_WIN_SZ> _packetValiditySamples;
  607. RingBuffer<float,ZT_PATH_QUALITY_METRIC_WIN_SZ> _throughputDisturbanceSamples;
  608. };
  609. } // namespace ZeroTier
  610. #endif