Cluster.hpp 12 KB

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