Bond.hpp 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606
  1. /*
  2. * Copyright (c)2013-2021 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: 2026-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_BOND_HPP
  14. #define ZT_BOND_HPP
  15. #include "../osdep/Phy.hpp"
  16. #include "Packet.hpp"
  17. #include "Path.hpp"
  18. #include "RuntimeEnvironment.hpp"
  19. #include "Trace.hpp"
  20. #include <cstdarg>
  21. #include <deque>
  22. #include <list>
  23. #include <map>
  24. /**
  25. * Indices for the path quality weight vector
  26. */
  27. enum ZT_BondQualityWeightIndex { ZT_QOS_LAT_IDX, ZT_QOS_LTM_IDX, ZT_QOS_PDV_IDX, ZT_QOS_PLR_IDX, ZT_QOS_PER_IDX, ZT_QOS_THR_IDX, ZT_QOS_THM_IDX, ZT_QOS_THV_IDX, ZT_QOS_AGE_IDX, ZT_QOS_SCP_IDX, ZT_QOS_WEIGHT_SIZE };
  28. /**
  29. * Multipath bonding policy
  30. */
  31. enum ZT_BondBondingPolicy {
  32. /**
  33. * Normal operation. No fault tolerance, no load balancing
  34. */
  35. ZT_BOND_POLICY_NONE = 0,
  36. /**
  37. * Sends traffic out on only one path at a time. Configurable immediate
  38. * fail-over.
  39. */
  40. ZT_BOND_POLICY_ACTIVE_BACKUP = 1,
  41. /**
  42. * Sends traffic out on all paths
  43. */
  44. ZT_BOND_POLICY_BROADCAST = 2,
  45. /**
  46. * Stripes packets across all paths
  47. */
  48. ZT_BOND_POLICY_BALANCE_RR = 3,
  49. /**
  50. * Packets destined for specific peers will always be sent over the same
  51. * path.
  52. */
  53. ZT_BOND_POLICY_BALANCE_XOR = 4,
  54. /**
  55. * Balances flows among all paths according to path performance
  56. */
  57. ZT_BOND_POLICY_BALANCE_AWARE = 5
  58. };
  59. /**
  60. * Multipath active re-selection policy (linkSelectMethod)
  61. */
  62. enum ZT_BondLinkSelectMethod {
  63. /**
  64. * Primary link regains status as active link whenever it comes back up
  65. * (default when links are explicitly specified)
  66. */
  67. ZT_BOND_RESELECTION_POLICY_ALWAYS = 0,
  68. /**
  69. * Primary link regains status as active link when it comes back up and
  70. * (if) it is better than the currently-active link.
  71. */
  72. ZT_BOND_RESELECTION_POLICY_BETTER = 1,
  73. /**
  74. * Primary link regains status as active link only if the currently-active
  75. * link fails.
  76. */
  77. ZT_BOND_RESELECTION_POLICY_FAILURE = 2,
  78. /**
  79. * The primary link can change if a superior path is detected.
  80. * (default if user provides no fail-over guidance)
  81. */
  82. ZT_BOND_RESELECTION_POLICY_OPTIMIZE = 3
  83. };
  84. /**
  85. * Mode of multipath link interface
  86. */
  87. enum ZT_BondLinkMode { ZT_BOND_SLAVE_MODE_PRIMARY = 0, ZT_BOND_SLAVE_MODE_SPARE = 1 };
  88. #include "../node/AtomicCounter.hpp"
  89. #include "../node/SharedPtr.hpp"
  90. #include <string>
  91. namespace ZeroTier {
  92. class Link {
  93. friend class SharedPtr<Link>;
  94. public:
  95. /**
  96. *
  97. * @param ifnameStr
  98. * @param ipvPref
  99. * @param speed
  100. * @param enabled
  101. * @param mode
  102. * @param failoverToLinkStr
  103. * @param userSpecifiedAlloc
  104. */
  105. Link(std::string ifnameStr, uint8_t ipvPref, uint32_t speed, bool enabled, uint8_t mode, std::string failoverToLinkStr, float userSpecifiedAlloc)
  106. : _ifnameStr(ifnameStr)
  107. , _ipvPref(ipvPref)
  108. , _speed(speed)
  109. , _relativeSpeed(0)
  110. , _enabled(enabled)
  111. , _mode(mode)
  112. , _failoverToLinkStr(failoverToLinkStr)
  113. , _userSpecifiedAlloc(userSpecifiedAlloc)
  114. , _isUserSpecified(false)
  115. {
  116. }
  117. /**
  118. * @return The string representation of this link's underlying interface's system name.
  119. */
  120. inline std::string ifname()
  121. {
  122. return _ifnameStr;
  123. }
  124. /**
  125. * @return Whether this link is designated as a primary.
  126. */
  127. inline bool primary()
  128. {
  129. return _mode == ZT_BOND_SLAVE_MODE_PRIMARY;
  130. }
  131. /**
  132. * @return Whether this link is designated as a spare.
  133. */
  134. inline bool spare()
  135. {
  136. return _mode == ZT_BOND_SLAVE_MODE_SPARE;
  137. }
  138. /**
  139. * @return The name of the link interface that should be used in the event of a failure.
  140. */
  141. inline std::string failoverToLink()
  142. {
  143. return _failoverToLinkStr;
  144. }
  145. /**
  146. * @return Whether this link interface was specified by the user or auto-detected.
  147. */
  148. inline bool isUserSpecified()
  149. {
  150. return _isUserSpecified;
  151. }
  152. /**
  153. * Signify that this link was specified by the user and not the result of auto-detection.
  154. *
  155. * @param isUserSpecified
  156. */
  157. inline void setAsUserSpecified(bool isUserSpecified)
  158. {
  159. _isUserSpecified = isUserSpecified;
  160. }
  161. /**
  162. * @return Whether or not the user has specified failover instructions.
  163. */
  164. inline bool userHasSpecifiedFailoverInstructions()
  165. {
  166. return _failoverToLinkStr.length();
  167. }
  168. /**
  169. * @return The speed of the link relative to others in the bond.
  170. */
  171. inline uint8_t relativeSpeed()
  172. {
  173. return _relativeSpeed;
  174. }
  175. /**
  176. * Sets the speed of the link relative to others in the bond.
  177. *
  178. * @param relativeSpeed The speed relative to the rest of the link.
  179. */
  180. inline void setRelativeSpeed(uint8_t relativeSpeed)
  181. {
  182. _relativeSpeed = relativeSpeed;
  183. }
  184. /**
  185. * @return The absolute speed of the link (as specified by the user.)
  186. */
  187. inline uint32_t speed()
  188. {
  189. return _speed;
  190. }
  191. /**
  192. * @return The address preference for this link (as specified by the user.)
  193. */
  194. inline uint8_t ipvPref()
  195. {
  196. return _ipvPref;
  197. }
  198. /**
  199. * @return The mode (e.g. primary/spare) for this link (as specified by the user.)
  200. */
  201. inline uint8_t mode()
  202. {
  203. return _mode;
  204. }
  205. /**
  206. * @return Whether this link is enabled or disabled
  207. */
  208. inline uint8_t enabled()
  209. {
  210. return _enabled;
  211. }
  212. private:
  213. /**
  214. * String representation of underlying interface's system name
  215. */
  216. std::string _ifnameStr;
  217. /**
  218. * What preference (if any) a user has for IP protocol version used in
  219. * path aggregations. Preference is expressed in the order of the digits:
  220. *
  221. * 0: no preference
  222. * 4: IPv4 only
  223. * 6: IPv6 only
  224. * 46: IPv4 over IPv6
  225. * 64: IPv6 over IPv4
  226. */
  227. uint8_t _ipvPref;
  228. /**
  229. * User-specified speed of this link
  230. */
  231. uint32_t _speed;
  232. /**
  233. * Speed relative to other specified links (computed by Bond)
  234. */
  235. uint8_t _relativeSpeed;
  236. /**
  237. * Whether this link is enabled, or (disabled (possibly bad config))
  238. */
  239. uint8_t _enabled;
  240. /**
  241. * Whether this link is designated as a primary, a spare, or no preference.
  242. */
  243. uint8_t _mode;
  244. /**
  245. * The specific name of the link to be used in the event that this
  246. * link fails.
  247. */
  248. std::string _failoverToLinkStr;
  249. /**
  250. * User-specified allocation
  251. */
  252. float _userSpecifiedAlloc;
  253. /**
  254. * Whether or not this link was created as a result of manual user specification. This is
  255. * important to know because certain policy decisions are dependent on whether the user
  256. * intents to use a specific set of interfaces.
  257. */
  258. bool _isUserSpecified;
  259. AtomicCounter __refCount;
  260. };
  261. class Link;
  262. class Peer;
  263. class Bond {
  264. public:
  265. /**
  266. * @return Whether this link is permitted to become a member of a bond.
  267. */
  268. static bool linkAllowed(std::string& policyAlias, SharedPtr<Link> link);
  269. /**
  270. * @return The minimum interval required to poll the active bonds to fulfill all active monitoring timing requirements.
  271. */
  272. static int minReqMonitorInterval()
  273. {
  274. return _minReqMonitorInterval;
  275. }
  276. /**
  277. * @return Whether the bonding layer is currently set up to be used.
  278. */
  279. static bool inUse()
  280. {
  281. return ! _bondPolicyTemplates.empty() || _defaultPolicy;
  282. }
  283. /**
  284. * @param basePolicyName Bonding policy name (See ZeroTierOne.h)
  285. * @return The bonding policy code for a given human-readable bonding policy name
  286. */
  287. static int getPolicyCodeByStr(const std::string& basePolicyName)
  288. {
  289. if (basePolicyName == "active-backup") {
  290. return 1;
  291. }
  292. if (basePolicyName == "broadcast") {
  293. return 2;
  294. }
  295. if (basePolicyName == "balance-rr") {
  296. return 3;
  297. }
  298. if (basePolicyName == "balance-xor") {
  299. return 4;
  300. }
  301. if (basePolicyName == "balance-aware") {
  302. return 5;
  303. }
  304. return 0; // "none"
  305. }
  306. /**
  307. * @param policy Bonding policy code (See ZeroTierOne.h)
  308. * @return The human-readable name for the given bonding policy code
  309. */
  310. static std::string getPolicyStrByCode(int policy)
  311. {
  312. if (policy == 1) {
  313. return "active-backup";
  314. }
  315. if (policy == 2) {
  316. return "broadcast";
  317. }
  318. if (policy == 3) {
  319. return "balance-rr";
  320. }
  321. if (policy == 4) {
  322. return "balance-xor";
  323. }
  324. if (policy == 5) {
  325. return "balance-aware";
  326. }
  327. return "none";
  328. }
  329. /**
  330. * Sets the default bonding policy for new or undefined bonds.
  331. *
  332. * @param bp Bonding policy
  333. */
  334. static void setBondingLayerDefaultPolicy(uint8_t bp)
  335. {
  336. _defaultPolicy = bp;
  337. }
  338. /**
  339. * Sets the default (custom) bonding policy for new or undefined bonds.
  340. *
  341. * @param alias Human-readable string alias for bonding policy
  342. */
  343. static void setBondingLayerDefaultPolicyStr(std::string alias)
  344. {
  345. _defaultPolicyStr = alias;
  346. }
  347. /**
  348. * Add a user-defined link to a given bonding policy.
  349. *
  350. * @param policyAlias User-defined custom name for variant of bonding policy
  351. * @param link Pointer to new link definition
  352. */
  353. static void addCustomLink(std::string& policyAlias, SharedPtr<Link> link);
  354. /**
  355. * Add a user-defined bonding policy that is based on one of the standard types.
  356. *
  357. * @param newBond Pointer to custom Bond object
  358. * @return Whether a uniquely-named custom policy was successfully added
  359. */
  360. static bool addCustomPolicy(const SharedPtr<Bond>& newBond);
  361. /**
  362. * Assigns a specific bonding policy
  363. *
  364. * @param identity
  365. * @param policyAlias
  366. * @return
  367. */
  368. static bool assignBondingPolicyToPeer(int64_t identity, const std::string& policyAlias);
  369. /**
  370. * Get pointer to bond by a given peer ID
  371. *
  372. * @param peer Remote peer ID
  373. * @return A pointer to the Bond
  374. */
  375. static SharedPtr<Bond> getBondByPeerId(int64_t identity);
  376. /**
  377. * Add a new bond to the bond controller.
  378. *
  379. * @param renv Runtime environment
  380. * @param peer Remote peer that this bond services
  381. * @return A pointer to the newly created Bond
  382. */
  383. static SharedPtr<Bond> createBond(const RuntimeEnvironment* renv, const SharedPtr<Peer>& peer);
  384. /**
  385. * Remove a bond from the bond controller.
  386. *
  387. * @param peerId Remote peer that this bond services
  388. */
  389. static void destroyBond(uint64_t peerId);
  390. /**
  391. * Periodically perform maintenance tasks for the bonding layer.
  392. *
  393. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  394. * @param now Current time
  395. */
  396. static void processBackgroundTasks(void* tPtr, int64_t now);
  397. /**
  398. * Gets a reference to a physical link definition given a policy alias and a local socket.
  399. *
  400. * @param policyAlias Policy in use
  401. * @param localSocket Local source socket
  402. * @param createIfNeeded Whether a Link object is created if the name wasn't previously in the link map
  403. * @return Physical link definition
  404. */
  405. static SharedPtr<Link> getLinkBySocket(const std::string& policyAlias, uint64_t localSocket, bool createIfNeeded);
  406. /**
  407. * Gets a reference to a physical link definition given its human-readable system name.
  408. *
  409. * @param policyAlias Policy in use
  410. * @param ifname Alphanumeric human-readable name
  411. * @return Physical link definition
  412. */
  413. static SharedPtr<Link> getLinkByName(const std::string& policyAlias, const std::string& ifname);
  414. private:
  415. static Phy<Bond*>* _phy;
  416. static Mutex _bonds_m;
  417. static Mutex _links_m;
  418. /**
  419. * The minimum required monitoring interval among all bonds
  420. */
  421. static int _minReqMonitorInterval;
  422. /**
  423. * The default bonding policy used for new bonds unless otherwise specified.
  424. */
  425. static uint8_t _defaultPolicy;
  426. /**
  427. * The default bonding policy used for new bonds unless otherwise specified.
  428. */
  429. static std::string _defaultPolicyStr;
  430. /**
  431. * All currently active bonds.
  432. */
  433. static std::map<int64_t, SharedPtr<Bond> > _bonds;
  434. /**
  435. * Map of peers to custom bonding policies
  436. */
  437. static std::map<int64_t, std::string> _policyTemplateAssignments;
  438. /**
  439. * User-defined bonding policies (can be assigned to a peer)
  440. */
  441. static std::map<std::string, SharedPtr<Bond> > _bondPolicyTemplates;
  442. /**
  443. * Set of links defined for a given bonding policy
  444. */
  445. static std::map<std::string, std::vector<SharedPtr<Link> > > _linkDefinitions;
  446. /**
  447. * Set of link objects mapped to their physical interfaces
  448. */
  449. static std::map<std::string, std::map<std::string, SharedPtr<Link> > > _interfaceToLinkMap;
  450. struct NominatedPath;
  451. struct Flow;
  452. friend class SharedPtr<Bond>;
  453. friend class Peer;
  454. public:
  455. void dumpInfo(int64_t now, bool force);
  456. std::string pathToStr(const SharedPtr<Path>& path);
  457. void dumpPathStatus(int64_t now, int pathIdx);
  458. SharedPtr<Link> getLink(const SharedPtr<Path>& path);
  459. /**
  460. * Constructor
  461. *
  462. *
  463. */
  464. Bond(const RuntimeEnvironment* renv);
  465. /**
  466. * Constructor. Creates a bond based off of ZT defaults
  467. *
  468. * @param renv Runtime environment
  469. * @param policy Bonding policy
  470. * @param peer
  471. */
  472. Bond(const RuntimeEnvironment* renv, int policy, const SharedPtr<Peer>& peer);
  473. /**
  474. * Constructor. For use when user intends to manually specify parameters
  475. *
  476. * @param basePolicy
  477. * @param policyAlias
  478. * @param peer
  479. */
  480. Bond(const RuntimeEnvironment* renv, std::string& basePolicy, std::string& policyAlias, const SharedPtr<Peer>& peer);
  481. /**
  482. * Constructor. Creates a bond based off of a user-defined bond template
  483. *
  484. * @param renv Runtime environment
  485. * @param original
  486. * @param peer
  487. */
  488. Bond(const RuntimeEnvironment* renv, SharedPtr<Bond> originalBond, const SharedPtr<Peer>& peer);
  489. /**
  490. * @return The human-readable name of the bonding policy
  491. */
  492. std::string policyAlias()
  493. {
  494. return _policyAlias;
  495. }
  496. /**
  497. * Inform the bond about the path that its peer (owning object) just learned about.
  498. * If the path is allowed to be used, it will be inducted into the bond on a trial
  499. * period where link statistics will be collected to judge its quality.
  500. *
  501. * @param path Newly-learned Path which should now be handled by the Bond
  502. * @param now Current time
  503. */
  504. void nominatePathToBond(const SharedPtr<Path>& path, int64_t now);
  505. /**
  506. * Add a nominated path to the bond. This merely maps the index from the nominated set
  507. * to a smaller set and sets the path's bonded flag to true.
  508. *
  509. * @param nominatedIdx The index in the nominated set
  510. * @param bondedIdx The index in the bonded set (subset of nominated)
  511. */
  512. void addPathToBond(int nominatedIdx, int bondedIdx);
  513. /**
  514. * Check path states and perform bond rebuilds if needed.
  515. *
  516. * @param now Current time
  517. * @param rebuild Whether or not the bond should be reconstructed.
  518. */
  519. void curateBond(int64_t now, bool rebuild);
  520. /**
  521. * Periodically perform statistical summaries of quality metrics for all paths.
  522. *
  523. * @param now Current time
  524. */
  525. void estimatePathQuality(int64_t now);
  526. /**
  527. * Record an invalid incoming packet. This packet failed
  528. * MAC/compression/cipher checks and will now contribute to a
  529. * Packet Error Ratio (PER).
  530. *
  531. * @param path Path over which packet was received
  532. */
  533. void recordIncomingInvalidPacket(const SharedPtr<Path>& path);
  534. /**
  535. * Record statistics on outbound an packet.
  536. *
  537. * @param path Path over which packet is being sent
  538. * @param packetId Packet ID
  539. * @param payloadLength Packet data length
  540. * @param verb Packet verb
  541. * @param flowId Flow ID
  542. * @param now Current time
  543. */
  544. void recordOutgoingPacket(const SharedPtr<Path>& path, uint64_t packetId, uint16_t payloadLength, Packet::Verb verb, int32_t flowId, int64_t now);
  545. /**
  546. * Process the contents of an inbound VERB_QOS_MEASUREMENT to gather path quality observations.
  547. *
  548. * @param now Current time
  549. * @param count Number of records
  550. * @param rx_id table of packet IDs
  551. * @param rx_ts table of holding times
  552. */
  553. void receivedQoS(const SharedPtr<Path>& path, int64_t now, int count, uint64_t* rx_id, uint16_t* rx_ts);
  554. /**
  555. * Process the contents of an inbound VERB_ACK to gather path quality observations.
  556. *
  557. * @param pathIdx Path over which packet was received
  558. * @param now Current time
  559. * @param ackedBytes Number of bytes ACKed by this VERB_ACK
  560. */
  561. void receivedAck(int pathIdx, int64_t now, int32_t ackedBytes);
  562. /**
  563. * Generate the contents of a VERB_QOS_MEASUREMENT packet.
  564. *
  565. * @param now Current time
  566. * @param qosBuffer destination buffer
  567. * @return Size of payload
  568. */
  569. int32_t generateQoSPacket(int pathIdx, int64_t now, char* qosBuffer);
  570. /**
  571. * Record statistics for an inbound packet.
  572. *
  573. * @param path Path over which packet was received
  574. * @param packetId Packet ID
  575. * @param payloadLength Packet data length
  576. * @param verb Packet verb
  577. * @param flowId Flow ID
  578. * @param now Current time
  579. */
  580. void recordIncomingPacket(const SharedPtr<Path>& path, uint64_t packetId, uint16_t payloadLength, Packet::Verb verb, int32_t flowId, int64_t now);
  581. /**
  582. * Determines the most appropriate path for packet and flow egress. This decision is made by
  583. * the underlying bonding policy as well as QoS-related statistical observations of path quality.
  584. *
  585. * @param now Current time
  586. * @param flowId Flow ID
  587. * @return Pointer to suggested Path
  588. */
  589. SharedPtr<Path> getAppropriatePath(int64_t now, int32_t flowId);
  590. /**
  591. * Creates a new flow record
  592. *
  593. * @param np Path over which flow shall be handled
  594. * @param flowId Flow ID
  595. * @param entropy A byte of entropy to be used by the bonding algorithm
  596. * @param now Current time
  597. * @return Pointer to newly-created Flow
  598. */
  599. SharedPtr<Flow> createFlow(int pathIdx, int32_t flowId, unsigned char entropy, int64_t now);
  600. /**
  601. * Removes flow records that are past a certain age limit.
  602. *
  603. * @param age Age threshold to be forgotten
  604. * @param oldest Whether only the oldest shall be forgotten
  605. * @param now Current time
  606. */
  607. void forgetFlowsWhenNecessary(uint64_t age, bool oldest, int64_t now);
  608. /**
  609. * Assigns a new flow to a bonded path
  610. *
  611. * @param flow Flow to be assigned
  612. * @param now Current time
  613. */
  614. bool assignFlowToBondedPath(SharedPtr<Flow>& flow, int64_t now);
  615. /**
  616. * Determine whether a path change should occur given the remote peer's reported utility and our
  617. * local peer's known utility. This has the effect of assigning inbound and outbound traffic to
  618. * the same path.
  619. *
  620. * @param now Current time
  621. * @param path Path over which the negotiation request was received
  622. * @param remoteUtility How much utility the remote peer claims to gain by using the declared path
  623. */
  624. void processIncomingPathNegotiationRequest(uint64_t now, SharedPtr<Path>& path, int16_t remoteUtility);
  625. /**
  626. * Determine state of path synchronization and whether a negotiation request
  627. * shall be sent to the peer.
  628. *
  629. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  630. * @param now Current time
  631. */
  632. void pathNegotiationCheck(void* tPtr, int64_t now);
  633. /**
  634. * Sends a VERB_ACK to the remote peer.
  635. *
  636. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  637. * @param path Path over which packet should be sent
  638. * @param localSocket Local source socket
  639. * @param atAddress
  640. * @param now Current time
  641. */
  642. void sendACK(void* tPtr, int pathIdx, int64_t localSocket, const InetAddress& atAddress, int64_t now);
  643. /**
  644. * Sends a VERB_QOS_MEASUREMENT to the remote peer.
  645. *
  646. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  647. * @param path Path over which packet should be sent
  648. * @param localSocket Local source socket
  649. * @param atAddress
  650. * @param now Current time
  651. */
  652. void sendQOS_MEASUREMENT(void* tPtr, int pathIdx, int64_t localSocket, const InetAddress& atAddress, int64_t now);
  653. /**
  654. * Sends a VERB_PATH_NEGOTIATION_REQUEST to the remote peer.
  655. *
  656. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  657. * @param path Path over which packet should be sent
  658. */
  659. void sendPATH_NEGOTIATION_REQUEST(void* tPtr, int pathIdx);
  660. /**
  661. *
  662. * @param now Current time
  663. */
  664. void processBalanceTasks(int64_t now);
  665. /**
  666. * Perform periodic tasks unique to active-backup
  667. *
  668. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  669. * @param now Current time
  670. */
  671. void processActiveBackupTasks(void* tPtr, int64_t now);
  672. /**
  673. * Switches the active link in an active-backup scenario to the next best during
  674. * a failover event.
  675. *
  676. * @param now Current time
  677. */
  678. void dequeueNextActiveBackupPath(uint64_t now);
  679. /**
  680. * Zero all timers
  681. */
  682. void initTimers();
  683. /**
  684. * Set bond parameters to reasonable defaults, these may later be overwritten by
  685. * user-specified parameters.
  686. *
  687. * @param policy Bonding policy
  688. * @param templateBond
  689. */
  690. void setBondParameters(int policy, SharedPtr<Bond> templateBond, bool useTemplate);
  691. /**
  692. * Check and assign user-specified quality weights to this bond.
  693. *
  694. * @param weights Set of user-specified weights
  695. * @param len Length of weight vector
  696. */
  697. void setUserQualityWeights(float weights[], int len);
  698. /**
  699. * @param latencyInMilliseconds Maximum acceptable latency.
  700. */
  701. void setMaxAcceptableLatency(int16_t latencyInMilliseconds)
  702. {
  703. _maxAcceptableLatency = latencyInMilliseconds;
  704. }
  705. /**
  706. * @param latencyInMilliseconds Maximum acceptable (mean) latency.
  707. */
  708. void setMaxAcceptableMeanLatency(int16_t latencyInMilliseconds)
  709. {
  710. _maxAcceptableMeanLatency = latencyInMilliseconds;
  711. }
  712. /**
  713. * @param latencyVarianceInMilliseconds Maximum acceptable packet delay variance (jitter).
  714. */
  715. void setMaxAcceptablePacketDelayVariance(int16_t latencyVarianceInMilliseconds)
  716. {
  717. _maxAcceptablePacketDelayVariance = latencyVarianceInMilliseconds;
  718. }
  719. /**
  720. * @param lossRatio Maximum acceptable packet loss ratio (PLR).
  721. */
  722. void setMaxAcceptablePacketLossRatio(float lossRatio)
  723. {
  724. _maxAcceptablePacketLossRatio = lossRatio;
  725. }
  726. /**
  727. * @param errorRatio Maximum acceptable packet error ratio (PER).
  728. */
  729. void setMaxAcceptablePacketErrorRatio(float errorRatio)
  730. {
  731. _maxAcceptablePacketErrorRatio = errorRatio;
  732. }
  733. /**
  734. * @param errorRatio Maximum acceptable packet error ratio (PER).
  735. */
  736. void setMinAcceptableAllocation(float minAlloc)
  737. {
  738. _minAcceptableAllocation = (uint8_t)(minAlloc * 255);
  739. }
  740. /**
  741. * @return Whether the user has defined links for use on this bond
  742. */
  743. inline bool userHasSpecifiedLinks()
  744. {
  745. return _userHasSpecifiedLinks;
  746. }
  747. /**
  748. * @return Whether the user has defined a set of failover link(s) for this bond
  749. */
  750. inline bool userHasSpecifiedFailoverInstructions()
  751. {
  752. return _userHasSpecifiedFailoverInstructions;
  753. };
  754. /**
  755. * @return Whether the user has specified a primary link
  756. */
  757. inline bool userHasSpecifiedPrimaryLink()
  758. {
  759. return _userHasSpecifiedPrimaryLink;
  760. }
  761. /**
  762. * @return Whether the user has specified link speeds
  763. */
  764. inline bool userHasSpecifiedLinkSpeeds()
  765. {
  766. return _userHasSpecifiedLinkSpeeds;
  767. }
  768. /**
  769. * Periodically perform maintenance tasks for each active bond.
  770. *
  771. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  772. * @param now Current time
  773. */
  774. void processBackgroundBondTasks(void* tPtr, int64_t now);
  775. /**
  776. * Rate limit gate for VERB_ACK
  777. *
  778. * @param now Current time
  779. * @return Whether the incoming packet should be rate-gated
  780. */
  781. inline bool rateGateACK(const int64_t now)
  782. {
  783. _ackCutoffCount++;
  784. int numToDrain = _lastAckRateCheck ? (now - _lastAckRateCheck) / ZT_ACK_DRAINAGE_DIVISOR : _ackCutoffCount;
  785. _lastAckRateCheck = now;
  786. if (_ackCutoffCount > numToDrain) {
  787. _ackCutoffCount -= numToDrain;
  788. }
  789. else {
  790. _ackCutoffCount = 0;
  791. }
  792. return (_ackCutoffCount < ZT_ACK_CUTOFF_LIMIT);
  793. }
  794. /**
  795. * Rate limit gate for VERB_QOS_MEASUREMENT
  796. *
  797. * @param now Current time
  798. * @return Whether the incoming packet should be rate-gated
  799. */
  800. inline bool rateGateQoS(int64_t now, SharedPtr<Path>& path)
  801. {
  802. // TODO: Verify before production
  803. char pathStr[64] = { 0 };
  804. path->address().toString(pathStr);
  805. int diff = now - _lastQoSRateCheck;
  806. if ((diff) <= (_qosSendInterval / ZT_MAX_PEER_NETWORK_PATHS)) {
  807. ++_qosCutoffCount;
  808. }
  809. else {
  810. _qosCutoffCount = 0;
  811. }
  812. _lastQoSRateCheck = now;
  813. // fprintf(stderr, "rateGateQoS (count=%d, send_interval=%d, diff=%d, path=%s)\n", _qosCutoffCount, _qosSendInterval, diff, pathStr);
  814. return (_qosCutoffCount < (ZT_MAX_PEER_NETWORK_PATHS * 2));
  815. }
  816. /**
  817. * Rate limit gate for VERB_PATH_NEGOTIATION_REQUEST
  818. *
  819. * @param now Current time
  820. * @return Whether the incoming packet should be rate-gated
  821. */
  822. inline bool rateGatePathNegotiation(int64_t now, SharedPtr<Path>& path)
  823. {
  824. // TODO: Verify before production
  825. char pathStr[64] = { 0 };
  826. path->address().toString(pathStr);
  827. int diff = now - _lastPathNegotiationReceived;
  828. if ((diff) <= (ZT_PATH_NEGOTIATION_CUTOFF_TIME / ZT_MAX_PEER_NETWORK_PATHS)) {
  829. ++_pathNegotiationCutoffCount;
  830. }
  831. else {
  832. _pathNegotiationCutoffCount = 0;
  833. }
  834. _lastPathNegotiationReceived = now;
  835. // fprintf(stderr, "rateGateNeg (count=%d, send_interval=%d, diff=%d, path=%s)\n", _pathNegotiationCutoffCount, (ZT_PATH_NEGOTIATION_CUTOFF_TIME / ZT_MAX_PEER_NETWORK_PATHS), diff, pathStr);
  836. return (_pathNegotiationCutoffCount < (ZT_MAX_PEER_NETWORK_PATHS * 2));
  837. }
  838. /**
  839. * @param interval Maximum amount of time user expects a failover to take on this bond.
  840. */
  841. inline void setFailoverInterval(uint32_t interval)
  842. {
  843. _failoverInterval = interval;
  844. }
  845. /**
  846. * @param interval Maximum amount of time user expects a failover to take on this bond.
  847. */
  848. inline uint32_t getFailoverInterval()
  849. {
  850. return _failoverInterval;
  851. }
  852. /**
  853. * @param strategy Strategy that the bond uses to re-assign protocol flows.
  854. */
  855. inline void setFlowRebalanceStrategy(uint32_t strategy)
  856. {
  857. _flowRebalanceStrategy = strategy;
  858. }
  859. /**
  860. * @param strategy Strategy that the bond uses to prob for path aliveness and quality
  861. */
  862. inline void setLinkMonitorStrategy(uint8_t strategy)
  863. {
  864. _linkMonitorStrategy = strategy;
  865. }
  866. /**
  867. * @return the current up delay parameter
  868. */
  869. inline uint16_t getUpDelay()
  870. {
  871. return _upDelay;
  872. }
  873. /**
  874. * @param upDelay Length of time before a newly-discovered path is admitted to the bond
  875. */
  876. inline void setUpDelay(int upDelay)
  877. {
  878. if (upDelay >= 0) {
  879. _upDelay = upDelay;
  880. }
  881. }
  882. /**
  883. * @return Length of time before a newly-failed path is removed from the bond
  884. */
  885. inline uint16_t getDownDelay()
  886. {
  887. return _downDelay;
  888. }
  889. /**
  890. * @param downDelay Length of time before a newly-failed path is removed from the bond
  891. */
  892. inline void setDownDelay(int downDelay)
  893. {
  894. if (downDelay >= 0) {
  895. _downDelay = downDelay;
  896. }
  897. }
  898. /**
  899. * @return The current monitoring interval for the bond
  900. */
  901. inline int monitorInterval()
  902. {
  903. return _monitorInterval;
  904. }
  905. /**
  906. * Set the current monitoring interval for the bond (can be overridden with intervals specific to certain links.)
  907. *
  908. * @param monitorInterval How often gratuitous VERB_HELLO(s) are sent to remote peer.
  909. */
  910. inline void setBondMonitorInterval(uint16_t interval)
  911. {
  912. _monitorInterval = interval;
  913. }
  914. /**
  915. * @param policy Bonding policy for this bond
  916. */
  917. inline void setPolicy(uint8_t policy)
  918. {
  919. _policy = policy;
  920. }
  921. /**
  922. * @return the current bonding policy
  923. */
  924. inline uint8_t policy()
  925. {
  926. return _policy;
  927. }
  928. /**
  929. * @return the number of links comprising this bond which are considered alive
  930. */
  931. inline uint8_t getNumAliveLinks()
  932. {
  933. return _numAliveLinks;
  934. };
  935. /**
  936. * @return the number of links comprising this bond
  937. */
  938. inline uint8_t getNumTotalLinks()
  939. {
  940. return _numTotalLinks;
  941. }
  942. /**
  943. *
  944. * @param allowFlowHashing
  945. */
  946. inline void setFlowHashing(bool allowFlowHashing)
  947. {
  948. _allowFlowHashing = allowFlowHashing;
  949. }
  950. /**
  951. * @return Whether flow-hashing is currently enabled for this bond.
  952. */
  953. bool flowHashingEnabled()
  954. {
  955. return _allowFlowHashing;
  956. }
  957. /**
  958. *
  959. * @param packetsPerLink
  960. */
  961. inline void setPacketsPerLink(int packetsPerLink)
  962. {
  963. _packetsPerLink = packetsPerLink;
  964. }
  965. /**
  966. * @return Number of packets to be sent on each interface in a balance-rr bond
  967. */
  968. inline int getPacketsPerLink()
  969. {
  970. return _packetsPerLink;
  971. }
  972. /**
  973. *
  974. * @param linkSelectMethod
  975. */
  976. inline void setLinkSelectMethod(uint8_t method)
  977. {
  978. _abLinkSelectMethod = method;
  979. }
  980. /**
  981. *
  982. * @return
  983. */
  984. inline uint8_t getLinkSelectMethod()
  985. {
  986. return _abLinkSelectMethod;
  987. }
  988. /**
  989. *
  990. * @param allowPathNegotiation
  991. */
  992. inline void setAllowPathNegotiation(bool allowPathNegotiation)
  993. {
  994. _allowPathNegotiation = allowPathNegotiation;
  995. }
  996. /**
  997. *
  998. * @return
  999. */
  1000. inline bool allowPathNegotiation()
  1001. {
  1002. return _allowPathNegotiation;
  1003. }
  1004. /**
  1005. * Forcibly rotates the currently active link used in an active-backup bond to the next link in the failover queue
  1006. *
  1007. * @return True if this operation succeeded, false if otherwise
  1008. */
  1009. bool abForciblyRotateLink();
  1010. /**
  1011. * @param now Current time
  1012. * @return All known paths to this peer
  1013. */
  1014. inline std::vector<SharedPtr<Path> > paths(const int64_t now) const
  1015. {
  1016. std::vector<SharedPtr<Path> > pp;
  1017. Mutex::Lock _l(_paths_m);
  1018. for (unsigned int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1019. if (! _paths[i].p)
  1020. break;
  1021. pp.push_back(_paths[i].p);
  1022. }
  1023. return pp;
  1024. }
  1025. /**
  1026. * Emit message to tracing system but with added timestamp and subsystem info
  1027. *
  1028. */
  1029. void log(const char* fmt, ...)
  1030. #ifdef __GNUC__
  1031. __attribute__((format(printf, 2, 3)))
  1032. #endif
  1033. {
  1034. #ifdef ZT_TRACE
  1035. time_t rawtime;
  1036. struct tm* timeinfo;
  1037. char timestamp[80];
  1038. time(&rawtime);
  1039. timeinfo = localtime(&rawtime);
  1040. strftime(timestamp, 80, "%F %T", timeinfo);
  1041. #define MAX_BOND_MSG_LEN 1024
  1042. char traceMsg[MAX_BOND_MSG_LEN];
  1043. char userMsg[MAX_BOND_MSG_LEN];
  1044. va_list args;
  1045. va_start(args, fmt);
  1046. if (vsnprintf(userMsg, sizeof(userMsg), fmt, args) < 0) {
  1047. fprintf(stderr, "Encountered format encoding error while writing to trace log\n");
  1048. return;
  1049. }
  1050. snprintf(traceMsg, MAX_BOND_MSG_LEN, "%s (%llx/%s) %s", timestamp, _peerId, _policyAlias.c_str(), userMsg);
  1051. va_end(args);
  1052. RR->t->bondStateMessage(NULL, traceMsg);
  1053. #undef MAX_MSG_LEN
  1054. #endif
  1055. }
  1056. /**
  1057. * Emit message to tracing system but with added timestamp and subsystem info
  1058. *
  1059. */
  1060. void debug(const char* fmt, ...)
  1061. #ifdef __GNUC__
  1062. __attribute__((format(printf, 2, 3)))
  1063. #endif
  1064. {
  1065. #ifdef ZT_DEBUG
  1066. time_t rawtime;
  1067. struct tm* timeinfo;
  1068. char timestamp[80];
  1069. time(&rawtime);
  1070. timeinfo = localtime(&rawtime);
  1071. strftime(timestamp, 80, "%F %T", timeinfo);
  1072. #define MAX_BOND_MSG_LEN 1024
  1073. char traceMsg[MAX_BOND_MSG_LEN];
  1074. char userMsg[MAX_BOND_MSG_LEN];
  1075. va_list args;
  1076. va_start(args, fmt);
  1077. if (vsnprintf(userMsg, sizeof(userMsg), fmt, args) < 0) {
  1078. fprintf(stderr, "Encountered format encoding error while writing to trace log\n");
  1079. return;
  1080. }
  1081. snprintf(traceMsg, MAX_BOND_MSG_LEN, "%s (%llx/%s) %s", timestamp, _peerId, _policyAlias.c_str(), userMsg);
  1082. va_end(args);
  1083. RR->t->bondStateMessage(NULL, traceMsg);
  1084. #undef MAX_MSG_LEN
  1085. #endif
  1086. }
  1087. private:
  1088. struct NominatedPath {
  1089. NominatedPath()
  1090. : lastAckSent(0)
  1091. , lastAckReceived(0)
  1092. , unackedBytes(0)
  1093. , packetsReceivedSinceLastAck(0)
  1094. , lastQoSMeasurement(0)
  1095. , lastThroughputEstimation(0)
  1096. , lastRefractoryUpdate(0)
  1097. , lastAliveToggle(0)
  1098. , alive(false)
  1099. , eligible(true)
  1100. , whenNominated(0)
  1101. , refractoryPeriod(0)
  1102. , ipvPref(0)
  1103. , mode(0)
  1104. , onlyPathOnLink(false)
  1105. , bonded(false)
  1106. , negotiated(false)
  1107. , shouldReallocateFlows(false)
  1108. , assignedFlowCount(0)
  1109. , latencyMean(0)
  1110. , latencyVariance(0)
  1111. , packetLossRatio(0)
  1112. , packetErrorRatio(0)
  1113. , throughputMean(0)
  1114. , throughputMax(0)
  1115. , throughputVariance(0)
  1116. , allocation(0)
  1117. , byteLoad(0)
  1118. , relativeByteLoad(0)
  1119. , affinity(0)
  1120. , failoverScore(0)
  1121. , packetsReceivedSinceLastQoS(0)
  1122. , packetsIn(0)
  1123. , packetsOut(0)
  1124. {
  1125. }
  1126. /**
  1127. * Set or update a refractory period for the path.
  1128. *
  1129. * @param punishment How much a path should be punished
  1130. * @param pathFailure Whether this call is the result of a recent path failure
  1131. */
  1132. inline void adjustRefractoryPeriod(int64_t now, uint32_t punishment, bool pathFailure)
  1133. {
  1134. if (pathFailure) {
  1135. unsigned int suggestedRefractoryPeriod = refractoryPeriod ? punishment + (refractoryPeriod * 2) : punishment;
  1136. refractoryPeriod = std::min(suggestedRefractoryPeriod, (unsigned int)ZT_BOND_MAX_REFRACTORY_PERIOD);
  1137. lastRefractoryUpdate = 0;
  1138. }
  1139. else {
  1140. uint32_t drainRefractory = 0;
  1141. if (lastRefractoryUpdate) {
  1142. drainRefractory = (now - lastRefractoryUpdate);
  1143. }
  1144. else {
  1145. drainRefractory = (now - lastAliveToggle);
  1146. }
  1147. lastRefractoryUpdate = now;
  1148. if (refractoryPeriod > drainRefractory) {
  1149. refractoryPeriod -= drainRefractory;
  1150. }
  1151. else {
  1152. refractoryPeriod = 0;
  1153. lastRefractoryUpdate = 0;
  1154. }
  1155. }
  1156. }
  1157. /**
  1158. * @return True if a path is permitted to be used in a bond (according to user pref.)
  1159. */
  1160. inline bool allowed()
  1161. {
  1162. return (! ipvPref || ((p->_addr.isV4() && (ipvPref == 4 || ipvPref == 46 || ipvPref == 64)) || ((p->_addr.isV6() && (ipvPref == 6 || ipvPref == 46 || ipvPref == 64)))));
  1163. }
  1164. /**
  1165. * @return True if a path is preferred over another on the same physical link (according to user pref.)
  1166. */
  1167. inline bool preferred()
  1168. {
  1169. return onlyPathOnLink || (p->_addr.isV4() && (ipvPref == 4 || ipvPref == 46)) || (p->_addr.isV6() && (ipvPref == 6 || ipvPref == 64));
  1170. }
  1171. /**
  1172. * @param now Current time
  1173. * @return Whether a QoS (VERB_QOS_MEASUREMENT) packet needs to be emitted at this time
  1174. */
  1175. inline bool needsToSendQoS(int64_t now, int qosSendInterval)
  1176. {
  1177. // fprintf(stderr, "QOS table (%d / %d)\n", packetsReceivedSinceLastQoS, ZT_QOS_TABLE_SIZE);
  1178. return ((packetsReceivedSinceLastQoS >= ZT_QOS_TABLE_SIZE) || ((now - lastQoSMeasurement) > qosSendInterval)) && packetsReceivedSinceLastQoS;
  1179. }
  1180. /**
  1181. * @param now Current time
  1182. * @return Whether an ACK (VERB_ACK) packet needs to be emitted at this time
  1183. */
  1184. inline bool needsToSendAck(int64_t now, int ackSendInterval)
  1185. {
  1186. return ((now - lastAckSent) >= ackSendInterval || (packetsReceivedSinceLastAck == ZT_QOS_TABLE_SIZE)) && packetsReceivedSinceLastAck;
  1187. }
  1188. /**
  1189. * Reset packet counters
  1190. */
  1191. inline void resetPacketCounts()
  1192. {
  1193. packetsIn = 0;
  1194. packetsOut = 0;
  1195. }
  1196. std::map<uint64_t, uint64_t> qosStatsOut; // id:egress_time
  1197. std::map<uint64_t, uint64_t> qosStatsIn; // id:now
  1198. std::map<uint64_t, uint64_t> ackStatsIn; // id:now
  1199. RingBuffer<int, ZT_QOS_SHORTTERM_SAMPLE_WIN_SIZE> qosRecordSize;
  1200. RingBuffer<float, ZT_QOS_SHORTTERM_SAMPLE_WIN_SIZE> qosRecordLossSamples;
  1201. RingBuffer<uint64_t, ZT_QOS_SHORTTERM_SAMPLE_WIN_SIZE> throughputSamples;
  1202. RingBuffer<bool, ZT_QOS_SHORTTERM_SAMPLE_WIN_SIZE> packetValiditySamples;
  1203. RingBuffer<float, ZT_QOS_SHORTTERM_SAMPLE_WIN_SIZE> throughputVarianceSamples;
  1204. RingBuffer<uint16_t, ZT_QOS_SHORTTERM_SAMPLE_WIN_SIZE> latencySamples;
  1205. uint64_t lastAckSent;
  1206. uint64_t lastAckReceived;
  1207. uint64_t unackedBytes;
  1208. uint64_t packetsReceivedSinceLastAck;
  1209. uint64_t lastQoSMeasurement; // Last time that a VERB_QOS_MEASUREMENT was sent out on this path.
  1210. uint64_t lastThroughputEstimation; // Last time that the path's throughput was estimated.
  1211. uint64_t lastRefractoryUpdate; // The last time that the refractory period was updated.
  1212. uint64_t lastAliveToggle; // The last time that the path was marked as "alive".
  1213. bool alive;
  1214. bool eligible; // State of eligibility at last check. Used for determining state changes.
  1215. uint64_t whenNominated; // Timestamp indicating when this path's trial period began.
  1216. uint32_t refractoryPeriod; // Amount of time that this path will be prevented from becoming a member of a bond.
  1217. uint8_t ipvPref; // IP version preference inherited from the physical link.
  1218. uint8_t mode; // Mode inherited from the physical link.
  1219. bool onlyPathOnLink; // IP version preference inherited from the physical link.
  1220. bool enabled; // Enabled state inherited from the physical link.
  1221. bool bonded; // Whether this path is currently part of a bond.
  1222. bool negotiated; // Whether this path was intentionally negotiated by either peer.
  1223. bool shouldReallocateFlows; // Whether flows should be moved from this path. Current traffic flows will be re-allocated immediately.
  1224. uint16_t assignedFlowCount; // The number of flows currently assigned to this path.
  1225. float latencyMean; // The mean latency (computed from a sliding window.)
  1226. float latencyVariance; // Packet delay variance (computed from a sliding window.)
  1227. float packetLossRatio; // The ratio of lost packets to received packets.
  1228. float packetErrorRatio; // The ratio of packets that failed their MAC/CRC checks to those that did not.
  1229. uint64_t throughputMean; // The estimated mean throughput of this path.
  1230. uint64_t throughputMax; // The maximum observed throughput of this path.
  1231. float throughputVariance; // The variance in the estimated throughput of this path.
  1232. uint8_t allocation; // The relative quality of this path to all others in the bond, [0-255].
  1233. uint64_t byteLoad; // How much load this path is under.
  1234. uint8_t relativeByteLoad; // How much load this path is under (relative to other paths in the bond.)
  1235. uint8_t affinity; // Relative value expressing how "deserving" this path is of new traffic.
  1236. uint32_t failoverScore; // Score that indicates to what degree this path is preferred over others that are available to the bonding policy. (specifically for active-backup)
  1237. int32_t packetsReceivedSinceLastQoS; // Number of packets received since the last VERB_QOS_MEASUREMENT was sent to the remote peer.
  1238. /**
  1239. * Counters used for tracking path load.
  1240. */
  1241. int packetsIn;
  1242. int packetsOut;
  1243. // AtomicCounter __refCount;
  1244. SharedPtr<Path> p;
  1245. void set(uint64_t now, const SharedPtr<Path>& path)
  1246. {
  1247. p = path;
  1248. whenNominated = now;
  1249. p->_bondingMetricPtr = (void*)this;
  1250. }
  1251. };
  1252. /**
  1253. * Paths nominated to the bond (may or may not actually be bonded)
  1254. */
  1255. NominatedPath _paths[ZT_MAX_PEER_NETWORK_PATHS];
  1256. inline int getNominatedPathIdx(const SharedPtr<Path>& path)
  1257. {
  1258. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1259. if (_paths[i].p == path) {
  1260. return i;
  1261. }
  1262. }
  1263. return ZT_MAX_PEER_NETWORK_PATHS;
  1264. }
  1265. /**
  1266. * A protocol flow that is identified by the origin and destination port.
  1267. */
  1268. struct Flow {
  1269. /**
  1270. * @param flowId Given flow ID
  1271. * @param now Current time
  1272. */
  1273. Flow(int32_t flowId, int64_t now) : id(flowId), bytesIn(0), bytesOut(0), lastActivity(now), lastPathReassignment(0), assignedPath(ZT_MAX_PEER_NETWORK_PATHS)
  1274. {
  1275. }
  1276. /**
  1277. * Reset flow statistics
  1278. */
  1279. inline void resetByteCounts()
  1280. {
  1281. bytesIn = 0;
  1282. bytesOut = 0;
  1283. }
  1284. /**
  1285. * How long since a packet was sent or received in this flow
  1286. *
  1287. * @param now Current time
  1288. * @return The age of the flow in terms of last recorded activity
  1289. */
  1290. int64_t age(int64_t now)
  1291. {
  1292. return now - lastActivity;
  1293. }
  1294. /**
  1295. * @param path Assigned path over which this flow should be handled
  1296. */
  1297. inline void assignPath(int pathIdx, int64_t now)
  1298. {
  1299. assignedPath = pathIdx;
  1300. lastPathReassignment = now;
  1301. }
  1302. AtomicCounter __refCount;
  1303. int32_t id; // Flow ID used for hashing and path selection
  1304. uint64_t bytesIn; // Used for tracking flow size
  1305. uint64_t bytesOut; // Used for tracking flow size
  1306. int64_t lastActivity; // The last time that this flow handled traffic
  1307. int64_t lastPathReassignment; // Time of last path assignment. Used for anti-flapping
  1308. int assignedPath; // Index of path to which this flow is assigned
  1309. };
  1310. const RuntimeEnvironment* RR;
  1311. AtomicCounter __refCount;
  1312. std::string _policyAlias; // Custom name given by the user to this bond type.
  1313. /**
  1314. * Set of indices corresponding to paths currently included in the bond proper. This
  1315. * may only be updated during a call to curateBond(). The reason for this is so that
  1316. * we can simplify the high frequency packet egress logic.
  1317. */
  1318. int _bondIdxMap[ZT_MAX_PEER_NETWORK_PATHS];
  1319. int _numBondedPaths; // Number of paths currently included in the _bondIdxMap set.
  1320. std::map<int32_t, SharedPtr<Flow> > _flows; // Flows hashed according to port and protocol
  1321. float _qw[ZT_QOS_WEIGHT_SIZE]; // How much each factor contributes to the "quality" score of a path.
  1322. uint8_t _policy;
  1323. uint32_t _upDelay;
  1324. uint32_t _downDelay;
  1325. // active-backup
  1326. int _abPathIdx; // current active path
  1327. std::deque<int> _abFailoverQueue;
  1328. uint8_t _abLinkSelectMethod; // link re-selection policy for the primary link in active-backup
  1329. // balance-rr
  1330. uint8_t _rrIdx; // index to path currently in use during Round Robin operation
  1331. uint16_t _rrPacketsSentOnCurrLink; // number of packets sent on this link since the most recent path switch.
  1332. /**
  1333. * How many packets will be sent on a path before moving to the next path
  1334. * in the round-robin sequence. A value of zero will cause a random path
  1335. * selection for each outgoing packet.
  1336. */
  1337. int _packetsPerLink;
  1338. // balance-aware
  1339. uint64_t _totalBondUnderload;
  1340. uint8_t _flowRebalanceStrategy;
  1341. // dynamic link monitoring
  1342. uint8_t _linkMonitorStrategy;
  1343. // path negotiation
  1344. int16_t _localUtility;
  1345. int _negotiatedPathIdx;
  1346. uint8_t _numSentPathNegotiationRequests;
  1347. bool _allowPathNegotiation;
  1348. /**
  1349. * Timers and intervals
  1350. */
  1351. uint32_t _failoverInterval;
  1352. uint32_t _qosSendInterval;
  1353. uint32_t _ackSendInterval;
  1354. uint32_t throughputMeasurementInterval;
  1355. uint32_t _qualityEstimationInterval;
  1356. /**
  1357. * Acceptable quality thresholds
  1358. */
  1359. float _maxAcceptablePacketLossRatio;
  1360. float _maxAcceptablePacketErrorRatio;
  1361. uint16_t _maxAcceptableLatency;
  1362. uint16_t _maxAcceptableMeanLatency;
  1363. uint16_t _maxAcceptablePacketDelayVariance;
  1364. uint8_t _minAcceptableAllocation;
  1365. /**
  1366. * Link state reporting
  1367. */
  1368. uint8_t _numAliveLinks;
  1369. uint8_t _numTotalLinks;
  1370. /**
  1371. * Default initial punishment inflicted on misbehaving paths. Punishment slowly
  1372. * drains linearly. For each eligibility change the remaining punishment is doubled.
  1373. */
  1374. uint32_t _defaultPathRefractoryPeriod;
  1375. unsigned char _freeRandomByte; // Free byte of entropy that is updated on every packet egress event.
  1376. SharedPtr<Peer> _peer; // Remote peer that this bond services
  1377. unsigned long long _peerId; // ID of the peer that this bond services
  1378. bool _isLeaf;
  1379. /**
  1380. * Rate-limiting
  1381. */
  1382. uint16_t _qosCutoffCount;
  1383. uint16_t _ackCutoffCount;
  1384. uint64_t _lastQoSRateCheck;
  1385. uint64_t _lastAckRateCheck;
  1386. uint16_t _pathNegotiationCutoffCount;
  1387. uint64_t _lastPathNegotiationReceived;
  1388. /**
  1389. * Recent event timestamps
  1390. */
  1391. uint64_t _lastSummaryDump;
  1392. uint64_t _lastQualityEstimation;
  1393. uint64_t _lastBackgroundTaskCheck;
  1394. uint64_t _lastBondStatusLog;
  1395. uint64_t _lastPathNegotiationCheck;
  1396. uint64_t _lastSentPathNegotiationRequest;
  1397. uint64_t _lastFlowExpirationCheck;
  1398. uint64_t _lastFlowRebalance;
  1399. uint64_t _lastFrame;
  1400. uint64_t _lastActiveBackupPathChange;
  1401. Mutex _paths_m;
  1402. Mutex _flows_m;
  1403. bool _userHasSpecifiedLinks; // Whether the user has specified links for this bond.
  1404. bool _userHasSpecifiedPrimaryLink; // Whether the user has specified a primary link for this bond.
  1405. bool _userHasSpecifiedFailoverInstructions; // Whether the user has specified failover instructions for this bond.
  1406. bool _userHasSpecifiedLinkSpeeds; // Whether the user has specified links speeds for this bond.
  1407. /**
  1408. * How frequently (in ms) a VERB_ECHO is sent to a peer to verify that a
  1409. * path is still active. A value of zero (0) will disable active path
  1410. * monitoring; as result, all monitoring will be a function of traffic.
  1411. */
  1412. int _monitorInterval;
  1413. bool _allowFlowHashing; // Whether or not flow hashing is allowed.
  1414. uint64_t _overheadBytes;
  1415. };
  1416. } // namespace ZeroTier
  1417. #endif