Cluster.hpp 9.1 KB

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