Cluster.hpp 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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 "Address.hpp"
  34. #include "InetAddress.hpp"
  35. #include "SHA512.hpp"
  36. #include "Utils.hpp"
  37. #include "Buffer.hpp"
  38. #include "Mutex.hpp"
  39. /**
  40. * Timeout for cluster members being considered "alive"
  41. */
  42. #define ZT_CLUSTER_TIMEOUT ZT_PEER_ACTIVITY_TIMEOUT
  43. /**
  44. * Maximum cluster message length in bytes
  45. *
  46. * Cluster nodes speak via TCP, with data encapsulated into individually
  47. * encrypted and authenticated messages. The maximum message size is
  48. * 65535 (0xffff) since the TCP stream uses 16-bit message size headers
  49. * (and this is a reasonable chunk size anyway).
  50. */
  51. #define ZT_CLUSTER_MAX_MESSAGE_LENGTH 65535
  52. /**
  53. * Maximum number of physical addresses we will cache for a cluster member
  54. */
  55. #define ZT_CLUSTER_MEMBER_MAX_PHYSICAL_ADDRS 8
  56. namespace ZeroTier {
  57. class RuntimeEnvironment;
  58. class CertificateOfMembership;
  59. class MulticastGroup;
  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. * Which distance algorithm is this cluster using?
  85. */
  86. enum DistanceAlgorithm
  87. {
  88. /**
  89. * Simple linear distance in three dimensions
  90. */
  91. DISTANCE_SIMPLE = 0,
  92. /**
  93. * Haversine formula using X,Y as lat,long and ignoring Z
  94. */
  95. DISTANCE_HAVERSINE = 1
  96. };
  97. /**
  98. * State message types
  99. */
  100. enum StateMessageType
  101. {
  102. STATE_MESSAGE_NOP = 0,
  103. /**
  104. * This cluster member is alive:
  105. * <[2] version minor>
  106. * <[2] version major>
  107. * <[2] version revision>
  108. * <[1] protocol version>
  109. * <[4] X location (signed 32-bit)>
  110. * <[4] Y location (signed 32-bit)>
  111. * <[4] Z location (signed 32-bit)>
  112. * <[8] local clock at this member>
  113. * <[8] load average>
  114. * <[8] flags (currently unused, must be zero)>
  115. * <[1] number of preferred ZeroTier endpoints>
  116. * <[...] InetAddress(es) of preferred ZeroTier endpoint(s)>
  117. */
  118. STATE_MESSAGE_ALIVE = 1,
  119. /**
  120. * Cluster member has this peer:
  121. * <[...] binary serialized peer identity>
  122. */
  123. STATE_MESSAGE_HAVE_PEER = 2,
  124. /**
  125. * Peer subscription to multicast group:
  126. * <[8] network ID>
  127. * <[5] peer ZeroTier address>
  128. * <[6] MAC address of multicast group>
  129. * <[4] 32-bit multicast group ADI>
  130. */
  131. STATE_MESSAGE_MULTICAST_LIKE = 3,
  132. /**
  133. * Certificate of network membership for a peer:
  134. * <[...] serialized COM>
  135. */
  136. STATE_MESSAGE_COM = 4,
  137. /**
  138. * Relay a packet to a peer:
  139. * <[1] 8-bit number of sending peer active path addresses>
  140. * <[...] series of serialized InetAddresses of sending peer's paths>
  141. * <[2] 16-bit packet length>
  142. * <[...] packet or packet fragment>
  143. */
  144. STATE_MESSAGE_RELAY = 5,
  145. /**
  146. * Request to send a packet to a locally-known peer:
  147. * <[5] ZeroTier address of recipient>
  148. * <[1] packet verb>
  149. * <[2] length of packet payload>
  150. * <[...] packet payload>
  151. *
  152. * This differs from RELAY in that it requests the receiving cluster
  153. * member to actually compose a ZeroTier Packet from itself to the
  154. * provided recipient. RELAY simply says "please forward this blob."
  155. * RELAY is used to implement peer-to-peer relaying with RENDEZVOUS,
  156. * while PROXY_SEND is used to implement proxy sending (which right
  157. * now is only used to send RENDEZVOUS).
  158. */
  159. STATE_MESSAGE_PROXY_SEND = 6
  160. };
  161. /**
  162. * Construct a new cluster
  163. *
  164. * @param renv Runtime environment
  165. * @param id This member's ID in the cluster
  166. * @param da Distance algorithm this cluster uses to compute distance and hand off peers
  167. * @param x My X
  168. * @param y My Y
  169. * @param z My Z
  170. * @param sendFunction Function to call to send messages to other cluster members
  171. * @param arg First argument to sendFunction
  172. */
  173. Cluster(
  174. const RuntimeEnvironment *renv,
  175. uint16_t id,
  176. DistanceAlgorithm da,
  177. int32_t x,
  178. int32_t y,
  179. int32_t z,
  180. void (*sendFunction)(void *,uint16_t,const void *,unsigned int),
  181. void *arg);
  182. ~Cluster();
  183. /**
  184. * @return This cluster member's ID
  185. */
  186. inline uint16_t id() const throw() { return _id; }
  187. /**
  188. * Handle an incoming intra-cluster message
  189. *
  190. * @param data Message data
  191. * @param len Message length (max: ZT_CLUSTER_MAX_MESSAGE_LENGTH)
  192. */
  193. void handleIncomingStateMessage(const void *msg,unsigned int len);
  194. /**
  195. * Advertise to the cluster that we have this peer
  196. *
  197. * @param peerAddress Peer address that we have
  198. */
  199. void replicateHavePeer(const Address &peerAddress);
  200. /**
  201. * Advertise a multicast LIKE to the cluster
  202. *
  203. * @param nwid Network ID
  204. * @param peerAddress Peer address that sent LIKE
  205. * @param group Multicast group
  206. */
  207. void replicateMulticastLike(uint64_t nwid,const Address &peerAddress,const MulticastGroup &group);
  208. /**
  209. * Advertise a network COM to the cluster
  210. *
  211. * @param com Certificate of network membership (contains peer and network ID)
  212. */
  213. void replicateCertificateOfNetworkMembership(const CertificateOfMembership &com);
  214. /**
  215. * This should be called no less frequently than once every 10 seconds.
  216. */
  217. void doPeriodicTasks();
  218. /**
  219. * Add a member ID to this cluster
  220. *
  221. * @param memberId Member ID
  222. */
  223. void addMember(uint16_t memberId);
  224. private:
  225. void _send(uint16_t memberId,const void *msg,unsigned int len);
  226. void _flush(uint16_t memberId);
  227. // These are initialized in the constructor and remain static
  228. uint16_t _masterSecret[ZT_SHA512_DIGEST_LEN / sizeof(uint16_t)];
  229. unsigned char _key[ZT_PEER_SECRET_KEY_LENGTH];
  230. const RuntimeEnvironment *RR;
  231. void (*_sendFunction)(void *,uint16_t,const void *,unsigned int);
  232. void *_arg;
  233. const int32_t _x;
  234. const int32_t _y;
  235. const int32_t _z;
  236. const DistanceAlgorithm _da;
  237. const uint16_t _id;
  238. struct _Member
  239. {
  240. unsigned char key[ZT_PEER_SECRET_KEY_LENGTH];
  241. uint64_t lastReceivedFrom;
  242. uint64_t lastReceivedAliveAnnouncement;
  243. uint64_t lastSentTo;
  244. uint64_t lastAnnouncedAliveTo;
  245. uint64_t load;
  246. int32_t x,y,z;
  247. InetAddress physicalAddresses[ZT_CLUSTER_MEMBER_MAX_PHYSICAL_ADDRS];
  248. unsigned int physicalAddressCount;
  249. Buffer<ZT_CLUSTER_MAX_MESSAGE_LENGTH> q;
  250. Mutex lock;
  251. _Member() :
  252. lastReceivedFrom(0),
  253. lastReceivedAliveAnnouncement(0),
  254. lastSentTo(0),
  255. lastAnnouncedAliveTo(0),
  256. load(0),
  257. x(0),
  258. y(0),
  259. z(0),
  260. physicalAddressCount(0) {}
  261. ~_Member() { Utils::burn(key,sizeof(key)); }
  262. };
  263. _Member _members[65536]; // cluster IDs can be from 0 to 65535 (16-bit)
  264. std::vector<uint16_t> _memberIds;
  265. Mutex _memberIds_m;
  266. // Record tracking which members have which peers and how recently they claimed this
  267. struct _PeerAffinity
  268. {
  269. _PeerAffinity(const Address &a,uint16_t mid,uint64_t ts) :
  270. key((a.toInt() << 16) | (uint64_t)mid),
  271. timestamp(ts) {}
  272. uint64_t key;
  273. uint64_t timestamp;
  274. inline Address address() const throw() { return Address(key >> 16); }
  275. inline uint16_t clusterMemberId() const throw() { return (uint16_t)(key & 0xffff); }
  276. inline bool operator<(const _PeerAffinity &pi) const throw() { return (key < pi.key); }
  277. };
  278. // A memory-efficient packed map of _PeerAffinity records searchable with std::binary_search() and std::lower_bound()
  279. std::vector<_PeerAffinity> _peerAffinities;
  280. Mutex _peerAffinities_m;
  281. };
  282. } // namespace ZeroTier
  283. #endif // ZT_ENABLE_CLUSTER
  284. #endif