关键词搜索

源码搜索 ×
×

漫话Redis源码之四十二

发布2022-01-02浏览407次

详情内容

这里的代码主要是服务端相关的,处理来自客户端的一些请求:

  1. #include "server.h"
  2. /* ================================ MULTI/EXEC ============================== */
  3. /* Client state initialization for MULTI/EXEC */
  4. void initClientMultiState(client *c) {
  5. c->mstate.commands = NULL;
  6. c->mstate.count = 0;
  7. c->mstate.cmd_flags = 0;
  8. c->mstate.cmd_inv_flags = 0;
  9. }
  10. /* Release all the resources associated with MULTI/EXEC state */
  11. void freeClientMultiState(client *c) {
  12. int j;
  13. for (j = 0; j < c->mstate.count; j++) {
  14. int i;
  15. multiCmd *mc = c->mstate.commands+j;
  16. for (i = 0; i < mc->argc; i++)
  17. decrRefCount(mc->argv[i]);
  18. zfree(mc->argv);
  19. }
  20. zfree(c->mstate.commands);
  21. }
  22. /* Add a new command into the MULTI commands queue */
  23. void queueMultiCommand(client *c) {
  24. multiCmd *mc;
  25. int j;
  26. /* No sense to waste memory if the transaction is already aborted.
  27. * this is useful in case client sends these in a pipeline, or doesn't
  28. * bother to read previous responses and didn't notice the multi was already
  29. * aborted. */
  30. if (c->flags & CLIENT_DIRTY_EXEC)
  31. return;
  32. c->mstate.commands = zrealloc(c->mstate.commands,
  33. sizeof(multiCmd)*(c->mstate.count+1));
  34. mc = c->mstate.commands+c->mstate.count;
  35. mc->cmd = c->cmd;
  36. mc->argc = c->argc;
  37. mc->argv = zmalloc(sizeof(robj*)*c->argc);
  38. memcpy(mc->argv,c->argv,sizeof(robj*)*c->argc);
  39. for (j = 0; j < c->argc; j++)
  40. incrRefCount(mc->argv[j]);
  41. c->mstate.count++;
  42. c->mstate.cmd_flags |= c->cmd->flags;
  43. c->mstate.cmd_inv_flags |= ~c->cmd->flags;
  44. }
  45. void discardTransaction(client *c) {
  46. freeClientMultiState(c);
  47. initClientMultiState(c);
  48. c->flags &= ~(CLIENT_MULTI|CLIENT_DIRTY_CAS|CLIENT_DIRTY_EXEC);
  49. unwatchAllKeys(c);
  50. }
  51. /* Flag the transaction as DIRTY_EXEC so that EXEC will fail.
  52. * Should be called every time there is an error while queueing a command. */
  53. void flagTransaction(client *c) {
  54. if (c->flags & CLIENT_MULTI)
  55. c->flags |= CLIENT_DIRTY_EXEC;
  56. }
  57. void multiCommand(client *c) {
  58. if (c->flags & CLIENT_MULTI) {
  59. addReplyError(c,"MULTI calls can not be nested");
  60. return;
  61. }
  62. c->flags |= CLIENT_MULTI;
  63. addReply(c,shared.ok);
  64. }
  65. void discardCommand(client *c) {
  66. if (!(c->flags & CLIENT_MULTI)) {
  67. addReplyError(c,"DISCARD without MULTI");
  68. return;
  69. }
  70. discardTransaction(c);
  71. addReply(c,shared.ok);
  72. }
  73. void beforePropagateMulti() {
  74. /* Propagating MULTI */
  75. serverAssert(!server.propagate_in_transaction);
  76. server.propagate_in_transaction = 1;
  77. }
  78. void afterPropagateExec() {
  79. /* Propagating EXEC */
  80. serverAssert(server.propagate_in_transaction == 1);
  81. server.propagate_in_transaction = 0;
  82. }
  83. /* Send a MULTI command to all the slaves and AOF file. Check the execCommand
  84. * implementation for more information. */
  85. void execCommandPropagateMulti(int dbid) {
  86. beforePropagateMulti();
  87. propagate(server.multiCommand,dbid,&shared.multi,1,
  88. PROPAGATE_AOF|PROPAGATE_REPL);
  89. }
  90. void execCommandPropagateExec(int dbid) {
  91. propagate(server.execCommand,dbid,&shared.exec,1,
  92. PROPAGATE_AOF|PROPAGATE_REPL);
  93. afterPropagateExec();
  94. }
  95. /* Aborts a transaction, with a specific error message.
  96. * The transaction is always aborted with -EXECABORT so that the client knows
  97. * the server exited the multi state, but the actual reason for the abort is
  98. * included too.
  99. * Note: 'error' may or may not end with \r\n. see addReplyErrorFormat. */
  100. void execCommandAbort(client *c, sds error) {
  101. discardTransaction(c);
  102. if (error[0] == '-') error++;
  103. addReplyErrorFormat(c, "-EXECABORT Transaction discarded because of: %s", error);
  104. /* Send EXEC to clients waiting data from MONITOR. We did send a MULTI
  105. * already, and didn't send any of the queued commands, now we'll just send
  106. * EXEC so it is clear that the transaction is over. */
  107. replicationFeedMonitors(c,server.monitors,c->db->id,c->argv,c->argc);
  108. }
  109. void execCommand(client *c) {
  110. int j;
  111. robj **orig_argv;
  112. int orig_argc;
  113. struct redisCommand *orig_cmd;
  114. int was_master = server.masterhost == NULL;
  115. if (!(c->flags & CLIENT_MULTI)) {
  116. addReplyError(c,"EXEC without MULTI");
  117. return;
  118. }
  119. /* EXEC with expired watched key is disallowed*/
  120. if (isWatchedKeyExpired(c)) {
  121. c->flags |= (CLIENT_DIRTY_CAS);
  122. }
  123. /* Check if we need to abort the EXEC because:
  124. * 1) Some WATCHed key was touched.
  125. * 2) There was a previous error while queueing commands.
  126. * A failed EXEC in the first case returns a multi bulk nil object
  127. * (technically it is not an error but a special behavior), while
  128. * in the second an EXECABORT error is returned. */
  129. if (c->flags & (CLIENT_DIRTY_CAS | CLIENT_DIRTY_EXEC)) {
  130. if (c->flags & CLIENT_DIRTY_EXEC) {
  131. addReplyErrorObject(c, shared.execaborterr);
  132. } else {
  133. addReply(c, shared.nullarray[c->resp]);
  134. }
  135. discardTransaction(c);
  136. return;
  137. }
  138. uint64_t old_flags = c->flags;
  139. /* we do not want to allow blocking commands inside multi */
  140. c->flags |= CLIENT_DENY_BLOCKING;
  141. /* Exec all the queued commands */
  142. unwatchAllKeys(c); /* Unwatch ASAP otherwise we'll waste CPU cycles */
  143. server.in_exec = 1;
  144. orig_argv = c->argv;
  145. orig_argc = c->argc;
  146. orig_cmd = c->cmd;
  147. addReplyArrayLen(c,c->mstate.count);
  148. for (j = 0; j < c->mstate.count; j++) {
  149. c->argc = c->mstate.commands[j].argc;
  150. c->argv = c->mstate.commands[j].argv;
  151. c->cmd = c->mstate.commands[j].cmd;
  152. /* ACL permissions are also checked at the time of execution in case
  153. * they were changed after the commands were queued. */
  154. int acl_errpos;
  155. int acl_retval = ACLCheckAllPerm(c,&acl_errpos);
  156. if (acl_retval != ACL_OK) {
  157. char *reason;
  158. switch (acl_retval) {
  159. case ACL_DENIED_CMD:
  160. reason = "no permission to execute the command or subcommand";
  161. break;
  162. case ACL_DENIED_KEY:
  163. reason = "no permission to touch the specified keys";
  164. break;
  165. case ACL_DENIED_CHANNEL:
  166. reason = "no permission to access one of the channels used "
  167. "as arguments";
  168. break;
  169. default:
  170. reason = "no permission";
  171. break;
  172. }
  173. addACLLogEntry(c,acl_retval,acl_errpos,NULL);
  174. addReplyErrorFormat(c,
  175. "-NOPERM ACLs rules changed between the moment the "
  176. "transaction was accumulated and the EXEC call. "
  177. "This command is no longer allowed for the "
  178. "following reason: %s", reason);
  179. } else {
  180. call(c,server.loading ? CMD_CALL_NONE : CMD_CALL_FULL);
  181. serverAssert((c->flags & CLIENT_BLOCKED) == 0);
  182. }
  183. /* Commands may alter argc/argv, restore mstate. */
  184. c->mstate.commands[j].argc = c->argc;
  185. c->mstate.commands[j].argv = c->argv;
  186. c->mstate.commands[j].cmd = c->cmd;
  187. }
  188. // restore old DENY_BLOCKING value
  189. if (!(old_flags & CLIENT_DENY_BLOCKING))
  190. c->flags &= ~CLIENT_DENY_BLOCKING;
  191. c->argv = orig_argv;
  192. c->argc = orig_argc;
  193. c->cmd = orig_cmd;
  194. discardTransaction(c);
  195. /* Make sure the EXEC command will be propagated as well if MULTI
  196. * was already propagated. */
  197. if (server.propagate_in_transaction) {
  198. int is_master = server.masterhost == NULL;
  199. server.dirty++;
  200. /* If inside the MULTI/EXEC block this instance was suddenly
  201. * switched from master to slave (using the SLAVEOF command), the
  202. * initial MULTI was propagated into the replication backlog, but the
  203. * rest was not. We need to make sure to at least terminate the
  204. * backlog with the final EXEC. */
  205. if (server.repl_backlog && was_master && !is_master) {
  206. char *execcmd = "*1\r\n$4\r\nEXEC\r\n";
  207. feedReplicationBacklog(execcmd,strlen(execcmd));
  208. }
  209. afterPropagateExec();
  210. }
  211. server.in_exec = 0;
  212. }
  213. /* ===================== WATCH (CAS alike for MULTI/EXEC) ===================
  214. *
  215. * The implementation uses a per-DB hash table mapping keys to list of clients
  216. * WATCHing those keys, so that given a key that is going to be modified
  217. * we can mark all the associated clients as dirty.
  218. *
  219. * Also every client contains a list of WATCHed keys so that's possible to
  220. * un-watch such keys when the client is freed or when UNWATCH is called. */
  221. /* In the client->watched_keys list we need to use watchedKey structures
  222. * as in order to identify a key in Redis we need both the key name and the
  223. * DB */
  224. typedef struct watchedKey {
  225. robj *key;
  226. redisDb *db;
  227. } watchedKey;
  228. /* Watch for the specified key */
  229. void watchForKey(client *c, robj *key) {
  230. list *clients = NULL;
  231. listIter li;
  232. listNode *ln;
  233. watchedKey *wk;
  234. /* Check if we are already watching for this key */
  235. listRewind(c->watched_keys,&li);
  236. while((ln = listNext(&li))) {
  237. wk = listNodeValue(ln);
  238. if (wk->db == c->db && equalStringObjects(key,wk->key))
  239. return; /* Key already watched */
  240. }
  241. /* This key is not already watched in this DB. Let's add it */
  242. clients = dictFetchValue(c->db->watched_keys,key);
  243. if (!clients) {
  244. clients = listCreate();
  245. dictAdd(c->db->watched_keys,key,clients);
  246. incrRefCount(key);
  247. }
  248. listAddNodeTail(clients,c);
  249. /* Add the new key to the list of keys watched by this client */
  250. wk = zmalloc(sizeof(*wk));
  251. wk->key = key;
  252. wk->db = c->db;
  253. incrRefCount(key);
  254. listAddNodeTail(c->watched_keys,wk);
  255. }
  256. /* Unwatch all the keys watched by this client. To clean the EXEC dirty
  257. * flag is up to the caller. */
  258. void unwatchAllKeys(client *c) {
  259. listIter li;
  260. listNode *ln;
  261. if (listLength(c->watched_keys) == 0) return;
  262. listRewind(c->watched_keys,&li);
  263. while((ln = listNext(&li))) {
  264. list *clients;
  265. watchedKey *wk;
  266. /* Lookup the watched key -> clients list and remove the client
  267. * from the list */
  268. wk = listNodeValue(ln);
  269. clients = dictFetchValue(wk->db->watched_keys, wk->key);
  270. serverAssertWithInfo(c,NULL,clients != NULL);
  271. listDelNode(clients,listSearchKey(clients,c));
  272. /* Kill the entry at all if this was the only client */
  273. if (listLength(clients) == 0)
  274. dictDelete(wk->db->watched_keys, wk->key);
  275. /* Remove this watched key from the client->watched list */
  276. listDelNode(c->watched_keys,ln);
  277. decrRefCount(wk->key);
  278. zfree(wk);
  279. }
  280. }
  281. /* iterates over the watched_keys list and
  282. * look for an expired key . */
  283. int isWatchedKeyExpired(client *c) {
  284. listIter li;
  285. listNode *ln;
  286. watchedKey *wk;
  287. if (listLength(c->watched_keys) == 0) return 0;
  288. listRewind(c->watched_keys,&li);
  289. while ((ln = listNext(&li))) {
  290. wk = listNodeValue(ln);
  291. if (keyIsExpired(wk->db, wk->key)) return 1;
  292. }
  293. return 0;
  294. }
  295. /* "Touch" a key, so that if this key is being WATCHed by some client the
  296. * next EXEC will fail. */
  297. void touchWatchedKey(redisDb *db, robj *key) {
  298. list *clients;
  299. listIter li;
  300. listNode *ln;
  301. if (dictSize(db->watched_keys) == 0) return;
  302. clients = dictFetchValue(db->watched_keys, key);
  303. if (!clients) return;
  304. /* Mark all the clients watching this key as CLIENT_DIRTY_CAS */
  305. /* Check if we are already watching for this key */
  306. listRewind(clients,&li);
  307. while((ln = listNext(&li))) {
  308. client *c = listNodeValue(ln);
  309. c->flags |= CLIENT_DIRTY_CAS;
  310. }
  311. }
  312. /* Set CLIENT_DIRTY_CAS to all clients of DB when DB is dirty.
  313. * It may happen in the following situations:
  314. * FLUSHDB, FLUSHALL, SWAPDB
  315. *
  316. * replaced_with: for SWAPDB, the WATCH should be invalidated if
  317. * the key exists in either of them, and skipped only if it
  318. * doesn't exist in both. */
  319. void touchAllWatchedKeysInDb(redisDb *emptied, redisDb *replaced_with) {
  320. listIter li;
  321. listNode *ln;
  322. dictEntry *de;
  323. if (dictSize(emptied->watched_keys) == 0) return;
  324. dictIterator *di = dictGetSafeIterator(emptied->watched_keys);
  325. while((de = dictNext(di)) != NULL) {
  326. robj *key = dictGetKey(de);
  327. list *clients = dictGetVal(de);
  328. if (!clients) continue;
  329. listRewind(clients,&li);
  330. while((ln = listNext(&li))) {
  331. client *c = listNodeValue(ln);
  332. if (dictFind(emptied->dict, key->ptr)) {
  333. c->flags |= CLIENT_DIRTY_CAS;
  334. } else if (replaced_with && dictFind(replaced_with->dict, key->ptr)) {
  335. c->flags |= CLIENT_DIRTY_CAS;
  336. }
  337. }
  338. }
  339. dictReleaseIterator(di);
  340. }
  341. void watchCommand(client *c) {
  342. int j;
  343. if (c->flags & CLIENT_MULTI) {
  344. addReplyError(c,"WATCH inside MULTI is not allowed");
  345. return;
  346. }
  347. for (j = 1; j < c->argc; j++)
  348. watchForKey(c,c->argv[j]);
  349. addReply(c,shared.ok);
  350. }
  351. void unwatchCommand(client *c) {
  352. unwatchAllKeys(c);
  353. c->flags &= (~CLIENT_DIRTY_CAS);
  354. addReply(c,shared.ok);
  355. }

相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载