Bond.hpp 40 KB

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