Cluster.hpp 8.9 KB

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