Cluster.hpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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 <map>
  31. #include "Constants.hpp"
  32. #include "../include/ZeroTierOne.h"
  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. #include "SharedPtr.hpp"
  40. #include "Hashtable.hpp"
  41. #include "Packet.hpp"
  42. #include "SharedPtr.hpp"
  43. /**
  44. * Timeout for cluster members being considered "alive"
  45. *
  46. * A cluster member is considered dead and will no longer have peers
  47. * redirected to it if we have not heard a heartbeat in this long.
  48. */
  49. #define ZT_CLUSTER_TIMEOUT 5000
  50. /**
  51. * Desired period between doPeriodicTasks() in milliseconds
  52. */
  53. #define ZT_CLUSTER_PERIODIC_TASK_PERIOD 25
  54. /**
  55. * How often to flush outgoing message queues (maximum interval)
  56. */
  57. #define ZT_CLUSTER_FLUSH_PERIOD 100
  58. /**
  59. * Maximum number of queued outgoing packets per sender address
  60. */
  61. #define ZT_CLUSTER_MAX_QUEUE_PER_SENDER 8
  62. /**
  63. * Expiration time for send queue entries
  64. */
  65. #define ZT_CLUSTER_QUEUE_EXPIRATION 1500
  66. namespace ZeroTier {
  67. class RuntimeEnvironment;
  68. class MulticastGroup;
  69. class Peer;
  70. class Identity;
  71. // Internal class implemented inside Cluster.cpp
  72. class _ClusterSendQueue;
  73. /**
  74. * Multi-homing cluster state replication and packet relaying
  75. *
  76. * Multi-homing means more than one node sharing the same ZeroTier identity.
  77. * There is nothing in the protocol to prevent this, but to make it work well
  78. * requires the devices sharing an identity to cooperate and share some
  79. * information.
  80. *
  81. * There are three use cases we want to fulfill:
  82. *
  83. * (1) Multi-homing of root servers with handoff for efficient routing,
  84. * HA, and load balancing across many commodity nodes.
  85. * (2) Multi-homing of network controllers for the same reason.
  86. * (3) Multi-homing of nodes on virtual networks, such as domain servers
  87. * and other important endpoints.
  88. *
  89. * These use cases are in order of escalating difficulty. The initial
  90. * version of Cluster is aimed at satisfying the first, though you are
  91. * free to try #2 and #3.
  92. */
  93. class Cluster
  94. {
  95. public:
  96. /**
  97. * State message types
  98. */
  99. enum StateMessageType
  100. {
  101. CLUSTER_MESSAGE_NOP = 0,
  102. /**
  103. * This cluster member is alive:
  104. * <[2] version minor>
  105. * <[2] version major>
  106. * <[2] version revision>
  107. * <[1] protocol version>
  108. * <[4] X location (signed 32-bit)>
  109. * <[4] Y location (signed 32-bit)>
  110. * <[4] Z location (signed 32-bit)>
  111. * <[8] local clock at this member>
  112. * <[8] load average>
  113. * <[8] number of peers>
  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. * Cluster members constantly broadcast an alive heartbeat and will only
  119. * receive peer redirects if they've done so within the timeout.
  120. */
  121. CLUSTER_MESSAGE_ALIVE = 1,
  122. /**
  123. * Cluster member has this peer:
  124. * <[...] serialized identity of peer>
  125. *
  126. * This is typically sent in response to WANT_PEER but can also be pushed
  127. * to prepopulate if this makes sense.
  128. */
  129. CLUSTER_MESSAGE_HAVE_PEER = 2,
  130. /**
  131. * Cluster member wants this peer:
  132. * <[5] ZeroTier address of peer>
  133. *
  134. * Members that have a direct link to this peer will respond with
  135. * HAVE_PEER.
  136. */
  137. CLUSTER_MESSAGE_WANT_PEER = 3,
  138. /**
  139. * A remote packet that we should also possibly respond to:
  140. * <[2] 16-bit length of remote packet>
  141. * <[...] remote packet payload>
  142. *
  143. * Cluster members may relay requests by relaying the request packet.
  144. * These may include requests such as WHOIS and MULTICAST_GATHER. The
  145. * packet must be already decrypted, decompressed, and authenticated.
  146. *
  147. * This can only be used for small request packets as per the cluster
  148. * message size limit, but since these are the only ones in question
  149. * this is fine.
  150. *
  151. * If a response is generated it is sent via PROXY_SEND.
  152. */
  153. CLUSTER_MESSAGE_REMOTE_PACKET = 4,
  154. /**
  155. * Request that VERB_RENDEZVOUS be sent to a peer that we have:
  156. * <[5] ZeroTier address of peer on recipient's side>
  157. * <[5] ZeroTier address of peer on sender's side>
  158. * <[1] 8-bit number of sender's peer's active path addresses>
  159. * <[...] series of serialized InetAddresses of sender's peer's paths>
  160. *
  161. * This requests that we perform NAT-t introduction between a peer that
  162. * we have and one on the sender's side. The sender furnishes contact
  163. * info for its peer, and we send VERB_RENDEZVOUS to both sides: to ours
  164. * directly and with PROXY_SEND to theirs.
  165. */
  166. CLUSTER_MESSAGE_PROXY_UNITE = 5,
  167. /**
  168. * Request that a cluster member send a packet to a locally-known peer:
  169. * <[5] ZeroTier address of recipient>
  170. * <[1] packet verb>
  171. * <[2] length of packet payload>
  172. * <[...] packet payload>
  173. *
  174. * This differs from RELAY in that it requests the receiving cluster
  175. * member to actually compose a ZeroTier Packet from itself to the
  176. * provided recipient. RELAY simply says "please forward this blob."
  177. * RELAY is used to implement peer-to-peer relaying with RENDEZVOUS,
  178. * while PROXY_SEND is used to implement proxy sending (which right
  179. * now is only used to send RENDEZVOUS).
  180. */
  181. CLUSTER_MESSAGE_PROXY_SEND = 6,
  182. /**
  183. * Replicate a network config for a network we belong to:
  184. * <[8] 64-bit network ID>
  185. * <[2] 16-bit length of network config>
  186. * <[...] serialized network config>
  187. *
  188. * This is used by clusters to avoid every member having to query
  189. * for the same netconf for networks all members belong to.
  190. *
  191. * TODO: not implemented yet!
  192. */
  193. CLUSTER_MESSAGE_NETWORK_CONFIG = 7
  194. };
  195. /**
  196. * Construct a new cluster
  197. */
  198. Cluster(
  199. const RuntimeEnvironment *renv,
  200. uint16_t id,
  201. const std::vector<InetAddress> &zeroTierPhysicalEndpoints,
  202. int32_t x,
  203. int32_t y,
  204. int32_t z,
  205. void (*sendFunction)(void *,unsigned int,const void *,unsigned int),
  206. void *sendFunctionArg,
  207. int (*addressToLocationFunction)(void *,const struct sockaddr_storage *,int *,int *,int *),
  208. void *addressToLocationFunctionArg);
  209. ~Cluster();
  210. /**
  211. * @return This cluster member's ID
  212. */
  213. inline uint16_t id() const throw() { return _id; }
  214. /**
  215. * Handle an incoming intra-cluster message
  216. *
  217. * @param data Message data
  218. * @param len Message length (max: ZT_CLUSTER_MAX_MESSAGE_LENGTH)
  219. */
  220. void handleIncomingStateMessage(const void *msg,unsigned int len);
  221. /**
  222. * Broadcast that we have a given peer
  223. *
  224. * This should be done when new peers are first contacted.
  225. *
  226. * @param id Identity of peer
  227. */
  228. void broadcastHavePeer(const Identity &id);
  229. /**
  230. * Send this packet via another node in this cluster if another node has this peer
  231. *
  232. * This is used in the outgoing packet and relaying logic in Switch to
  233. * relay packets to other cluster members. It isn't PROXY_SEND-- that is
  234. * used internally in Cluster to send responses to peer queries.
  235. *
  236. * @param fromPeerAddress Source peer address (if known, should be NULL for fragments)
  237. * @param toPeerAddress Destination peer address
  238. * @param data Packet or packet fragment data
  239. * @param len Length of packet or fragment
  240. * @param unite If true, also request proxy unite across cluster
  241. */
  242. void sendViaCluster(const Address &fromPeerAddress,const Address &toPeerAddress,const void *data,unsigned int len,bool unite);
  243. /**
  244. * Send a distributed query to other cluster members
  245. *
  246. * Some queries such as WHOIS or MULTICAST_GATHER need a response from other
  247. * cluster members. Replies (if any) will be sent back to the peer via
  248. * PROXY_SEND across the cluster.
  249. *
  250. * @param pkt Packet to distribute
  251. */
  252. void sendDistributedQuery(const Packet &pkt);
  253. /**
  254. * Call every ~ZT_CLUSTER_PERIODIC_TASK_PERIOD milliseconds.
  255. */
  256. void doPeriodicTasks();
  257. /**
  258. * Add a member ID to this cluster
  259. *
  260. * @param memberId Member ID
  261. */
  262. void addMember(uint16_t memberId);
  263. /**
  264. * Remove a member ID from this cluster
  265. *
  266. * @param memberId Member ID to remove
  267. */
  268. void removeMember(uint16_t memberId);
  269. /**
  270. * Find a better cluster endpoint for this peer (if any)
  271. *
  272. * @param redirectTo InetAddress to be set to a better endpoint (if there is one)
  273. * @param peerAddress Address of peer to (possibly) redirect
  274. * @param peerPhysicalAddress Physical address of peer's current best path (where packet was most recently received or getBestPath()->address())
  275. * @param offload Always redirect if possible -- can be used to offload peers during shutdown
  276. * @return True if redirectTo was set to a new address, false if redirectTo was not modified
  277. */
  278. bool findBetterEndpoint(InetAddress &redirectTo,const Address &peerAddress,const InetAddress &peerPhysicalAddress,bool offload);
  279. /**
  280. * Fill out ZT_ClusterStatus structure (from core API)
  281. *
  282. * @param status Reference to structure to hold result (anything there is replaced)
  283. */
  284. void status(ZT_ClusterStatus &status) const;
  285. private:
  286. void _send(uint16_t memberId,StateMessageType type,const void *msg,unsigned int len);
  287. void _flush(uint16_t memberId);
  288. void _doREMOTE_WHOIS(uint64_t fromMemberId,const Packet &remotep);
  289. void _doREMOTE_MULTICAST_GATHER(uint64_t fromMemberId,const Packet &remotep);
  290. // These are initialized in the constructor and remain immutable ------------
  291. uint16_t _masterSecret[ZT_SHA512_DIGEST_LEN / sizeof(uint16_t)];
  292. unsigned char _key[ZT_PEER_SECRET_KEY_LENGTH];
  293. const RuntimeEnvironment *RR;
  294. _ClusterSendQueue *const _sendQueue;
  295. void (*_sendFunction)(void *,unsigned int,const void *,unsigned int);
  296. void *_sendFunctionArg;
  297. int (*_addressToLocationFunction)(void *,const struct sockaddr_storage *,int *,int *,int *);
  298. void *_addressToLocationFunctionArg;
  299. const int32_t _x;
  300. const int32_t _y;
  301. const int32_t _z;
  302. const uint16_t _id;
  303. const std::vector<InetAddress> _zeroTierPhysicalEndpoints;
  304. // end immutable fields -----------------------------------------------------
  305. struct _Member
  306. {
  307. unsigned char key[ZT_PEER_SECRET_KEY_LENGTH];
  308. uint64_t lastReceivedAliveAnnouncement;
  309. uint64_t lastAnnouncedAliveTo;
  310. uint64_t load;
  311. uint64_t peers;
  312. int32_t x,y,z;
  313. std::vector<InetAddress> zeroTierPhysicalEndpoints;
  314. Buffer<ZT_CLUSTER_MAX_MESSAGE_LENGTH> q;
  315. Mutex lock;
  316. inline void clear()
  317. {
  318. lastReceivedAliveAnnouncement = 0;
  319. lastAnnouncedAliveTo = 0;
  320. load = 0;
  321. peers = 0;
  322. x = 0;
  323. y = 0;
  324. z = 0;
  325. zeroTierPhysicalEndpoints.clear();
  326. q.clear();
  327. }
  328. _Member() { this->clear(); }
  329. ~_Member() { Utils::burn(key,sizeof(key)); }
  330. };
  331. _Member *const _members;
  332. std::vector<uint16_t> _memberIds;
  333. Mutex _memberIds_m;
  334. std::map< std::pair<Address,unsigned int>,uint64_t > _remotePeers; // we need ordered behavior and lower_bound here
  335. Mutex _remotePeers_m;
  336. uint64_t _lastFlushed;
  337. uint64_t _lastCleanedRemotePeers;
  338. uint64_t _lastCleanedQueue;
  339. };
  340. } // namespace ZeroTier
  341. #endif // ZT_ENABLE_CLUSTER
  342. #endif