Cluster.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 ZeroTier, Inc.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. * --
  19. *
  20. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #ifndef ZT_CLUSTER_HPP
  28. #define ZT_CLUSTER_HPP
  29. #ifdef ZT_ENABLE_CLUSTER
  30. #include <vector>
  31. #include <algorithm>
  32. #include "Constants.hpp"
  33. #include "../include/ZeroTierOne.h"
  34. #include "Address.hpp"
  35. #include "InetAddress.hpp"
  36. #include "SHA512.hpp"
  37. #include "Utils.hpp"
  38. #include "Buffer.hpp"
  39. #include "Mutex.hpp"
  40. #include "SharedPtr.hpp"
  41. #include "Hashtable.hpp"
  42. /**
  43. * Timeout for cluster members being considered "alive"
  44. *
  45. * A cluster member is considered dead and will no longer have peers
  46. * redirected to it if we have not heard a heartbeat in this long.
  47. */
  48. #define ZT_CLUSTER_TIMEOUT 10000
  49. /**
  50. * How often should we announce that we have a peer?
  51. */
  52. #define ZT_CLUSTER_HAVE_PEER_ANNOUNCE_PERIOD ZT_PEER_DIRECT_PING_DELAY
  53. /**
  54. * Desired period between doPeriodicTasks() in milliseconds
  55. */
  56. #define ZT_CLUSTER_PERIODIC_TASK_PERIOD 250
  57. /**
  58. * How often to flush outgoing message queues (maximum interval)
  59. */
  60. #define ZT_CLUSTER_FLUSH_PERIOD 500
  61. namespace ZeroTier {
  62. class RuntimeEnvironment;
  63. class CertificateOfMembership;
  64. class MulticastGroup;
  65. class Peer;
  66. class Identity;
  67. /**
  68. * Multi-homing cluster state replication and packet relaying
  69. *
  70. * Multi-homing means more than one node sharing the same ZeroTier identity.
  71. * There is nothing in the protocol to prevent this, but to make it work well
  72. * requires the devices sharing an identity to cooperate and share some
  73. * information.
  74. *
  75. * There are three use cases we want to fulfill:
  76. *
  77. * (1) Multi-homing of root servers with handoff for efficient routing,
  78. * HA, and load balancing across many commodity nodes.
  79. * (2) Multi-homing of network controllers for the same reason.
  80. * (3) Multi-homing of nodes on virtual networks, such as domain servers
  81. * and other important endpoints.
  82. *
  83. * These use cases are in order of escalating difficulty. The initial
  84. * version of Cluster is aimed at satisfying the first, though you are
  85. * free to try #2 and #3.
  86. */
  87. class Cluster
  88. {
  89. public:
  90. /**
  91. * State message types
  92. */
  93. enum StateMessageType
  94. {
  95. STATE_MESSAGE_NOP = 0,
  96. /**
  97. * This cluster member is alive:
  98. * <[2] version minor>
  99. * <[2] version major>
  100. * <[2] version revision>
  101. * <[1] protocol version>
  102. * <[4] X location (signed 32-bit)>
  103. * <[4] Y location (signed 32-bit)>
  104. * <[4] Z location (signed 32-bit)>
  105. * <[8] local clock at this member>
  106. * <[8] load average>
  107. * <[8] flags (currently unused, must be zero)>
  108. * <[1] number of preferred ZeroTier endpoints>
  109. * <[...] InetAddress(es) of preferred ZeroTier endpoint(s)>
  110. */
  111. STATE_MESSAGE_ALIVE = 1,
  112. /**
  113. * Cluster member has this peer:
  114. * <[...] binary serialized peer identity>
  115. * <[...] binary serialized peer remote physical address>
  116. *
  117. * Clusters send this message when they learn a path to a peer. The
  118. * replicated physical address is the one learned.
  119. */
  120. STATE_MESSAGE_HAVE_PEER = 2,
  121. /**
  122. * Peer subscription to multicast group:
  123. * <[8] network ID>
  124. * <[5] peer ZeroTier address>
  125. * <[6] MAC address of multicast group>
  126. * <[4] 32-bit multicast group ADI>
  127. */
  128. STATE_MESSAGE_MULTICAST_LIKE = 3,
  129. /**
  130. * Certificate of network membership for a peer:
  131. * <[...] serialized COM>
  132. */
  133. STATE_MESSAGE_COM = 4,
  134. /**
  135. * Request that VERB_RENDEZVOUS be sent to a peer that we have:
  136. * <[5] ZeroTier address of peer on recipient's side>
  137. * <[5] ZeroTier address of peer on sender's side>
  138. * <[1] 8-bit number of sender's peer's active path addresses>
  139. * <[...] series of serialized InetAddresses of sender's peer's paths>
  140. *
  141. * This requests that we perform NAT-t introduction between a peer that
  142. * we have and one on the sender's side. The sender furnishes contact
  143. * info for its peer, and we send VERB_RENDEZVOUS to both sides: to ours
  144. * directly and with PROXY_SEND to theirs.
  145. */
  146. STATE_MESSAGE_PROXY_UNITE = 5,
  147. /**
  148. * Request that a cluster member send a packet to a locally-known peer:
  149. * <[5] ZeroTier address of recipient>
  150. * <[1] packet verb>
  151. * <[2] length of packet payload>
  152. * <[...] packet payload>
  153. *
  154. * This differs from RELAY in that it requests the receiving cluster
  155. * member to actually compose a ZeroTier Packet from itself to the
  156. * provided recipient. RELAY simply says "please forward this blob."
  157. * RELAY is used to implement peer-to-peer relaying with RENDEZVOUS,
  158. * while PROXY_SEND is used to implement proxy sending (which right
  159. * now is only used to send RENDEZVOUS).
  160. */
  161. STATE_MESSAGE_PROXY_SEND = 6,
  162. /**
  163. * Replicate a network config for a network we belong to:
  164. * <[8] 64-bit network ID>
  165. * <[2] 16-bit length of network config>
  166. * <[...] serialized network config>
  167. *
  168. * This is used by clusters to avoid every member having to query
  169. * for the same netconf for networks all members belong to.
  170. *
  171. * TODO: not implemented yet!
  172. */
  173. STATE_MESSAGE_NETWORK_CONFIG = 7
  174. };
  175. /**
  176. * Construct a new cluster
  177. */
  178. Cluster(
  179. const RuntimeEnvironment *renv,
  180. uint16_t id,
  181. const std::vector<InetAddress> &zeroTierPhysicalEndpoints,
  182. int32_t x,
  183. int32_t y,
  184. int32_t z,
  185. void (*sendFunction)(void *,unsigned int,const void *,unsigned int),
  186. void *sendFunctionArg,
  187. int (*addressToLocationFunction)(void *,const struct sockaddr_storage *,int *,int *,int *),
  188. void *addressToLocationFunctionArg);
  189. ~Cluster();
  190. /**
  191. * @return This cluster member's ID
  192. */
  193. inline uint16_t id() const throw() { return _id; }
  194. /**
  195. * Handle an incoming intra-cluster message
  196. *
  197. * @param data Message data
  198. * @param len Message length (max: ZT_CLUSTER_MAX_MESSAGE_LENGTH)
  199. */
  200. void handleIncomingStateMessage(const void *msg,unsigned int len);
  201. /**
  202. * Send this packet via another node in this cluster if another node has this peer
  203. *
  204. * @param fromPeerAddress Source peer address (if known, should be NULL for fragments)
  205. * @param toPeerAddress Destination peer address
  206. * @param data Packet or packet fragment data
  207. * @param len Length of packet or fragment
  208. * @param unite If true, also request proxy unite across cluster
  209. * @return True if this data was sent via another cluster member, false if none have this peer
  210. */
  211. bool sendViaCluster(const Address &fromPeerAddress,const Address &toPeerAddress,const void *data,unsigned int len,bool unite);
  212. /**
  213. * Advertise to the cluster that we have this peer
  214. *
  215. * @param peerId Identity of peer that we have
  216. * @param physicalAddress Physical address of peer (from our POV)
  217. */
  218. void replicateHavePeer(const Identity &peerId,const InetAddress &physicalAddress);
  219. /**
  220. * Advertise a multicast LIKE to the cluster
  221. *
  222. * @param nwid Network ID
  223. * @param peerAddress Peer address that sent LIKE
  224. * @param group Multicast group
  225. */
  226. void replicateMulticastLike(uint64_t nwid,const Address &peerAddress,const MulticastGroup &group);
  227. /**
  228. * Advertise a network COM to the cluster
  229. *
  230. * @param com Certificate of network membership (contains peer and network ID)
  231. */
  232. void replicateCertificateOfNetworkMembership(const CertificateOfMembership &com);
  233. /**
  234. * Call every ~ZT_CLUSTER_PERIODIC_TASK_PERIOD milliseconds.
  235. */
  236. void doPeriodicTasks();
  237. /**
  238. * Add a member ID to this cluster
  239. *
  240. * @param memberId Member ID
  241. */
  242. void addMember(uint16_t memberId);
  243. /**
  244. * Remove a member ID from this cluster
  245. *
  246. * @param memberId Member ID to remove
  247. */
  248. void removeMember(uint16_t memberId);
  249. /**
  250. * Find a better cluster endpoint for this peer (if any)
  251. *
  252. * @param redirectTo InetAddress to be set to a better endpoint (if there is one)
  253. * @param peerAddress Address of peer to (possibly) redirect
  254. * @param peerPhysicalAddress Physical address of peer's current best path (where packet was most recently received or getBestPath()->address())
  255. * @param offload Always redirect if possible -- can be used to offload peers during shutdown
  256. * @return True if redirectTo was set to a new address, false if redirectTo was not modified
  257. */
  258. bool findBetterEndpoint(InetAddress &redirectTo,const Address &peerAddress,const InetAddress &peerPhysicalAddress,bool offload);
  259. /**
  260. * Fill out ZT_ClusterStatus structure (from core API)
  261. *
  262. * @param status Reference to structure to hold result (anything there is replaced)
  263. */
  264. void status(ZT_ClusterStatus &status) const;
  265. private:
  266. void _send(uint16_t memberId,StateMessageType type,const void *msg,unsigned int len);
  267. void _flush(uint16_t memberId);
  268. // These are initialized in the constructor and remain immutable
  269. uint16_t _masterSecret[ZT_SHA512_DIGEST_LEN / sizeof(uint16_t)];
  270. unsigned char _key[ZT_PEER_SECRET_KEY_LENGTH];
  271. const RuntimeEnvironment *RR;
  272. void (*_sendFunction)(void *,unsigned int,const void *,unsigned int);
  273. void *_sendFunctionArg;
  274. int (*_addressToLocationFunction)(void *,const struct sockaddr_storage *,int *,int *,int *);
  275. void *_addressToLocationFunctionArg;
  276. const int32_t _x;
  277. const int32_t _y;
  278. const int32_t _z;
  279. const uint16_t _id;
  280. const std::vector<InetAddress> _zeroTierPhysicalEndpoints;
  281. // end immutable fields
  282. struct _Member
  283. {
  284. unsigned char key[ZT_PEER_SECRET_KEY_LENGTH];
  285. uint64_t lastReceivedAliveAnnouncement;
  286. uint64_t lastAnnouncedAliveTo;
  287. uint64_t load;
  288. int32_t x,y,z;
  289. std::vector<InetAddress> zeroTierPhysicalEndpoints;
  290. Buffer<ZT_CLUSTER_MAX_MESSAGE_LENGTH> q;
  291. Mutex lock;
  292. inline void clear()
  293. {
  294. lastReceivedAliveAnnouncement = 0;
  295. lastAnnouncedAliveTo = 0;
  296. load = 0;
  297. x = 0;
  298. y = 0;
  299. z = 0;
  300. zeroTierPhysicalEndpoints.clear();
  301. q.clear();
  302. }
  303. _Member() { this->clear(); }
  304. ~_Member() { Utils::burn(key,sizeof(key)); }
  305. };
  306. _Member *const _members;
  307. std::vector<uint16_t> _memberIds;
  308. Mutex _memberIds_m;
  309. struct _PA
  310. {
  311. _PA() : ts(0),mid(0xffff) {}
  312. uint64_t ts;
  313. uint16_t mid;
  314. };
  315. Hashtable< Address,_PA > _peerAffinities;
  316. Mutex _peerAffinities_m;
  317. uint64_t _lastCleanedPeerAffinities;
  318. uint64_t _lastCheckedPeersForAnnounce;
  319. uint64_t _lastFlushed;
  320. };
  321. } // namespace ZeroTier
  322. #endif // ZT_ENABLE_CLUSTER
  323. #endif