You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

redis_pool.c 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. /*-
  2. * Copyright 2016 Vsevolod Stakhov
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "config.h"
  17. #include "contrib/libev/ev.h"
  18. #include "redis_pool.h"
  19. #include "cfg_file.h"
  20. #include "contrib/hiredis/hiredis.h"
  21. #include "contrib/hiredis/async.h"
  22. #include "contrib/hiredis/adapters/libev.h"
  23. #include "cryptobox.h"
  24. #include "logger.h"
  25. struct rspamd_redis_pool_elt;
  26. enum rspamd_redis_pool_connection_state {
  27. RSPAMD_REDIS_POOL_CONN_INACTIVE = 0,
  28. RSPAMD_REDIS_POOL_CONN_ACTIVE,
  29. RSPAMD_REDIS_POOL_CONN_FINALISING
  30. };
  31. struct rspamd_redis_pool_connection {
  32. struct redisAsyncContext *ctx;
  33. struct rspamd_redis_pool_elt *elt;
  34. GList *entry;
  35. ev_timer timeout;
  36. enum rspamd_redis_pool_connection_state state;
  37. gchar tag[MEMPOOL_UID_LEN];
  38. ref_entry_t ref;
  39. };
  40. struct rspamd_redis_pool_elt {
  41. struct rspamd_redis_pool *pool;
  42. guint64 key;
  43. GQueue *active;
  44. GQueue *inactive;
  45. };
  46. struct rspamd_redis_pool {
  47. struct ev_loop *event_loop;
  48. struct rspamd_config *cfg;
  49. GHashTable *elts_by_key;
  50. GHashTable *elts_by_ctx;
  51. gdouble timeout;
  52. guint max_conns;
  53. };
  54. static const gdouble default_timeout = 10.0;
  55. static const guint default_max_conns = 100;
  56. #define msg_err_rpool(...) rspamd_default_log_function (G_LOG_LEVEL_CRITICAL, \
  57. "redis_pool", conn->tag, \
  58. G_STRFUNC, \
  59. __VA_ARGS__)
  60. #define msg_warn_rpool(...) rspamd_default_log_function (G_LOG_LEVEL_WARNING, \
  61. "redis_pool", conn->tag, \
  62. G_STRFUNC, \
  63. __VA_ARGS__)
  64. #define msg_info_rpool(...) rspamd_default_log_function (G_LOG_LEVEL_INFO, \
  65. "redis_pool", conn->tag, \
  66. G_STRFUNC, \
  67. __VA_ARGS__)
  68. #define msg_debug_rpool(...) rspamd_conditional_debug_fast (NULL, NULL, \
  69. rspamd_redis_pool_log_id, "redis_pool", conn->tag, \
  70. G_STRFUNC, \
  71. __VA_ARGS__)
  72. INIT_LOG_MODULE(redis_pool)
  73. static inline guint64
  74. rspamd_redis_pool_get_key (const gchar *db, const gchar *password,
  75. const char *ip, int port)
  76. {
  77. rspamd_cryptobox_fast_hash_state_t st;
  78. rspamd_cryptobox_fast_hash_init (&st, rspamd_hash_seed ());
  79. if (db) {
  80. rspamd_cryptobox_fast_hash_update (&st, db, strlen (db));
  81. }
  82. if (password) {
  83. rspamd_cryptobox_fast_hash_update (&st, password, strlen (password));
  84. }
  85. rspamd_cryptobox_fast_hash_update (&st, ip, strlen (ip));
  86. rspamd_cryptobox_fast_hash_update (&st, &port, sizeof (port));
  87. return rspamd_cryptobox_fast_hash_final (&st);
  88. }
  89. static void
  90. rspamd_redis_pool_conn_dtor (struct rspamd_redis_pool_connection *conn)
  91. {
  92. if (conn->state == RSPAMD_REDIS_POOL_CONN_ACTIVE) {
  93. msg_debug_rpool ("active connection removed");
  94. if (conn->ctx) {
  95. if (!(conn->ctx->c.flags & REDIS_FREEING)) {
  96. redisAsyncContext *ac = conn->ctx;
  97. conn->ctx = NULL;
  98. g_hash_table_remove (conn->elt->pool->elts_by_ctx, ac);
  99. ac->onDisconnect = NULL;
  100. redisAsyncFree (ac);
  101. }
  102. }
  103. if (conn->entry) {
  104. g_queue_unlink (conn->elt->active, conn->entry);
  105. }
  106. }
  107. else {
  108. msg_debug_rpool ("inactive connection removed");
  109. ev_timer_stop (conn->elt->pool->event_loop, &conn->timeout);
  110. if (conn->ctx && !(conn->ctx->c.flags & REDIS_FREEING)) {
  111. redisAsyncContext *ac = conn->ctx;
  112. /* To prevent on_disconnect here */
  113. conn->state = RSPAMD_REDIS_POOL_CONN_FINALISING;
  114. g_hash_table_remove (conn->elt->pool->elts_by_ctx, ac);
  115. conn->ctx = NULL;
  116. ac->onDisconnect = NULL;
  117. redisAsyncFree (ac);
  118. }
  119. if (conn->entry) {
  120. g_queue_unlink (conn->elt->inactive, conn->entry);
  121. }
  122. }
  123. if (conn->entry) {
  124. g_list_free (conn->entry);
  125. }
  126. g_free (conn);
  127. }
  128. static void
  129. rspamd_redis_pool_elt_dtor (gpointer p)
  130. {
  131. GList *cur;
  132. struct rspamd_redis_pool_elt *elt = p;
  133. struct rspamd_redis_pool_connection *c;
  134. for (cur = elt->active->head; cur != NULL; cur = g_list_next (cur)) {
  135. c = cur->data;
  136. c->entry = NULL;
  137. REF_RELEASE (c);
  138. }
  139. for (cur = elt->inactive->head; cur != NULL; cur = g_list_next (cur)) {
  140. c = cur->data;
  141. c->entry = NULL;
  142. REF_RELEASE (c);
  143. }
  144. g_queue_free (elt->active);
  145. g_queue_free (elt->inactive);
  146. g_free (elt);
  147. }
  148. static void
  149. rspamd_redis_on_quit (redisAsyncContext *c, gpointer r, gpointer priv)
  150. {
  151. struct rspamd_redis_pool_connection *conn =
  152. (struct rspamd_redis_pool_connection *)priv;
  153. msg_debug_rpool ("quit command reply for the connection %p, refcount: %d",
  154. conn->ctx, conn->ref.refcount);
  155. /*
  156. * We now schedule timer to enforce removal after callback is executed
  157. * to prevent races. But actually, the connection will likely be freed by
  158. * hiredis itself. It is quite brain damaged logic but it is better to
  159. * deal with it... Dtor will definitely stop this timer.
  160. */
  161. conn->timeout.repeat = 0.1;
  162. ev_timer_again (conn->elt->pool->event_loop, &conn->timeout);
  163. }
  164. static void
  165. rspamd_redis_conn_timeout (EV_P_ ev_timer *w, int revents)
  166. {
  167. struct rspamd_redis_pool_connection *conn =
  168. (struct rspamd_redis_pool_connection *)w->data;
  169. g_assert (conn->state != RSPAMD_REDIS_POOL_CONN_ACTIVE);
  170. if (conn->state == RSPAMD_REDIS_POOL_CONN_INACTIVE) {
  171. msg_debug_rpool ("scheduled soft removal of connection %p, refcount: %d",
  172. conn->ctx, conn->ref.refcount);
  173. redisAsyncCommand (conn->ctx, rspamd_redis_on_quit, conn, "QUIT");
  174. conn->state = RSPAMD_REDIS_POOL_CONN_FINALISING;
  175. ev_timer_again (EV_A_ w);
  176. /* Prevent reusing */
  177. if (conn->entry) {
  178. g_queue_unlink (conn->elt->inactive, conn->entry);
  179. conn->entry = NULL;
  180. }
  181. }
  182. else {
  183. /* Finalising by timeout */
  184. msg_debug_rpool ("final removal of connection %p, refcount: %d",
  185. conn->ctx, conn->ref.refcount);
  186. REF_RELEASE (conn);
  187. }
  188. }
  189. static void
  190. rspamd_redis_pool_schedule_timeout (struct rspamd_redis_pool_connection *conn)
  191. {
  192. gdouble real_timeout;
  193. guint active_elts;
  194. active_elts = g_queue_get_length (conn->elt->active);
  195. if (active_elts > conn->elt->pool->max_conns) {
  196. real_timeout = conn->elt->pool->timeout / 2.0;
  197. real_timeout = rspamd_time_jitter (real_timeout, real_timeout / 4.0);
  198. }
  199. else {
  200. real_timeout = conn->elt->pool->timeout;
  201. real_timeout = rspamd_time_jitter (real_timeout, real_timeout / 2.0);
  202. }
  203. msg_debug_rpool ("scheduled connection %p cleanup in %.1f seconds",
  204. conn->ctx, real_timeout);
  205. conn->timeout.data = conn;
  206. ev_timer_init (&conn->timeout,
  207. rspamd_redis_conn_timeout,
  208. real_timeout, real_timeout / 2.0);
  209. ev_timer_start (conn->elt->pool->event_loop, &conn->timeout);
  210. }
  211. static void
  212. rspamd_redis_pool_on_disconnect (const struct redisAsyncContext *ac, int status,
  213. void *ud)
  214. {
  215. struct rspamd_redis_pool_connection *conn = ud;
  216. /*
  217. * Here, we know that redis itself will free this connection
  218. * so, we need to do something very clever about it
  219. */
  220. if (conn->state != RSPAMD_REDIS_POOL_CONN_ACTIVE) {
  221. /* Do nothing for active connections as it is already handled somewhere */
  222. if (conn->ctx) {
  223. msg_debug_rpool ("inactive connection terminated: %s, refs: %d",
  224. conn->ctx->errstr, conn->ref.refcount);
  225. }
  226. REF_RELEASE (conn);
  227. }
  228. }
  229. static struct rspamd_redis_pool_connection *
  230. rspamd_redis_pool_new_connection (struct rspamd_redis_pool *pool,
  231. struct rspamd_redis_pool_elt *elt,
  232. const char *db,
  233. const char *password,
  234. const char *ip,
  235. gint port)
  236. {
  237. struct rspamd_redis_pool_connection *conn;
  238. struct redisAsyncContext *ctx;
  239. if (*ip == '/' || *ip == '.') {
  240. ctx = redisAsyncConnectUnix (ip);
  241. }
  242. else {
  243. ctx = redisAsyncConnect (ip, port);
  244. }
  245. if (ctx) {
  246. if (ctx->err != REDIS_OK) {
  247. msg_err ("cannot connect to redis %s (port %d): %s", ip, port, ctx->errstr);
  248. redisAsyncFree (ctx);
  249. return NULL;
  250. }
  251. else {
  252. conn = g_malloc0 (sizeof (*conn));
  253. conn->entry = g_list_prepend (NULL, conn);
  254. conn->elt = elt;
  255. conn->state = RSPAMD_REDIS_POOL_CONN_ACTIVE;
  256. g_hash_table_insert (elt->pool->elts_by_ctx, ctx, conn);
  257. g_queue_push_head_link (elt->active, conn->entry);
  258. conn->ctx = ctx;
  259. rspamd_random_hex (conn->tag, sizeof (conn->tag));
  260. REF_INIT_RETAIN (conn, rspamd_redis_pool_conn_dtor);
  261. msg_debug_rpool ("created new connection to %s:%d: %p", ip, port, ctx);
  262. redisLibevAttach (pool->event_loop, ctx);
  263. redisAsyncSetDisconnectCallback (ctx, rspamd_redis_pool_on_disconnect,
  264. conn);
  265. if (password) {
  266. redisAsyncCommand (ctx, NULL, NULL,
  267. "AUTH %s", password);
  268. }
  269. if (db) {
  270. redisAsyncCommand (ctx, NULL, NULL,
  271. "SELECT %s", db);
  272. }
  273. }
  274. return conn;
  275. }
  276. return NULL;
  277. }
  278. static struct rspamd_redis_pool_elt *
  279. rspamd_redis_pool_new_elt (struct rspamd_redis_pool *pool)
  280. {
  281. struct rspamd_redis_pool_elt *elt;
  282. elt = g_malloc0 (sizeof (*elt));
  283. elt->active = g_queue_new ();
  284. elt->inactive = g_queue_new ();
  285. elt->pool = pool;
  286. return elt;
  287. }
  288. struct rspamd_redis_pool *
  289. rspamd_redis_pool_init (void)
  290. {
  291. struct rspamd_redis_pool *pool;
  292. pool = g_malloc0 (sizeof (*pool));
  293. pool->elts_by_key = g_hash_table_new_full (g_int64_hash, g_int64_equal,
  294. NULL, rspamd_redis_pool_elt_dtor);
  295. pool->elts_by_ctx = g_hash_table_new (g_direct_hash, g_direct_equal);
  296. return pool;
  297. }
  298. void
  299. rspamd_redis_pool_config (struct rspamd_redis_pool *pool,
  300. struct rspamd_config *cfg,
  301. struct ev_loop *ev_base)
  302. {
  303. g_assert (pool != NULL);
  304. pool->event_loop = ev_base;
  305. pool->cfg = cfg;
  306. pool->timeout = default_timeout;
  307. pool->max_conns = default_max_conns;
  308. }
  309. struct redisAsyncContext*
  310. rspamd_redis_pool_connect (struct rspamd_redis_pool *pool,
  311. const gchar *db, const gchar *password,
  312. const char *ip, int port)
  313. {
  314. guint64 key;
  315. struct rspamd_redis_pool_elt *elt;
  316. GList *conn_entry;
  317. struct rspamd_redis_pool_connection *conn;
  318. g_assert (pool != NULL);
  319. g_assert (pool->event_loop != NULL);
  320. g_assert (ip != NULL);
  321. key = rspamd_redis_pool_get_key (db, password, ip, port);
  322. elt = g_hash_table_lookup (pool->elts_by_key, &key);
  323. if (elt) {
  324. if (g_queue_get_length (elt->inactive) > 0) {
  325. conn_entry = g_queue_pop_head_link (elt->inactive);
  326. conn = conn_entry->data;
  327. g_assert (conn->state != RSPAMD_REDIS_POOL_CONN_ACTIVE);
  328. if (conn->ctx->err == REDIS_OK) {
  329. ev_timer_stop (elt->pool->event_loop, &conn->timeout);
  330. conn->state = RSPAMD_REDIS_POOL_CONN_ACTIVE;
  331. g_queue_push_tail_link (elt->active, conn_entry);
  332. msg_debug_rpool ("reused existing connection to %s:%d: %p",
  333. ip, port, conn->ctx);
  334. }
  335. else {
  336. g_list_free (conn->entry);
  337. conn->entry = NULL;
  338. REF_RELEASE (conn);
  339. conn = rspamd_redis_pool_new_connection (pool, elt,
  340. db, password, ip, port);
  341. }
  342. }
  343. else {
  344. /* Need to create connection */
  345. conn = rspamd_redis_pool_new_connection (pool, elt,
  346. db, password, ip, port);
  347. }
  348. }
  349. else {
  350. /* Need to create a pool */
  351. elt = rspamd_redis_pool_new_elt (pool);
  352. elt->key = key;
  353. g_hash_table_insert (pool->elts_by_key, &elt->key, elt);
  354. conn = rspamd_redis_pool_new_connection (pool, elt,
  355. db, password, ip, port);
  356. }
  357. if (!conn) {
  358. return NULL;
  359. }
  360. REF_RETAIN (conn);
  361. return conn->ctx;
  362. }
  363. void
  364. rspamd_redis_pool_release_connection (struct rspamd_redis_pool *pool,
  365. struct redisAsyncContext *ctx, enum rspamd_redis_pool_release_type how)
  366. {
  367. struct rspamd_redis_pool_connection *conn;
  368. g_assert (pool != NULL);
  369. g_assert (ctx != NULL);
  370. conn = g_hash_table_lookup (pool->elts_by_ctx, ctx);
  371. if (conn != NULL) {
  372. g_assert (conn->state == RSPAMD_REDIS_POOL_CONN_ACTIVE);
  373. if (ctx->err != REDIS_OK) {
  374. /* We need to terminate connection forcefully */
  375. msg_debug_rpool ("closed connection %p due to an error", conn->ctx);
  376. REF_RELEASE (conn);
  377. }
  378. else {
  379. if (how == RSPAMD_REDIS_RELEASE_DEFAULT) {
  380. /* Ensure that there are no callbacks attached to this conn */
  381. if (ctx->replies.head == NULL) {
  382. /* Just move it to the inactive queue */
  383. g_queue_unlink (conn->elt->active, conn->entry);
  384. g_queue_push_head_link (conn->elt->inactive, conn->entry);
  385. conn->state = RSPAMD_REDIS_POOL_CONN_INACTIVE;
  386. rspamd_redis_pool_schedule_timeout (conn);
  387. msg_debug_rpool ("mark connection %p inactive", conn->ctx);
  388. }
  389. else {
  390. msg_debug_rpool ("closed connection %p due to callbacks left",
  391. conn->ctx);
  392. REF_RELEASE (conn);
  393. }
  394. }
  395. else {
  396. if (how == RSPAMD_REDIS_RELEASE_FATAL) {
  397. msg_debug_rpool ("closed connection %p due to an fatal termination",
  398. conn->ctx);
  399. }
  400. else {
  401. msg_debug_rpool ("closed connection %p due to explicit termination",
  402. conn->ctx);
  403. }
  404. REF_RELEASE (conn);
  405. }
  406. }
  407. REF_RELEASE (conn);
  408. }
  409. else {
  410. g_assert_not_reached ();
  411. }
  412. }
  413. void
  414. rspamd_redis_pool_destroy (struct rspamd_redis_pool *pool)
  415. {
  416. struct rspamd_redis_pool_elt *elt;
  417. GHashTableIter it;
  418. gpointer k, v;
  419. g_assert (pool != NULL);
  420. g_hash_table_iter_init (&it, pool->elts_by_key);
  421. while (g_hash_table_iter_next (&it, &k, &v)) {
  422. elt = v;
  423. rspamd_redis_pool_elt_dtor (elt);
  424. g_hash_table_iter_steal (&it);
  425. }
  426. g_hash_table_unref (pool->elts_by_ctx);
  427. g_hash_table_unref (pool->elts_by_key);
  428. g_free (pool);
  429. }
  430. const gchar*
  431. rspamd_redis_type_to_string (int type)
  432. {
  433. const gchar *ret = "unknown";
  434. switch (type) {
  435. case REDIS_REPLY_STRING:
  436. ret = "string";
  437. break;
  438. case REDIS_REPLY_ARRAY:
  439. ret = "array";
  440. break;
  441. case REDIS_REPLY_INTEGER:
  442. ret = "int";
  443. break;
  444. case REDIS_REPLY_STATUS:
  445. ret = "status";
  446. break;
  447. case REDIS_REPLY_NIL:
  448. ret = "nil";
  449. break;
  450. case REDIS_REPLY_ERROR:
  451. ret = "error";
  452. break;
  453. default:
  454. break;
  455. }
  456. return ret;
  457. }