Bond.hpp 41 KB

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