PubSubListener.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. #ifdef ZT_CONTROLLER_USE_LIBPQ
  2. #include "PubSubListener.hpp"
  3. #include "DB.hpp"
  4. #include "member.pb.h"
  5. #include "network.pb.h"
  6. #include "opentelemetry/trace/provider.h"
  7. #include "rustybits.h"
  8. #include <google/cloud/pubsub/admin/subscription_admin_client.h>
  9. #include <google/cloud/pubsub/admin/subscription_admin_connection.h>
  10. #include <google/cloud/pubsub/message.h>
  11. #include <google/cloud/pubsub/subscriber.h>
  12. #include <google/cloud/pubsub/subscription.h>
  13. #include <google/cloud/pubsub/topic.h>
  14. #include <nlohmann/json.hpp>
  15. namespace pubsub = ::google::cloud::pubsub;
  16. namespace pubsub_admin = ::google::cloud::pubsub_admin;
  17. namespace ZeroTier {
  18. nlohmann::json toJson(const pbmessages::NetworkChange_Network& nc);
  19. nlohmann::json toJson(const pbmessages::MemberChange_Member& mc);
  20. PubSubListener::PubSubListener(std::string controller_id, std::string project, std::string topic)
  21. : _controller_id(controller_id)
  22. , _project(project)
  23. , _topic(topic)
  24. , _subscription_id("sub-" + controller_id + "-network-changes")
  25. , _run(false)
  26. , _adminClient(pubsub_admin::MakeSubscriptionAdminConnection())
  27. , _subscription(pubsub::Subscription(_project, _subscription_id))
  28. {
  29. GOOGLE_PROTOBUF_VERIFY_VERSION;
  30. google::pubsub::v1::Subscription request;
  31. request.set_name(_subscription.FullName());
  32. request.set_topic(pubsub::Topic(project, topic).FullName());
  33. request.set_filter("(attributes.controller_id=\"" + _controller_id + "\")");
  34. auto sub = _adminClient.CreateSubscription(request);
  35. if (! sub.ok()) {
  36. fprintf(stderr, "Failed to create subscription: %s\n", sub.status().message().c_str());
  37. throw std::runtime_error("Failed to create subscription");
  38. }
  39. if (sub.status().code() == google::cloud::StatusCode::kAlreadyExists) {
  40. fprintf(stderr, "Subscription already exists\n");
  41. throw std::runtime_error("Subscription already exists");
  42. }
  43. _subscriber = std::make_shared<pubsub::Subscriber>(pubsub::MakeSubscriberConnection(_subscription));
  44. _run = true;
  45. _subscriberThread = std::thread(&PubSubListener::subscribe, this);
  46. }
  47. PubSubListener::~PubSubListener()
  48. {
  49. _run = false;
  50. if (_subscriberThread.joinable()) {
  51. _subscriberThread.join();
  52. }
  53. }
  54. void PubSubListener::subscribe()
  55. {
  56. while (_run) {
  57. try {
  58. fprintf(stderr, "Starting new subscription session\n");
  59. auto session = _subscriber->Subscribe([this](pubsub::Message const& m, pubsub::AckHandler h) {
  60. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  61. auto tracer = provider->GetTracer("PubSubListener");
  62. auto span = tracer->StartSpan("PubSubListener::onMessage");
  63. auto scope = tracer->WithActiveSpan(span);
  64. span->SetAttribute("message_id", m.message_id());
  65. span->SetAttribute("ordering_key", m.ordering_key());
  66. span->SetAttribute("attributes", m.attributes().size());
  67. fprintf(stderr, "Received message %s\n", m.message_id().c_str());
  68. onNotification(m.data());
  69. std::move(h).ack();
  70. span->SetStatus(opentelemetry::trace::StatusCode::kOk);
  71. return true;
  72. });
  73. auto result = session.wait_for(std::chrono::seconds(10));
  74. if (result == std::future_status::timeout) {
  75. session.cancel();
  76. std::this_thread::sleep_for(std::chrono::seconds(5));
  77. continue;
  78. }
  79. if (! session.valid()) {
  80. fprintf(stderr, "Subscription session no longer valid\n");
  81. std::this_thread::sleep_for(std::chrono::seconds(5));
  82. continue;
  83. }
  84. }
  85. catch (google::cloud::Status const& status) {
  86. fprintf(stderr, "Subscription terminated with status: %s\n", status.message().c_str());
  87. std::this_thread::sleep_for(std::chrono::seconds(5));
  88. }
  89. }
  90. }
  91. PubSubNetworkListener::PubSubNetworkListener(std::string controller_id, std::string project, DB* db)
  92. : PubSubListener(controller_id, project, "controller-network-change-stream")
  93. , _db(db)
  94. {
  95. }
  96. PubSubNetworkListener::~PubSubNetworkListener()
  97. {
  98. }
  99. void PubSubNetworkListener::onNotification(const std::string& payload)
  100. {
  101. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  102. auto tracer = provider->GetTracer("PubSubNetworkListener");
  103. auto span = tracer->StartSpan("PubSubNetworkListener::onNotification");
  104. auto scope = tracer->WithActiveSpan(span);
  105. pbmessages::NetworkChange nc;
  106. if (! nc.ParseFromString(payload)) {
  107. fprintf(stderr, "Failed to parse NetworkChange protobuf message\n");
  108. span->SetAttribute("error", "Failed to parse NetworkChange protobuf message");
  109. span->SetStatus(opentelemetry::trace::StatusCode::kError, "Failed to parse protobuf");
  110. return;
  111. }
  112. fprintf(stderr, "Network notification received");
  113. try {
  114. nlohmann::json oldConfig, newConfig;
  115. if (nc.has_old()) {
  116. oldConfig = toJson(nc.old());
  117. }
  118. if (nc.has_new_()) {
  119. newConfig = toJson(nc.new_());
  120. }
  121. if (oldConfig.is_object() && newConfig.is_object()) {
  122. // network modification
  123. std::string nwid = oldConfig["id"].get<std::string>();
  124. span->SetAttribute("action", "network_change");
  125. span->SetAttribute("network_id", nwid);
  126. _db->save(newConfig, _db->isReady());
  127. }
  128. else if (newConfig.is_object() && ! oldConfig.is_object()) {
  129. // new network
  130. std::string nwid = newConfig["id"];
  131. span->SetAttribute("network_id", nwid);
  132. span->SetAttribute("action", "new_network");
  133. _db->save(newConfig, _db->isReady());
  134. }
  135. else if (! newConfig.is_object() && oldConfig.is_object()) {
  136. // network deletion
  137. std::string nwid = oldConfig["id"];
  138. span->SetAttribute("action", "delete_network");
  139. span->SetAttribute("network_id", nwid);
  140. uint64_t networkId = Utils::hexStrToU64(nwid.c_str());
  141. if (networkId) {
  142. _db->eraseNetwork(networkId);
  143. }
  144. }
  145. }
  146. catch (const nlohmann::json::parse_error& e) {
  147. fprintf(stderr, "JSON parse error: %s\n", e.what());
  148. span->SetAttribute("error", e.what());
  149. span->SetStatus(opentelemetry::trace::StatusCode::kError, e.what());
  150. return;
  151. }
  152. catch (const std::exception& e) {
  153. fprintf(stderr, "Exception in PubSubNetworkListener: %s\n", e.what());
  154. span->SetAttribute("error", e.what());
  155. span->SetStatus(opentelemetry::trace::StatusCode::kError, e.what());
  156. return;
  157. }
  158. }
  159. PubSubMemberListener::PubSubMemberListener(std::string controller_id, std::string project, DB* db)
  160. : PubSubListener(controller_id, project, "controller-member-change-stream")
  161. , _db(db)
  162. {
  163. }
  164. PubSubMemberListener::~PubSubMemberListener()
  165. {
  166. }
  167. void PubSubMemberListener::onNotification(const std::string& payload)
  168. {
  169. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  170. auto tracer = provider->GetTracer("PubSubMemberListener");
  171. auto span = tracer->StartSpan("PubSubMemberListener::onNotification");
  172. auto scope = tracer->WithActiveSpan(span);
  173. pbmessages::MemberChange mc;
  174. if (! mc.ParseFromString(payload)) {
  175. fprintf(stderr, "Failed to parse MemberChange protobuf message\n");
  176. span->SetAttribute("error", "Failed to parse MemberChange protobuf message");
  177. span->SetStatus(opentelemetry::trace::StatusCode::kError, "Failed to parse protobuf");
  178. return;
  179. }
  180. fprintf(stderr, "Member notification received");
  181. try {
  182. nlohmann::json tmp;
  183. nlohmann::json oldConfig, newConfig;
  184. if (mc.has_old()) {
  185. oldConfig = toJson(mc.old());
  186. }
  187. if (mc.has_new_()) {
  188. newConfig = toJson(mc.new_());
  189. }
  190. if (oldConfig.is_object() && newConfig.is_object()) {
  191. // member modification
  192. std::string memberID = oldConfig["id"].get<std::string>();
  193. std::string networkID = oldConfig["nwid"].get<std::string>();
  194. span->SetAttribute("action", "member_change");
  195. span->SetAttribute("member_id", memberID);
  196. span->SetAttribute("network_id", networkID);
  197. _db->save(newConfig, _db->isReady());
  198. }
  199. else if (newConfig.is_object() && ! oldConfig.is_object()) {
  200. // new member
  201. std::string memberID = newConfig["id"].get<std::string>();
  202. std::string networkID = newConfig["nwid"].get<std::string>();
  203. span->SetAttribute("action", "new_member");
  204. span->SetAttribute("member_id", memberID);
  205. span->SetAttribute("network_id", networkID);
  206. _db->save(newConfig, _db->isReady());
  207. }
  208. else if (! newConfig.is_object() && oldConfig.is_object()) {
  209. // member deletion
  210. std::string memberID = oldConfig["id"].get<std::string>();
  211. std::string networkID = oldConfig["nwid"].get<std::string>();
  212. span->SetAttribute("action", "delete_member");
  213. span->SetAttribute("member_id", memberID);
  214. span->SetAttribute("network_id", networkID);
  215. uint64_t networkId = Utils::hexStrToU64(networkID.c_str());
  216. uint64_t memberId = Utils::hexStrToU64(memberID.c_str());
  217. if (networkId && memberId) {
  218. _db->eraseMember(networkId, memberId);
  219. }
  220. }
  221. }
  222. catch (const nlohmann::json::parse_error& e) {
  223. fprintf(stderr, "JSON parse error: %s\n", e.what());
  224. span->SetAttribute("error", e.what());
  225. span->SetStatus(opentelemetry::trace::StatusCode::kError, e.what());
  226. return;
  227. }
  228. catch (const std::exception& e) {
  229. fprintf(stderr, "Exception in PubSubMemberListener: %s\n", e.what());
  230. span->SetAttribute("error", e.what());
  231. span->SetStatus(opentelemetry::trace::StatusCode::kError, e.what());
  232. return;
  233. }
  234. }
  235. nlohmann::json toJson(const pbmessages::NetworkChange_Network& nc)
  236. {
  237. nlohmann::json out;
  238. out["id"] = nc.network_id();
  239. out["name"] = nc.name();
  240. out["capabilities"] = OSUtils::jsonParse(nc.capabilities());
  241. out["mtu"] = nc.mtu();
  242. out["multicastLimit"] = nc.multicast_limit();
  243. out["private"] = nc.is_private();
  244. out["remoteTraceLevel"] = nc.remote_trace_level();
  245. if (nc.has_remote_trace_target()) {
  246. out["remoteTraceTarget"] = nc.remote_trace_target();
  247. }
  248. else {
  249. out["remoteTraceTarget"] = "";
  250. }
  251. out["rules"] = OSUtils::jsonParse(nc.rules());
  252. out["rulesSource"] = nc.rules_source();
  253. out["tags"] = OSUtils::jsonParse(nc.tags());
  254. if (nc.has_ipv4_assign_mode()) {
  255. nlohmann::json ipv4mode;
  256. ipv4mode["zt"] = nc.ipv4_assign_mode().zt();
  257. out["ipv4AssignMode"] = ipv4mode;
  258. }
  259. if (nc.has_ipv6_assign_mode()) {
  260. nlohmann::json ipv6mode;
  261. ipv6mode["6plane"] = nc.ipv6_assign_mode().six_plane();
  262. ipv6mode["rfc4193"] = nc.ipv6_assign_mode().rfc4193();
  263. ipv6mode["zt"] = nc.ipv6_assign_mode().zt();
  264. out["ipv6AssignMode"] = ipv6mode;
  265. }
  266. if (nc.assignment_pools_size() > 0) {
  267. nlohmann::json pools = nlohmann::json::array();
  268. for (const auto& p : nc.assignment_pools()) {
  269. nlohmann::json pool;
  270. pool["ipRangeStart"] = p.start_ip();
  271. pool["ipRangeEnd"] = p.end_ip();
  272. pools.push_back(pool);
  273. }
  274. out["assignmentPools"] = pools;
  275. }
  276. if (nc.routes_size() > 0) {
  277. nlohmann::json routes = nlohmann::json::array();
  278. for (const auto& r : nc.routes()) {
  279. nlohmann::json route;
  280. route["target"] = r.target();
  281. if (r.has_via()) {
  282. route["via"] = r.via();
  283. }
  284. routes.push_back(route);
  285. }
  286. out["routes"] = routes;
  287. }
  288. if (nc.has_dns()) {
  289. nlohmann::json dns;
  290. if (nc.dns().nameservers_size() > 0) {
  291. nlohmann::json servers = nlohmann::json::array();
  292. for (const auto& s : nc.dns().nameservers()) {
  293. servers.push_back(s);
  294. }
  295. dns["servers"] = servers;
  296. }
  297. dns["domain"] = nc.dns().domain();
  298. out["dns"] = dns;
  299. }
  300. out["ssoEnabled"] = nc.sso_enabled();
  301. nlohmann::json sso;
  302. if (nc.sso_enabled()) {
  303. sso = nlohmann::json::object();
  304. if (nc.has_sso_client_id()) {
  305. sso["ssoClientId"] = nc.sso_client_id();
  306. }
  307. if (nc.has_sso_authorization_endpoint()) {
  308. sso["ssoAuthorizationEndpoint"] = nc.sso_authorization_endpoint();
  309. }
  310. if (nc.has_sso_issuer()) {
  311. sso["ssoIssuer"] = nc.sso_issuer();
  312. }
  313. if (nc.has_sso_provider()) {
  314. sso["ssoProvider"] = nc.sso_provider();
  315. }
  316. }
  317. out["ssoConfig"] = sso;
  318. return out;
  319. }
  320. nlohmann::json toJson(const pbmessages::MemberChange_Member& mc)
  321. {
  322. nlohmann::json out;
  323. out["id"] = mc.device_id();
  324. out["nwid"] = mc.network_id();
  325. if (mc.has_remote_trace_target()) {
  326. out["remoteTraceTarget"] = mc.remote_trace_target();
  327. }
  328. else {
  329. out["remoteTraceTarget"] = "";
  330. }
  331. out["authorized"] = mc.authorized();
  332. out["activeBridge"] = mc.active_bridge();
  333. auto ipAssignments = mc.ip_assignments();
  334. if (ipAssignments.size() > 0) {
  335. nlohmann::json assignments = nlohmann::json::array();
  336. for (const auto& ip : ipAssignments) {
  337. assignments.push_back(ip);
  338. }
  339. out["ipAssignments"] = assignments;
  340. }
  341. out["noAutoAssignIps"] = mc.no_auto_assign_ips();
  342. out["ssoExempt"] = mc.sso_exepmt();
  343. out["authenticationExpiryTime"] = mc.auth_expiry_time();
  344. out["capabilities"] = OSUtils::jsonParse(mc.capabilities());
  345. out["creationTime"] = mc.creation_time();
  346. out["identity"] = mc.identity();
  347. out["lastAuthorizedTime"] = mc.last_authorized_time();
  348. out["lastDeauthorizedTime"] = mc.last_deauthorized_time();
  349. out["remoteTraceLevel"] = mc.remote_trace_level();
  350. out["revision"] = mc.revision();
  351. out["tags"] = OSUtils::jsonParse(mc.tags());
  352. out["versionMajor"] = mc.version_major();
  353. out["versionMinor"] = mc.version_minor();
  354. out["versionRev"] = mc.version_rev();
  355. out["versionProtocol"] = mc.version_protocol();
  356. return out;
  357. }
  358. } // namespace ZeroTier
  359. #endif // ZT_CONTROLLER_USE_LIBPQ