Cluster.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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. #define ZT_CLUSTER_TIMEOUT 10000
  46. /**
  47. * How often should we announce that we have a peer?
  48. */
  49. #define ZT_CLUSTER_HAVE_PEER_ANNOUNCE_PERIOD 60000
  50. /**
  51. * Desired period between doPeriodicTasks() in milliseconds
  52. */
  53. #define ZT_CLUSTER_PERIODIC_TASK_PERIOD 100
  54. namespace ZeroTier {
  55. class RuntimeEnvironment;
  56. class CertificateOfMembership;
  57. class MulticastGroup;
  58. class Peer;
  59. class Identity;
  60. /**
  61. * Multi-homing cluster state replication and packet relaying
  62. *
  63. * Multi-homing means more than one node sharing the same ZeroTier identity.
  64. * There is nothing in the protocol to prevent this, but to make it work well
  65. * requires the devices sharing an identity to cooperate and share some
  66. * information.
  67. *
  68. * There are three use cases we want to fulfill:
  69. *
  70. * (1) Multi-homing of root servers with handoff for efficient routing,
  71. * HA, and load balancing across many commodity nodes.
  72. * (2) Multi-homing of network controllers for the same reason.
  73. * (3) Multi-homing of nodes on virtual networks, such as domain servers
  74. * and other important endpoints.
  75. *
  76. * These use cases are in order of escalating difficulty. The initial
  77. * version of Cluster is aimed at satisfying the first, though you are
  78. * free to try #2 and #3.
  79. */
  80. class Cluster
  81. {
  82. public:
  83. /**
  84. * State message types
  85. */
  86. enum StateMessageType
  87. {
  88. STATE_MESSAGE_NOP = 0,
  89. /**
  90. * This cluster member is alive:
  91. * <[2] version minor>
  92. * <[2] version major>
  93. * <[2] version revision>
  94. * <[1] protocol version>
  95. * <[4] X location (signed 32-bit)>
  96. * <[4] Y location (signed 32-bit)>
  97. * <[4] Z location (signed 32-bit)>
  98. * <[8] local clock at this member>
  99. * <[8] load average>
  100. * <[8] flags (currently unused, must be zero)>
  101. * <[1] number of preferred ZeroTier endpoints>
  102. * <[...] InetAddress(es) of preferred ZeroTier endpoint(s)>
  103. */
  104. STATE_MESSAGE_ALIVE = 1,
  105. /**
  106. * Cluster member has this peer:
  107. * <[...] binary serialized peer identity>
  108. */
  109. STATE_MESSAGE_HAVE_PEER = 2,
  110. /**
  111. * Peer subscription to multicast group:
  112. * <[8] network ID>
  113. * <[5] peer ZeroTier address>
  114. * <[6] MAC address of multicast group>
  115. * <[4] 32-bit multicast group ADI>
  116. */
  117. STATE_MESSAGE_MULTICAST_LIKE = 3,
  118. /**
  119. * Certificate of network membership for a peer:
  120. * <[...] serialized COM>
  121. */
  122. STATE_MESSAGE_COM = 4,
  123. /**
  124. * Request that VERB_RENDEZVOUS be sent to a peer that we have:
  125. * <[5] ZeroTier address of peer on recipient's side>
  126. * <[5] ZeroTier address of peer on sender's side>
  127. * <[1] 8-bit number of sender's peer's active path addresses>
  128. * <[...] series of serialized InetAddresses of sender's peer's paths>
  129. *
  130. * This requests that we perform NAT-t introduction between a peer that
  131. * we have and one on the sender's side. The sender furnishes contact
  132. * info for its peer, and we send VERB_RENDEZVOUS to both sides: to ours
  133. * directly and with PROXY_SEND to theirs.
  134. */
  135. STATE_MESSAGE_PROXY_UNITE = 5,
  136. /**
  137. * Request that a cluster member send a packet to a locally-known peer:
  138. * <[5] ZeroTier address of recipient>
  139. * <[1] packet verb>
  140. * <[2] length of packet payload>
  141. * <[...] packet payload>
  142. *
  143. * This differs from RELAY in that it requests the receiving cluster
  144. * member to actually compose a ZeroTier Packet from itself to the
  145. * provided recipient. RELAY simply says "please forward this blob."
  146. * RELAY is used to implement peer-to-peer relaying with RENDEZVOUS,
  147. * while PROXY_SEND is used to implement proxy sending (which right
  148. * now is only used to send RENDEZVOUS).
  149. */
  150. STATE_MESSAGE_PROXY_SEND = 6,
  151. /**
  152. * Replicate a network config for a network we belong to:
  153. * <[8] 64-bit network ID>
  154. * <[2] 16-bit length of network config>
  155. * <[...] serialized network config>
  156. *
  157. * This is used by clusters to avoid every member having to query
  158. * for the same netconf for networks all members belong to.
  159. *
  160. * TODO: not implemented yet!
  161. */
  162. STATE_MESSAGE_NETWORK_CONFIG = 7
  163. };
  164. /**
  165. * Construct a new cluster
  166. */
  167. Cluster(
  168. const RuntimeEnvironment *renv,
  169. uint16_t id,
  170. const std::vector<InetAddress> &zeroTierPhysicalEndpoints,
  171. int32_t x,
  172. int32_t y,
  173. int32_t z,
  174. void (*sendFunction)(void *,unsigned int,const void *,unsigned int),
  175. void *sendFunctionArg,
  176. int (*addressToLocationFunction)(void *,const struct sockaddr_storage *,int *,int *,int *),
  177. void *addressToLocationFunctionArg);
  178. ~Cluster();
  179. /**
  180. * @return This cluster member's ID
  181. */
  182. inline uint16_t id() const throw() { return _id; }
  183. /**
  184. * Handle an incoming intra-cluster message
  185. *
  186. * @param data Message data
  187. * @param len Message length (max: ZT_CLUSTER_MAX_MESSAGE_LENGTH)
  188. */
  189. void handleIncomingStateMessage(const void *msg,unsigned int len);
  190. /**
  191. * Send this packet via another node in this cluster if another node has this peer
  192. *
  193. * @param fromPeerAddress Source peer address (if known, should be NULL for fragments)
  194. * @param toPeerAddress Destination peer address
  195. * @param data Packet or packet fragment data
  196. * @param len Length of packet or fragment
  197. * @param unite If true, also request proxy unite across cluster
  198. * @return True if this data was sent via another cluster member, false if none have this peer
  199. */
  200. bool sendViaCluster(const Address &fromPeerAddress,const Address &toPeerAddress,const void *data,unsigned int len,bool unite);
  201. /**
  202. * Advertise to the cluster that we have this peer
  203. *
  204. * @param peerId Identity of peer that we have
  205. */
  206. void replicateHavePeer(const Identity &peerId);
  207. /**
  208. * Advertise a multicast LIKE to the cluster
  209. *
  210. * @param nwid Network ID
  211. * @param peerAddress Peer address that sent LIKE
  212. * @param group Multicast group
  213. */
  214. void replicateMulticastLike(uint64_t nwid,const Address &peerAddress,const MulticastGroup &group);
  215. /**
  216. * Advertise a network COM to the cluster
  217. *
  218. * @param com Certificate of network membership (contains peer and network ID)
  219. */
  220. void replicateCertificateOfNetworkMembership(const CertificateOfMembership &com);
  221. /**
  222. * Call every ~ZT_CLUSTER_PERIODIC_TASK_PERIOD milliseconds.
  223. */
  224. void doPeriodicTasks();
  225. /**
  226. * Add a member ID to this cluster
  227. *
  228. * @param memberId Member ID
  229. */
  230. void addMember(uint16_t memberId);
  231. /**
  232. * Remove a member ID from this cluster
  233. *
  234. * @param memberId Member ID to remove
  235. */
  236. void removeMember(uint16_t memberId);
  237. /**
  238. * Find a better cluster endpoint for this peer (if any)
  239. *
  240. * @param redirectTo InetAddress to be set to a better endpoint (if there is one)
  241. * @param peerAddress Address of peer to (possibly) redirect
  242. * @param peerPhysicalAddress Physical address of peer's current best path (where packet was most recently received or getBestPath()->address())
  243. * @param offload Always redirect if possible -- can be used to offload peers during shutdown
  244. * @return True if redirectTo was set to a new address, false if redirectTo was not modified
  245. */
  246. bool findBetterEndpoint(InetAddress &redirectTo,const Address &peerAddress,const InetAddress &peerPhysicalAddress,bool offload);
  247. /**
  248. * Fill out ZT_ClusterStatus structure (from core API)
  249. *
  250. * @param status Reference to structure to hold result (anything there is replaced)
  251. */
  252. void status(ZT_ClusterStatus &status) const;
  253. private:
  254. void _send(uint16_t memberId,StateMessageType type,const void *msg,unsigned int len);
  255. void _flush(uint16_t memberId);
  256. // These are initialized in the constructor and remain static
  257. uint16_t _masterSecret[ZT_SHA512_DIGEST_LEN / sizeof(uint16_t)];
  258. unsigned char _key[ZT_PEER_SECRET_KEY_LENGTH];
  259. const RuntimeEnvironment *RR;
  260. void (*_sendFunction)(void *,unsigned int,const void *,unsigned int);
  261. void *_sendFunctionArg;
  262. int (*_addressToLocationFunction)(void *,const struct sockaddr_storage *,int *,int *,int *);
  263. void *_addressToLocationFunctionArg;
  264. const int32_t _x;
  265. const int32_t _y;
  266. const int32_t _z;
  267. const uint16_t _id;
  268. const std::vector<InetAddress> _zeroTierPhysicalEndpoints;
  269. struct _Member
  270. {
  271. unsigned char key[ZT_PEER_SECRET_KEY_LENGTH];
  272. uint64_t lastReceivedAliveAnnouncement;
  273. uint64_t lastAnnouncedAliveTo;
  274. uint64_t load;
  275. int32_t x,y,z;
  276. std::vector<InetAddress> zeroTierPhysicalEndpoints;
  277. Buffer<ZT_CLUSTER_MAX_MESSAGE_LENGTH> q;
  278. Mutex lock;
  279. inline void clear()
  280. {
  281. lastReceivedAliveAnnouncement = 0;
  282. lastAnnouncedAliveTo = 0;
  283. load = 0;
  284. x = 0;
  285. y = 0;
  286. z = 0;
  287. zeroTierPhysicalEndpoints.clear();
  288. q.clear();
  289. }
  290. _Member() { this->clear(); }
  291. ~_Member() { Utils::burn(key,sizeof(key)); }
  292. };
  293. _Member *const _members; // cluster IDs can be from 0 to 65535 (16-bit)
  294. std::vector<uint16_t> _memberIds;
  295. Mutex _memberIds_m;
  296. // Record tracking which members have which peers and how recently they claimed this -- also used to track our last claimed time
  297. struct _PeerAffinity
  298. {
  299. _PeerAffinity(const Address &a,uint16_t mid,uint64_t ts) :
  300. key((a.toInt() << 16) | (uint64_t)mid),
  301. timestamp(ts) {}
  302. uint64_t key;
  303. uint64_t timestamp;
  304. inline Address address() const throw() { return Address(key >> 16); }
  305. inline uint16_t clusterMemberId() const throw() { return (uint16_t)(key & 0xffff); }
  306. inline bool operator<(const _PeerAffinity &pi) const throw() { return (key < pi.key); }
  307. };
  308. // A memory-efficient packed map of _PeerAffinity records searchable with std::binary_search() and std::lower_bound()
  309. std::vector<_PeerAffinity> _peerAffinities;
  310. Mutex _peerAffinities_m;
  311. };
  312. } // namespace ZeroTier
  313. #endif // ZT_ENABLE_CLUSTER
  314. #endif