Path.hpp 23 KB

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