PostgreSQL.cpp 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2018 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. #ifdef ZT_CONTROLLER_USE_LIBPQ
  19. #include "PostgreSQL.hpp"
  20. #include "EmbeddedNetworkController.hpp"
  21. #include "../version.h"
  22. #include <libpq-fe.h>
  23. using json = nlohmann::json;
  24. namespace {
  25. static const char *_timestr()
  26. {
  27. time_t t = time(0);
  28. char *ts = ctime(&t);
  29. char *p = ts;
  30. if (!p)
  31. return "";
  32. while (*p) {
  33. if (*p == '\n') {
  34. *p = (char)0;
  35. break;
  36. }
  37. ++p;
  38. }
  39. return ts;
  40. }
  41. }
  42. using namespace ZeroTier;
  43. PostgreSQL::PostgreSQL(EmbeddedNetworkController *const nc, const Identity &myId, const char *path)
  44. : DB(nc, myId, path)
  45. , _ready(0)
  46. , _connected(1)
  47. , _run(1)
  48. , _waitNoticePrinted(false)
  49. {
  50. _connString = std::string(path);
  51. _readyLock.lock();
  52. _heartbeatThread = std::thread(&PostgreSQL::heartbeat, this);
  53. _membersDbWatcher = std::thread(&PostgreSQL::membersDbWatcher, this);
  54. _networksDbWatcher = std::thread(&PostgreSQL::networksDbWatcher, this);
  55. for (int i = 0; i < ZT_CONTROLLER_RETHINKDB_COMMIT_THREADS; ++i) {
  56. _commitThread[i] = std::thread(&PostgreSQL::commitThread, this);
  57. }
  58. _onlineNotificationThread = std::thread(&PostgreSQL::onlineNotificationThread, this);
  59. }
  60. PostgreSQL::~PostgreSQL()
  61. {
  62. _run = 0;
  63. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  64. _heartbeatThread.join();
  65. _membersDbWatcher.join();
  66. _networksDbWatcher.join();
  67. for (int i = 0; i < ZT_CONTROLLER_RETHINKDB_COMMIT_THREADS; ++i) {
  68. _commitThread[i].join();
  69. }
  70. _onlineNotificationThread.join();
  71. }
  72. bool PostgreSQL::waitForReady()
  73. {
  74. while (_ready < 2) {
  75. if (!_waitNoticePrinted) {
  76. _waitNoticePrinted = true;
  77. fprintf(stderr, "[%s] NOTICE: %.10llx controller PostgreSQL waiting for initial data download..." ZT_EOL_S, ::_timestr(), (unsigned long long)_myAddress.toInt());
  78. }
  79. _readyLock.lock();
  80. _readyLock.unlock();
  81. }
  82. return true;
  83. }
  84. bool PostgreSQL::isReady()
  85. {
  86. return ((_ready == 2)&&(_connected));
  87. }
  88. void PostgreSQL::save(nlohmann::json *orig, nlohmann::json &record)
  89. {
  90. if (!record.is_object()) {
  91. return;
  92. }
  93. waitForReady();
  94. if (orig) {
  95. if (*orig != record) {
  96. record["revision"] = OSUtils::jsonInt(record["revision"],0ULL) + 1;
  97. _commitQueue.post(new nlohmann::json(record));
  98. }
  99. } else {
  100. record["revision"] = 1;
  101. _commitQueue.post(new nlohmann::json(record));
  102. }
  103. }
  104. void PostgreSQL::eraseNetwork(const uint64_t networkId)
  105. {
  106. char tmp2[24];
  107. waitForReady();
  108. Utils::hex(networkId, tmp2);
  109. json *tmp = new json();
  110. (*tmp)["id"] = tmp2;
  111. (*tmp)["objtype"] = "_delete_network";
  112. _commitQueue.post(tmp);
  113. }
  114. void PostgreSQL::eraseMember(const uint64_t networkId, const uint64_t memberId)
  115. {
  116. char tmp2[24];
  117. json *tmp = new json();
  118. Utils::hex(networkId, tmp2);
  119. (*tmp)["nwid"] = tmp2;
  120. Utils::hex(memberId, tmp2);
  121. (*tmp)["id"] = tmp2;
  122. (*tmp)["objtype"] = "_delete_member";
  123. _commitQueue.post(tmp);
  124. }
  125. void PostgreSQL::nodeIsOnline(const uint64_t networkId, const uint64_t memberId, const InetAddress &physicalAddress)
  126. {
  127. std::lock_guard<std::mutex> l(_lastOnline_l);
  128. std::pair<int64_t, InetAddress> &i = _lastOnline[std::pair<uint64_t,uint64_t>(networkId, memberId)];
  129. i.first = OSUtils::now();
  130. if (physicalAddress) {
  131. i.second = physicalAddress;
  132. }
  133. }
  134. void PostgreSQL::initializeNetworks(PGconn *conn)
  135. {
  136. // TODO: do stuff here
  137. if (++this->_ready == 2) {
  138. if (_waitNoticePrinted) {
  139. fprintf(stderr,"[%s] NOTICE: %.10llx controller RethinkDB data download complete." ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
  140. }
  141. _readyLock.unlock();
  142. }
  143. }
  144. void PostgreSQL::initializeMembers(PGconn *conn)
  145. {
  146. // TODO: do stuff here
  147. if (++this->_ready == 2) {
  148. if (_waitNoticePrinted) {
  149. fprintf(stderr,"[%s] NOTICE: %.10llx controller RethinkDB data download complete." ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
  150. }
  151. _readyLock.unlock();
  152. }
  153. }
  154. void PostgreSQL::heartbeat()
  155. {
  156. char publicId[1024];
  157. char hostnameTmp[1024];
  158. _myId.toString(false,publicId);
  159. if (gethostname(hostnameTmp, sizeof(hostnameTmp))!= 0) {
  160. hostnameTmp[0] = (char)0;
  161. } else {
  162. for (int i = 0; i < sizeof(hostnameTmp); ++i) {
  163. if ((hostnameTmp[i] == '.')||(hostnameTmp[i] == 0)) {
  164. hostnameTmp[i] = (char)0;
  165. break;
  166. }
  167. }
  168. }
  169. const char *controllerId = _myAddressStr.c_str();
  170. const char *publicIdentity = publicId;
  171. const char *hostname = hostnameTmp;
  172. PGconn *conn = PQconnectdb(_path.c_str());
  173. if (PQstatus(conn) == CONNECTION_BAD) {
  174. fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
  175. PQfinish(conn);
  176. exit(1);
  177. }
  178. while (_run == 1) {
  179. if(PQstatus(conn) != CONNECTION_OK) {
  180. PQfinish(conn);
  181. conn = PQconnectdb(_path.c_str());
  182. }
  183. if (conn) {
  184. const char *values[8] = {
  185. controllerId,
  186. hostname,
  187. std::to_string(OSUtils::now()).c_str(),
  188. publicIdentity,
  189. std::to_string(ZEROTIER_ONE_VERSION_MAJOR).c_str(),
  190. std::to_string(ZEROTIER_ONE_VERSION_MINOR).c_str(),
  191. std::to_string(ZEROTIER_ONE_VERSION_REVISION).c_str(),
  192. std::to_string(ZEROTIER_ONE_VERSION_BUILD).c_str()
  193. };
  194. int lengths[8] = {
  195. (int)strlen(values[0]),
  196. (int)strlen(values[1]),
  197. (int)strlen(values[2]),
  198. (int)strlen(values[3]),
  199. (int)strlen(values[4]),
  200. (int)strlen(values[5]),
  201. (int)strlen(values[6]),
  202. (int)strlen(values[7])
  203. };
  204. int binary[8] = {0,0,0,0,0,0,0,0};
  205. PGresult *res = PQexecParams(conn,
  206. "INSERT INTO ztc_controller (id, cluster_host, last_alive, public_identity, v_major, v_minor, v_rev, v_build) "
  207. "VALUES ($1, $2, TO_TIMESTAMP($3::double precision/1000), $4, $5, $6, $7, $8) "
  208. "ON CONFLICT (id) DO UPDATE SET cluster_host = EXCLUDED.cluster_host, last_alive = EXCLUDED.last_alive, "
  209. "public_identity = EXCLUDED.public_identity, v_major = EXCLUDED.v_major, v_minor = EXCLUDED.v_minor, "
  210. "v_rev = EXCLUDED.v_rev, v_build = EXCLUDED.v_rev",
  211. 8, // number of parameters
  212. NULL, // oid field. ignore
  213. values, // values for substitution
  214. lengths, // lengths in bytes of each value
  215. binary, // binary?
  216. 0);
  217. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  218. fprintf(stderr, "Heartbeat Update Failed: %s\n", PQresultErrorMessage(res));
  219. }
  220. PQclear(res);
  221. }
  222. std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  223. }
  224. PQfinish(conn);
  225. conn = NULL;
  226. }
  227. void PostgreSQL::membersDbWatcher()
  228. {
  229. PGconn *conn = PQconnectdb(_path.c_str());
  230. if (PQstatus(conn) == CONNECTION_BAD) {
  231. fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
  232. PQfinish(conn);
  233. exit(1);
  234. }
  235. initializeMembers(conn);
  236. char buf[11] = {0};
  237. std::string cmd = "LISTEN member_" + std::string(_myAddress.toString(buf));
  238. PGresult *res = PQexec(conn, cmd.c_str());
  239. if (!res || PQresultStatus(res) != PGRES_COMMAND_OK) {
  240. fprintf(stderr, "LISTEN command failed: %s\n", PQresultErrorMessage(res));
  241. PQclear(res);
  242. PQfinish(conn);
  243. exit(1);
  244. }
  245. while(_run == 1) {
  246. if (PQstatus(conn) != CONNECTION_OK) {
  247. fprintf(stderr, "ERROR: Member Watcher lost connection to Postgres.");
  248. exit(-1);
  249. }
  250. PGnotify *notify = NULL;
  251. PQconsumeInput(conn);
  252. while ((notify = PQnotifies(conn)) != NULL) {
  253. fprintf(stderr, "ASYNC NOTIFY of '%s' id:%s received\n", notify->relname, notify->extra);
  254. try {
  255. json tmp(json::parse(notify->extra));
  256. json &ov = tmp["old_val"];
  257. json &nv = tmp["new_val"];
  258. json oldConfig, newConfig;
  259. if (ov.is_object()) oldConfig = ov;
  260. if (nv.is_object()) newConfig = nv;
  261. if (oldConfig.is_object() || newConfig.is_object()) {
  262. _memberChanged(oldConfig,newConfig,(this->_ready>=2));
  263. }
  264. } catch (...) {} // ignore bad records
  265. free(notify);
  266. }
  267. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  268. }
  269. PQfinish(conn);
  270. conn = NULL;
  271. }
  272. void PostgreSQL::networksDbWatcher()
  273. {
  274. PGconn *conn = PQconnectdb(_path.c_str());
  275. if (PQstatus(conn) == CONNECTION_BAD) {
  276. fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
  277. PQfinish(conn);
  278. exit(1);
  279. }
  280. initializeNetworks(conn);
  281. char buf[11] = {0};
  282. std::string cmd = "LISTEN network_" + std::string(_myAddress.toString(buf));
  283. PGresult *res = PQexec(conn, cmd.c_str());
  284. if (!res || PQresultStatus(res) != PGRES_COMMAND_OK) {
  285. fprintf(stderr, "LISTEN command failed: %s\n", PQresultErrorMessage(res));
  286. PQclear(res);
  287. PQfinish(conn);
  288. exit(1);
  289. }
  290. while(_run == 1) {
  291. if (PQstatus(conn) != CONNECTION_OK) {
  292. fprintf(stderr, "ERROR: Network Watcher lost connection to Postgres.");
  293. exit(-1);
  294. }
  295. PGnotify *notify = NULL;
  296. PQconsumeInput(conn);
  297. while ((notify = PQnotifies(conn)) != NULL) {
  298. fprintf(stderr, "ASYNC NOTIFY of '%s' id:%s received\n", notify->relname, notify->extra);
  299. try {
  300. json tmp(json::parse(notify->extra));
  301. json &ov = tmp["old_val"];
  302. json &nv = tmp["new_val"];
  303. json oldConfig, newConfig;
  304. if (ov.is_object()) oldConfig = ov;
  305. if (nv.is_object()) newConfig = nv;
  306. if (oldConfig.is_object()||newConfig.is_object()) {
  307. _networkChanged(oldConfig,newConfig,(this->_ready >= 2));
  308. }
  309. } catch (...) {} // ignore bad records
  310. free(notify);
  311. }
  312. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  313. }
  314. PQfinish(conn);
  315. conn = NULL;
  316. }
  317. void PostgreSQL::commitThread()
  318. {
  319. json *config = nullptr;
  320. while(_commitQueue.get(config)&(_run == 1)) {
  321. if (!config) {
  322. continue;
  323. }
  324. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  325. }
  326. }
  327. void PostgreSQL::onlineNotificationThread()
  328. {
  329. _connected = 1;
  330. while (_run == 1) {
  331. std::this_thread::sleep_for(std::chrono::milliseconds(250));
  332. }
  333. }
  334. #endif //ZT_CONTROLLER_USE_LIBPQ