]>
Commit | Line | Data |
---|---|---|
1 | #include "redis.h" | |
2 | ||
3 | #include <fcntl.h> | |
4 | #include <pthread.h> | |
5 | #include <math.h> | |
6 | #include <signal.h> | |
7 | ||
8 | /* dscache.c - Disk store cache for disk store backend. | |
9 | * | |
10 | * When Redis is configured for using disk as backend instead of memory, the | |
11 | * memory is used as a cache, so that recently accessed keys are taken in | |
12 | * memory for fast read and write operations. | |
13 | * | |
14 | * Modified keys are marked to be flushed on disk, and will be flushed | |
15 | * as long as the maxium configured flush time elapsed. | |
16 | * | |
17 | * This file implements the whole caching subsystem and contains further | |
18 | * documentation. */ | |
19 | ||
20 | /* TODO: | |
21 | * | |
22 | * WARNING: most of the following todo items and design issues are no | |
23 | * longer relevant with the new design. Here as a checklist to see if | |
24 | * some old ideas still apply. | |
25 | * | |
26 | * - What happens when an object is destroyed? | |
27 | * | |
28 | * If the object is destroyed since semantically it was deleted or | |
29 | * replaced with something new, we don't care if there was a SAVE | |
30 | * job pending for it. Anyway when the IO JOb will be created we'll get | |
31 | * the pointer of the current value. | |
32 | * | |
33 | * If the object is already a REDIS_IO_SAVEINPROG object, then it is | |
34 | * impossible that we get a decrRefCount() that will reach refcount of zero | |
35 | * since the object is both in the dataset and in the io job entry. | |
36 | * | |
37 | * - What happens with MULTI/EXEC? | |
38 | * | |
39 | * Good question. Without some kind of versioning with a global counter | |
40 | * it is not possible to have trasactions on disk, but they are still | |
41 | * useful since from the point of view of memory and client bugs it is | |
42 | * a protection anyway. Also it's useful for WATCH. | |
43 | * | |
44 | * Btw there is to check what happens when WATCH gets combined to keys | |
45 | * that gets removed from the object cache. Should be save but better | |
46 | * to check. | |
47 | * | |
48 | * - Check if/why INCR will not update the LRU info for the object. | |
49 | * | |
50 | * - Fix/Check the following race condition: a key gets a DEL so there is | |
51 | * a write operation scheduled against this key. Later the same key will | |
52 | * be the argument of a GET, but the write operation was still not | |
53 | * completed (to delete the file). If the GET will be for some reason | |
54 | * a blocking loading (via lookup) we can load the old value on memory. | |
55 | * | |
56 | * This problems can be fixed with negative caching. We can use it | |
57 | * to optimize the system, but also when a key is deleted we mark | |
58 | * it as non existing on disk as well (in a way that this cache | |
59 | * entry can't be evicted, setting time to 0), then we avoid looking at | |
60 | * the disk at all if the key can't be there. When an IO Job complete | |
61 | * a deletion, we set the time of the negative caching to a non zero | |
62 | * value so it will be evicted later. | |
63 | * | |
64 | * Are there other patterns like this where we load stale data? | |
65 | * | |
66 | * Also, make sure that key preloading is ONLY done for keys that are | |
67 | * not marked as cacheKeyDoesNotExist(), otherwise, again, we can load | |
68 | * data from disk that should instead be deleted. | |
69 | * | |
70 | * - dsSet() should use rename(2) in order to avoid corruptions. | |
71 | * | |
72 | * - Don't add a LOAD if there is already a LOADINPROGRESS, or is this | |
73 | * impossible since anyway the io_keys stuff will work as lock? | |
74 | * | |
75 | * - Serialize special encoded things in a raw form. | |
76 | * | |
77 | * - When putting IO read operations on top of the queue, do this only if | |
78 | * the already-on-top operation is not a save or if it is a save that | |
79 | * is scheduled for later execution. If there is a save that is ready to | |
80 | * fire, let's insert the load operation just before the first save that | |
81 | * is scheduled for later exection for instance. | |
82 | * | |
83 | * - Support MULTI/EXEC transactions via a journal file, that is played on | |
84 | * startup to check if there is cleanup to do. This way we can implement | |
85 | * transactions with our simple file based KV store. | |
86 | */ | |
87 | ||
88 | /* Virtual Memory is composed mainly of two subsystems: | |
89 | * - Blocking Virutal Memory | |
90 | * - Threaded Virtual Memory I/O | |
91 | * The two parts are not fully decoupled, but functions are split among two | |
92 | * different sections of the source code (delimited by comments) in order to | |
93 | * make more clear what functionality is about the blocking VM and what about | |
94 | * the threaded (not blocking) VM. | |
95 | * | |
96 | * Redis VM design: | |
97 | * | |
98 | * Redis VM is a blocking VM (one that blocks reading swapped values from | |
99 | * disk into memory when a value swapped out is needed in memory) that is made | |
100 | * unblocking by trying to examine the command argument vector in order to | |
101 | * load in background values that will likely be needed in order to exec | |
102 | * the command. The command is executed only once all the relevant keys | |
103 | * are loaded into memory. | |
104 | * | |
105 | * This basically is almost as simple of a blocking VM, but almost as parallel | |
106 | * as a fully non-blocking VM. | |
107 | */ | |
108 | ||
109 | void spawnIOThread(void); | |
110 | int cacheScheduleIOPushJobs(int flags); | |
111 | int processActiveIOJobs(int max); | |
112 | ||
113 | /* =================== Virtual Memory - Blocking Side ====================== */ | |
114 | ||
115 | void dsInit(void) { | |
116 | int pipefds[2]; | |
117 | size_t stacksize; | |
118 | ||
119 | zmalloc_enable_thread_safeness(); /* we need thread safe zmalloc() */ | |
120 | ||
121 | redisLog(REDIS_NOTICE,"Opening Disk Store: %s", server.ds_path); | |
122 | /* Open Disk Store */ | |
123 | if (dsOpen() != REDIS_OK) { | |
124 | redisLog(REDIS_WARNING,"Fatal error opening disk store. Exiting."); | |
125 | exit(1); | |
126 | }; | |
127 | ||
128 | /* Initialize threaded I/O for Object Cache */ | |
129 | server.io_newjobs = listCreate(); | |
130 | server.io_processing = listCreate(); | |
131 | server.io_processed = listCreate(); | |
132 | server.io_ready_clients = listCreate(); | |
133 | pthread_mutex_init(&server.io_mutex,NULL); | |
134 | pthread_cond_init(&server.io_condvar,NULL); | |
135 | pthread_mutex_init(&server.bgsavethread_mutex,NULL); | |
136 | server.io_active_threads = 0; | |
137 | if (pipe(pipefds) == -1) { | |
138 | redisLog(REDIS_WARNING,"Unable to intialized DS: pipe(2): %s. Exiting." | |
139 | ,strerror(errno)); | |
140 | exit(1); | |
141 | } | |
142 | server.io_ready_pipe_read = pipefds[0]; | |
143 | server.io_ready_pipe_write = pipefds[1]; | |
144 | redisAssert(anetNonBlock(NULL,server.io_ready_pipe_read) != ANET_ERR); | |
145 | /* LZF requires a lot of stack */ | |
146 | pthread_attr_init(&server.io_threads_attr); | |
147 | pthread_attr_getstacksize(&server.io_threads_attr, &stacksize); | |
148 | ||
149 | /* Solaris may report a stacksize of 0, let's set it to 1 otherwise | |
150 | * multiplying it by 2 in the while loop later will not really help ;) */ | |
151 | if (!stacksize) stacksize = 1; | |
152 | ||
153 | while (stacksize < REDIS_THREAD_STACK_SIZE) stacksize *= 2; | |
154 | pthread_attr_setstacksize(&server.io_threads_attr, stacksize); | |
155 | /* Listen for events in the threaded I/O pipe */ | |
156 | if (aeCreateFileEvent(server.el, server.io_ready_pipe_read, AE_READABLE, | |
157 | vmThreadedIOCompletedJob, NULL) == AE_ERR) | |
158 | oom("creating file event"); | |
159 | ||
160 | /* Spawn our I/O thread */ | |
161 | spawnIOThread(); | |
162 | } | |
163 | ||
164 | /* Compute how good candidate the specified object is for eviction. | |
165 | * An higher number means a better candidate. */ | |
166 | double computeObjectSwappability(robj *o) { | |
167 | /* actual age can be >= minage, but not < minage. As we use wrapping | |
168 | * 21 bit clocks with minutes resolution for the LRU. */ | |
169 | return (double) estimateObjectIdleTime(o); | |
170 | } | |
171 | ||
172 | /* Try to free one entry from the diskstore object cache */ | |
173 | int cacheFreeOneEntry(void) { | |
174 | int j, i; | |
175 | struct dictEntry *best = NULL; | |
176 | double best_swappability = 0; | |
177 | redisDb *best_db = NULL; | |
178 | robj *val; | |
179 | sds key; | |
180 | ||
181 | for (j = 0; j < server.dbnum; j++) { | |
182 | redisDb *db = server.db+j; | |
183 | /* Why maxtries is set to 100? | |
184 | * Because this way (usually) we'll find 1 object even if just 1% - 2% | |
185 | * are swappable objects */ | |
186 | int maxtries = 100; | |
187 | ||
188 | for (i = 0; i < 5 && dictSize(db->dict); i++) { | |
189 | dictEntry *de; | |
190 | double swappability; | |
191 | robj keyobj; | |
192 | sds keystr; | |
193 | ||
194 | if (maxtries) maxtries--; | |
195 | de = dictGetRandomKey(db->dict); | |
196 | keystr = dictGetEntryKey(de); | |
197 | val = dictGetEntryVal(de); | |
198 | initStaticStringObject(keyobj,keystr); | |
199 | ||
200 | /* Don't remove objects that are currently target of a | |
201 | * read or write operation. */ | |
202 | if (cacheScheduleIOGetFlags(db,&keyobj) != 0) { | |
203 | if (maxtries) i--; /* don't count this try */ | |
204 | continue; | |
205 | } | |
206 | swappability = computeObjectSwappability(val); | |
207 | if (!best || swappability > best_swappability) { | |
208 | best = de; | |
209 | best_swappability = swappability; | |
210 | best_db = db; | |
211 | } | |
212 | } | |
213 | } | |
214 | if (best == NULL) { | |
215 | /* Was not able to fix a single object... we should check if our | |
216 | * IO queues have stuff in queue, and try to consume the queue | |
217 | * otherwise we'll use an infinite amount of memory if changes to | |
218 | * the dataset are faster than I/O */ | |
219 | if (listLength(server.cache_io_queue) > 0) { | |
220 | redisLog(REDIS_DEBUG,"--- Busy waiting IO to reclaim memory"); | |
221 | cacheScheduleIOPushJobs(REDIS_IO_ASAP); | |
222 | processActiveIOJobs(1); | |
223 | return REDIS_OK; | |
224 | } | |
225 | /* Nothing to free at all... */ | |
226 | return REDIS_ERR; | |
227 | } | |
228 | key = dictGetEntryKey(best); | |
229 | val = dictGetEntryVal(best); | |
230 | ||
231 | redisLog(REDIS_DEBUG,"Key selected for cache eviction: %s swappability:%f", | |
232 | key, best_swappability); | |
233 | ||
234 | /* Delete this key from memory */ | |
235 | { | |
236 | robj *kobj = createStringObject(key,sdslen(key)); | |
237 | dbDelete(best_db,kobj); | |
238 | decrRefCount(kobj); | |
239 | } | |
240 | return REDIS_OK; | |
241 | } | |
242 | ||
243 | /* Return true if it's safe to swap out objects in a given moment. | |
244 | * Basically we don't want to swap objects out while there is a BGSAVE | |
245 | * or a BGAEOREWRITE running in backgroud. */ | |
246 | int dsCanTouchDiskStore(void) { | |
247 | return (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1); | |
248 | } | |
249 | ||
250 | /* ==================== Disk store negative caching ======================== | |
251 | * | |
252 | * When disk store is enabled, we need negative caching, that is, to remember | |
253 | * keys that are for sure *not* on the disk key-value store. | |
254 | * | |
255 | * This is usefuls because without negative caching cache misses will cost us | |
256 | * a disk lookup, even if the same non existing key is accessed again and again. | |
257 | * | |
258 | * With negative caching we remember that the key is not on disk, so if it's | |
259 | * not in memory and we have a negative cache entry, we don't try a disk | |
260 | * access at all. | |
261 | */ | |
262 | ||
263 | /* Returns true if the specified key may exists on disk, that is, we don't | |
264 | * have an entry in our negative cache for this key */ | |
265 | int cacheKeyMayExist(redisDb *db, robj *key) { | |
266 | return dictFind(db->io_negcache,key) == NULL; | |
267 | } | |
268 | ||
269 | /* Set the specified key as an entry that may possibily exist on disk, that is, | |
270 | * remove the negative cache entry for this key if any. */ | |
271 | void cacheSetKeyMayExist(redisDb *db, robj *key) { | |
272 | dictDelete(db->io_negcache,key); | |
273 | } | |
274 | ||
275 | /* Set the specified key as non existing on disk, that is, create a negative | |
276 | * cache entry for this key. */ | |
277 | void cacheSetKeyDoesNotExist(redisDb *db, robj *key) { | |
278 | if (dictReplace(db->io_negcache,key,(void*)time(NULL))) { | |
279 | incrRefCount(key); | |
280 | } | |
281 | } | |
282 | ||
283 | /* Remove one entry from negative cache using approximated LRU. */ | |
284 | int negativeCacheEvictOneEntry(void) { | |
285 | struct dictEntry *de; | |
286 | robj *best = NULL; | |
287 | redisDb *best_db = NULL; | |
288 | time_t time, best_time = 0; | |
289 | int j; | |
290 | ||
291 | for (j = 0; j < server.dbnum; j++) { | |
292 | redisDb *db = server.db+j; | |
293 | int i; | |
294 | ||
295 | if (dictSize(db->io_negcache) == 0) continue; | |
296 | for (i = 0; i < 3; i++) { | |
297 | de = dictGetRandomKey(db->io_negcache); | |
298 | time = (time_t) dictGetEntryVal(de); | |
299 | ||
300 | if (best == NULL || time < best_time) { | |
301 | best = dictGetEntryKey(de); | |
302 | best_db = db; | |
303 | best_time = time; | |
304 | } | |
305 | } | |
306 | } | |
307 | if (best) { | |
308 | dictDelete(best_db->io_negcache,best); | |
309 | return REDIS_OK; | |
310 | } else { | |
311 | return REDIS_ERR; | |
312 | } | |
313 | } | |
314 | ||
315 | /* ================== Disk store cache - Threaded I/O ====================== */ | |
316 | ||
317 | void freeIOJob(iojob *j) { | |
318 | decrRefCount(j->key); | |
319 | /* j->val can be NULL if the job is about deleting the key from disk. */ | |
320 | if (j->val) decrRefCount(j->val); | |
321 | zfree(j); | |
322 | } | |
323 | ||
324 | /* Every time a thread finished a Job, it writes a byte into the write side | |
325 | * of an unix pipe in order to "awake" the main thread, and this function | |
326 | * is called. | |
327 | * | |
328 | * If privdata != NULL the function will try to put more jobs in the queue | |
329 | * of IO jobs to process as more room is made. */ | |
330 | void vmThreadedIOCompletedJob(aeEventLoop *el, int fd, void *privdata, | |
331 | int mask) | |
332 | { | |
333 | char buf[1]; | |
334 | int retval, processed = 0, toprocess = -1; | |
335 | REDIS_NOTUSED(el); | |
336 | REDIS_NOTUSED(mask); | |
337 | ||
338 | /* For every byte we read in the read side of the pipe, there is one | |
339 | * I/O job completed to process. */ | |
340 | while((retval = read(fd,buf,1)) == 1) { | |
341 | iojob *j; | |
342 | listNode *ln; | |
343 | ||
344 | redisLog(REDIS_DEBUG,"Processing I/O completed job"); | |
345 | ||
346 | /* Get the processed element (the oldest one) */ | |
347 | lockThreadedIO(); | |
348 | redisAssert(listLength(server.io_processed) != 0); | |
349 | if (toprocess == -1) { | |
350 | toprocess = (listLength(server.io_processed)*REDIS_MAX_COMPLETED_JOBS_PROCESSED)/100; | |
351 | if (toprocess <= 0) toprocess = 1; | |
352 | } | |
353 | ln = listFirst(server.io_processed); | |
354 | j = ln->value; | |
355 | listDelNode(server.io_processed,ln); | |
356 | unlockThreadedIO(); | |
357 | ||
358 | /* Post process it in the main thread, as there are things we | |
359 | * can do just here to avoid race conditions and/or invasive locks */ | |
360 | redisLog(REDIS_DEBUG,"COMPLETED Job type %s, key: %s", | |
361 | (j->type == REDIS_IOJOB_LOAD) ? "load" : "save", | |
362 | (unsigned char*)j->key->ptr); | |
363 | if (j->type == REDIS_IOJOB_LOAD) { | |
364 | /* Create the key-value pair in the in-memory database */ | |
365 | if (j->val != NULL) { | |
366 | /* Note: it's possible that the key is already in memory | |
367 | * due to a blocking load operation. */ | |
368 | if (dbAdd(j->db,j->key,j->val) == REDIS_OK) { | |
369 | incrRefCount(j->val); | |
370 | if (j->expire != -1) setExpire(j->db,j->key,j->expire); | |
371 | } | |
372 | } else { | |
373 | /* Key not found on disk. If it is also not in memory | |
374 | * as a cached object, nor there is a job writing it | |
375 | * in background, we are sure the key does not exist | |
376 | * currently. | |
377 | * | |
378 | * So we set a negative cache entry avoiding that the | |
379 | * resumed client will block load what does not exist... */ | |
380 | if (dictFind(j->db->dict,j->key->ptr) == NULL && | |
381 | (cacheScheduleIOGetFlags(j->db,j->key) & | |
382 | (REDIS_IO_SAVE|REDIS_IO_SAVEINPROG)) == 0) | |
383 | { | |
384 | cacheSetKeyDoesNotExist(j->db,j->key); | |
385 | } | |
386 | } | |
387 | cacheScheduleIODelFlag(j->db,j->key,REDIS_IO_LOADINPROG); | |
388 | handleClientsBlockedOnSwappedKey(j->db,j->key); | |
389 | freeIOJob(j); | |
390 | } else if (j->type == REDIS_IOJOB_SAVE) { | |
391 | cacheScheduleIODelFlag(j->db,j->key,REDIS_IO_SAVEINPROG); | |
392 | freeIOJob(j); | |
393 | } | |
394 | processed++; | |
395 | if (privdata != NULL) cacheScheduleIOPushJobs(0); | |
396 | if (processed == toprocess) return; | |
397 | } | |
398 | if (retval < 0 && errno != EAGAIN) { | |
399 | redisLog(REDIS_WARNING, | |
400 | "WARNING: read(2) error in vmThreadedIOCompletedJob() %s", | |
401 | strerror(errno)); | |
402 | } | |
403 | } | |
404 | ||
405 | void lockThreadedIO(void) { | |
406 | pthread_mutex_lock(&server.io_mutex); | |
407 | } | |
408 | ||
409 | void unlockThreadedIO(void) { | |
410 | pthread_mutex_unlock(&server.io_mutex); | |
411 | } | |
412 | ||
413 | void *IOThreadEntryPoint(void *arg) { | |
414 | iojob *j; | |
415 | listNode *ln; | |
416 | REDIS_NOTUSED(arg); | |
417 | long long start; | |
418 | ||
419 | pthread_detach(pthread_self()); | |
420 | lockThreadedIO(); | |
421 | while(1) { | |
422 | /* Get a new job to process */ | |
423 | if (listLength(server.io_newjobs) == 0) { | |
424 | /* Wait for more work to do */ | |
425 | redisLog(REDIS_DEBUG,"[T] wait for signal"); | |
426 | pthread_cond_wait(&server.io_condvar,&server.io_mutex); | |
427 | redisLog(REDIS_DEBUG,"[T] signal received"); | |
428 | continue; | |
429 | } | |
430 | start = ustime(); | |
431 | redisLog(REDIS_DEBUG,"[T] %ld IO jobs to process", | |
432 | listLength(server.io_newjobs)); | |
433 | ln = listFirst(server.io_newjobs); | |
434 | j = ln->value; | |
435 | listDelNode(server.io_newjobs,ln); | |
436 | /* Add the job in the processing queue */ | |
437 | listAddNodeTail(server.io_processing,j); | |
438 | ln = listLast(server.io_processing); /* We use ln later to remove it */ | |
439 | unlockThreadedIO(); | |
440 | ||
441 | redisLog(REDIS_DEBUG,"[T] %ld: new job type %s: %p about key '%s'", | |
442 | (long) pthread_self(), | |
443 | (j->type == REDIS_IOJOB_LOAD) ? "load" : "save", | |
444 | (void*)j, (char*)j->key->ptr); | |
445 | ||
446 | /* Process the Job */ | |
447 | if (j->type == REDIS_IOJOB_LOAD) { | |
448 | time_t expire; | |
449 | ||
450 | j->val = dsGet(j->db,j->key,&expire); | |
451 | if (j->val) j->expire = expire; | |
452 | } else if (j->type == REDIS_IOJOB_SAVE) { | |
453 | if (j->val) { | |
454 | dsSet(j->db,j->key,j->val,j->expire); | |
455 | } else { | |
456 | dsDel(j->db,j->key); | |
457 | } | |
458 | } | |
459 | ||
460 | /* Done: insert the job into the processed queue */ | |
461 | redisLog(REDIS_DEBUG,"[T] %ld completed the job: %p (key %s)", | |
462 | (long) pthread_self(), (void*)j, (char*)j->key->ptr); | |
463 | ||
464 | redisLog(REDIS_DEBUG,"[T] lock IO"); | |
465 | lockThreadedIO(); | |
466 | redisLog(REDIS_DEBUG,"[T] IO locked"); | |
467 | listDelNode(server.io_processing,ln); | |
468 | listAddNodeTail(server.io_processed,j); | |
469 | ||
470 | /* Signal the main thread there is new stuff to process */ | |
471 | redisAssert(write(server.io_ready_pipe_write,"x",1) == 1); | |
472 | redisLog(REDIS_WARNING,"TIME (%c): %lld\n", j->type == REDIS_IOJOB_LOAD ? 'L' : 'S', ustime()-start); | |
473 | } | |
474 | /* never reached, but that's the full pattern... */ | |
475 | unlockThreadedIO(); | |
476 | return NULL; | |
477 | } | |
478 | ||
479 | void spawnIOThread(void) { | |
480 | pthread_t thread; | |
481 | sigset_t mask, omask; | |
482 | int err; | |
483 | ||
484 | sigemptyset(&mask); | |
485 | sigaddset(&mask,SIGCHLD); | |
486 | sigaddset(&mask,SIGHUP); | |
487 | sigaddset(&mask,SIGPIPE); | |
488 | pthread_sigmask(SIG_SETMASK, &mask, &omask); | |
489 | while ((err = pthread_create(&thread,&server.io_threads_attr,IOThreadEntryPoint,NULL)) != 0) { | |
490 | redisLog(REDIS_WARNING,"Unable to spawn an I/O thread: %s", | |
491 | strerror(err)); | |
492 | usleep(1000000); | |
493 | } | |
494 | pthread_sigmask(SIG_SETMASK, &omask, NULL); | |
495 | server.io_active_threads++; | |
496 | } | |
497 | ||
498 | /* Wait that up to 'max' pending IO Jobs are processed by the I/O thread. | |
499 | * From our point of view an IO job processed means that the count of | |
500 | * server.io_processed must increase by one. | |
501 | * | |
502 | * If max is -1, all the pending IO jobs will be processed. | |
503 | * | |
504 | * Returns the number of IO jobs processed. | |
505 | * | |
506 | * NOTE: while this may appear like a busy loop, we are actually blocked | |
507 | * by IO since we continuously acquire/release the IO lock. */ | |
508 | int processActiveIOJobs(int max) { | |
509 | int processed = 0; | |
510 | ||
511 | while(max == -1 || max > 0) { | |
512 | int io_processed_len; | |
513 | ||
514 | redisLog(REDIS_DEBUG,"[P] lock IO"); | |
515 | lockThreadedIO(); | |
516 | redisLog(REDIS_DEBUG,"Waiting IO jobs processing: new:%d proessing:%d processed:%d",listLength(server.io_newjobs),listLength(server.io_processing),listLength(server.io_processed)); | |
517 | ||
518 | if (listLength(server.io_newjobs) == 0 && | |
519 | listLength(server.io_processing) == 0) | |
520 | { | |
521 | /* There is nothing more to process */ | |
522 | redisLog(REDIS_DEBUG,"[P] Nothing to process, unlock IO, return"); | |
523 | unlockThreadedIO(); | |
524 | break; | |
525 | } | |
526 | ||
527 | #if 1 | |
528 | /* If there are new jobs we need to signal the thread to | |
529 | * process the next one. FIXME: drop this if useless. */ | |
530 | redisLog(REDIS_DEBUG,"[P] waitEmptyIOJobsQueue: new %d, processing %d, processed %d", | |
531 | listLength(server.io_newjobs), | |
532 | listLength(server.io_processing), | |
533 | listLength(server.io_processed)); | |
534 | ||
535 | if (listLength(server.io_newjobs)) { | |
536 | redisLog(REDIS_DEBUG,"[P] There are new jobs, signal"); | |
537 | pthread_cond_signal(&server.io_condvar); | |
538 | } | |
539 | #endif | |
540 | ||
541 | /* Check if we can process some finished job */ | |
542 | io_processed_len = listLength(server.io_processed); | |
543 | redisLog(REDIS_DEBUG,"[P] Unblock IO"); | |
544 | unlockThreadedIO(); | |
545 | redisLog(REDIS_DEBUG,"[P] Wait"); | |
546 | usleep(10000); | |
547 | if (io_processed_len) { | |
548 | vmThreadedIOCompletedJob(NULL,server.io_ready_pipe_read, | |
549 | (void*)0xdeadbeef,0); | |
550 | processed++; | |
551 | if (max != -1) max--; | |
552 | } | |
553 | } | |
554 | return processed; | |
555 | } | |
556 | ||
557 | void waitEmptyIOJobsQueue(void) { | |
558 | processActiveIOJobs(-1); | |
559 | } | |
560 | ||
561 | /* Process up to 'max' IO Jobs already completed by threads but still waiting | |
562 | * processing from the main thread. | |
563 | * | |
564 | * If max == -1 all the pending jobs are processed. | |
565 | * | |
566 | * The number of processed jobs is returned. */ | |
567 | int processPendingIOJobs(int max) { | |
568 | int processed = 0; | |
569 | ||
570 | while(max == -1 || max > 0) { | |
571 | int io_processed_len; | |
572 | ||
573 | lockThreadedIO(); | |
574 | io_processed_len = listLength(server.io_processed); | |
575 | unlockThreadedIO(); | |
576 | if (io_processed_len == 0) break; | |
577 | vmThreadedIOCompletedJob(NULL,server.io_ready_pipe_read, | |
578 | (void*)0xdeadbeef,0); | |
579 | if (max != -1) max--; | |
580 | processed++; | |
581 | } | |
582 | return processed; | |
583 | } | |
584 | ||
585 | void processAllPendingIOJobs(void) { | |
586 | processPendingIOJobs(-1); | |
587 | } | |
588 | ||
589 | /* This function must be called while with threaded IO locked */ | |
590 | void queueIOJob(iojob *j) { | |
591 | redisLog(REDIS_DEBUG,"Queued IO Job %p type %d about key '%s'\n", | |
592 | (void*)j, j->type, (char*)j->key->ptr); | |
593 | listAddNodeTail(server.io_newjobs,j); | |
594 | if (server.io_active_threads < server.vm_max_threads) | |
595 | spawnIOThread(); | |
596 | } | |
597 | ||
598 | /* Consume all the IO scheduled operations, and all the thread IO jobs | |
599 | * so that eventually the state of diskstore is a point-in-time snapshot. | |
600 | * | |
601 | * This is useful when we need to BGSAVE with diskstore enabled. */ | |
602 | void cacheForcePointInTime(void) { | |
603 | redisLog(REDIS_NOTICE,"Diskstore: synching on disk to reach point-in-time state."); | |
604 | while (listLength(server.cache_io_queue) != 0) { | |
605 | cacheScheduleIOPushJobs(REDIS_IO_ASAP); | |
606 | processActiveIOJobs(1); | |
607 | } | |
608 | waitEmptyIOJobsQueue(); | |
609 | processAllPendingIOJobs(); | |
610 | } | |
611 | ||
612 | void cacheCreateIOJob(int type, redisDb *db, robj *key, robj *val, time_t expire) { | |
613 | iojob *j; | |
614 | ||
615 | j = zmalloc(sizeof(*j)); | |
616 | j->type = type; | |
617 | j->db = db; | |
618 | j->key = key; | |
619 | incrRefCount(key); | |
620 | j->val = val; | |
621 | if (val) incrRefCount(val); | |
622 | j->expire = expire; | |
623 | ||
624 | lockThreadedIO(); | |
625 | queueIOJob(j); | |
626 | pthread_cond_signal(&server.io_condvar); | |
627 | unlockThreadedIO(); | |
628 | } | |
629 | ||
630 | /* ============= Disk store cache - Scheduling of IO operations ============= | |
631 | * | |
632 | * We use a queue and an hash table to hold the state of IO operations | |
633 | * so that's fast to lookup if there is already an IO operation in queue | |
634 | * for a given key. | |
635 | * | |
636 | * There are two types of IO operations for a given key: | |
637 | * REDIS_IO_LOAD and REDIS_IO_SAVE. | |
638 | * | |
639 | * The function cacheScheduleIO() function pushes the specified IO operation | |
640 | * in the queue, but avoid adding the same key for the same operation | |
641 | * multiple times, thanks to the associated hash table. | |
642 | * | |
643 | * We take a set of flags per every key, so when the scheduled IO operation | |
644 | * gets moved from the scheduled queue to the actual IO Jobs queue that | |
645 | * is processed by the IO thread, we flag it as IO_LOADINPROG or | |
646 | * IO_SAVEINPROG. | |
647 | * | |
648 | * So for every given key we always know if there is some IO operation | |
649 | * scheduled, or in progress, for this key. | |
650 | * | |
651 | * NOTE: all this is very important in order to guarantee correctness of | |
652 | * the Disk Store Cache. Jobs are always queued here. Load jobs are | |
653 | * queued at the head for faster execution only in the case there is not | |
654 | * already a write operation of some kind for this job. | |
655 | * | |
656 | * So we have ordering, but can do exceptions when there are no already | |
657 | * operations for a given key. Also when we need to block load a given | |
658 | * key, for an immediate lookup operation, we can check if the key can | |
659 | * be accessed synchronously without race conditions (no IN PROGRESS | |
660 | * operations for this key), otherwise we blocking wait for completion. */ | |
661 | ||
662 | #define REDIS_IO_LOAD 1 | |
663 | #define REDIS_IO_SAVE 2 | |
664 | #define REDIS_IO_LOADINPROG 4 | |
665 | #define REDIS_IO_SAVEINPROG 8 | |
666 | ||
667 | void cacheScheduleIOAddFlag(redisDb *db, robj *key, long flag) { | |
668 | struct dictEntry *de = dictFind(db->io_queued,key); | |
669 | ||
670 | if (!de) { | |
671 | dictAdd(db->io_queued,key,(void*)flag); | |
672 | incrRefCount(key); | |
673 | return; | |
674 | } else { | |
675 | long flags = (long) dictGetEntryVal(de); | |
676 | ||
677 | if (flags & flag) { | |
678 | redisLog(REDIS_WARNING,"Adding the same flag again: was: %ld, addede: %ld",flags,flag); | |
679 | redisAssert(!(flags & flag)); | |
680 | } | |
681 | flags |= flag; | |
682 | dictGetEntryVal(de) = (void*) flags; | |
683 | } | |
684 | } | |
685 | ||
686 | void cacheScheduleIODelFlag(redisDb *db, robj *key, long flag) { | |
687 | struct dictEntry *de = dictFind(db->io_queued,key); | |
688 | long flags; | |
689 | ||
690 | redisAssert(de != NULL); | |
691 | flags = (long) dictGetEntryVal(de); | |
692 | redisAssert(flags & flag); | |
693 | flags &= ~flag; | |
694 | if (flags == 0) { | |
695 | dictDelete(db->io_queued,key); | |
696 | } else { | |
697 | dictGetEntryVal(de) = (void*) flags; | |
698 | } | |
699 | } | |
700 | ||
701 | int cacheScheduleIOGetFlags(redisDb *db, robj *key) { | |
702 | struct dictEntry *de = dictFind(db->io_queued,key); | |
703 | ||
704 | return (de == NULL) ? 0 : ((long) dictGetEntryVal(de)); | |
705 | } | |
706 | ||
707 | void cacheScheduleIO(redisDb *db, robj *key, int type) { | |
708 | ioop *op; | |
709 | long flags; | |
710 | ||
711 | if ((flags = cacheScheduleIOGetFlags(db,key)) & type) return; | |
712 | ||
713 | redisLog(REDIS_DEBUG,"Scheduling key %s for %s", | |
714 | key->ptr, type == REDIS_IO_LOAD ? "loading" : "saving"); | |
715 | cacheScheduleIOAddFlag(db,key,type); | |
716 | op = zmalloc(sizeof(*op)); | |
717 | op->type = type; | |
718 | op->db = db; | |
719 | op->key = key; | |
720 | incrRefCount(key); | |
721 | op->ctime = time(NULL); | |
722 | ||
723 | /* Give priority to load operations if there are no save already | |
724 | * in queue for the same key. */ | |
725 | if (type == REDIS_IO_LOAD && !(flags & REDIS_IO_SAVE)) { | |
726 | listAddNodeHead(server.cache_io_queue, op); | |
727 | cacheScheduleIOPushJobs(REDIS_IO_ONLYLOADS); | |
728 | } else { | |
729 | /* FIXME: probably when this happens we want to at least move | |
730 | * the write job about this queue on top, and set the creation time | |
731 | * to a value that will force processing ASAP. */ | |
732 | listAddNodeTail(server.cache_io_queue, op); | |
733 | } | |
734 | } | |
735 | ||
736 | /* Push scheduled IO operations into IO Jobs that the IO thread can process. | |
737 | * | |
738 | * If flags include REDIS_IO_ONLYLOADS only load jobs are processed:this is | |
739 | * useful since it's safe to push LOAD IO jobs from any place of the code, while | |
740 | * SAVE io jobs should never be pushed while we are processing a command | |
741 | * (not protected by lookupKey() that will block on keys in IO_SAVEINPROG | |
742 | * state. | |
743 | * | |
744 | * The REDIS_IO_ASAP flag tells the function to don't wait for the IO job | |
745 | * scheduled completion time, but just do the operation ASAP. This is useful | |
746 | * when we need to reclaim memory from the IO queue. | |
747 | */ | |
748 | #define MAX_IO_JOBS_QUEUE 10 | |
749 | int cacheScheduleIOPushJobs(int flags) { | |
750 | time_t now = time(NULL); | |
751 | listNode *ln; | |
752 | int jobs, topush = 0, pushed = 0; | |
753 | ||
754 | /* Don't push new jobs if there is a threaded BGSAVE in progress. */ | |
755 | if (server.bgsavethread != (pthread_t) -1) return 0; | |
756 | ||
757 | /* Sync stuff on disk, but only if we have less | |
758 | * than MAX_IO_JOBS_QUEUE IO jobs. */ | |
759 | lockThreadedIO(); | |
760 | jobs = listLength(server.io_newjobs); | |
761 | unlockThreadedIO(); | |
762 | ||
763 | topush = MAX_IO_JOBS_QUEUE-jobs; | |
764 | if (topush < 0) topush = 0; | |
765 | if (topush > (signed)listLength(server.cache_io_queue)) | |
766 | topush = listLength(server.cache_io_queue); | |
767 | ||
768 | while((ln = listFirst(server.cache_io_queue)) != NULL) { | |
769 | ioop *op = ln->value; | |
770 | struct dictEntry *de; | |
771 | robj *val; | |
772 | ||
773 | if (!topush) break; | |
774 | topush--; | |
775 | ||
776 | if (op->type != REDIS_IO_LOAD && flags & REDIS_IO_ONLYLOADS) break; | |
777 | ||
778 | /* Don't execute SAVE before the scheduled time for completion */ | |
779 | if (op->type == REDIS_IO_SAVE && !(flags & REDIS_IO_ASAP) && | |
780 | (now - op->ctime) < server.cache_flush_delay) break; | |
781 | ||
782 | /* Don't add a SAVE job in the IO thread queue if there is already | |
783 | * a save in progress for the same key. */ | |
784 | if (op->type == REDIS_IO_SAVE && | |
785 | cacheScheduleIOGetFlags(op->db,op->key) & REDIS_IO_SAVEINPROG) | |
786 | { | |
787 | /* Move the operation at the end of the list if there | |
788 | * are other operations, so we can try to process the next one. | |
789 | * Otherwise break, nothing to do here. */ | |
790 | if (listLength(server.cache_io_queue) > 1) { | |
791 | listDelNode(server.cache_io_queue,ln); | |
792 | listAddNodeTail(server.cache_io_queue,op); | |
793 | continue; | |
794 | } else { | |
795 | break; | |
796 | } | |
797 | } | |
798 | ||
799 | redisLog(REDIS_DEBUG,"Creating IO %s Job for key %s", | |
800 | op->type == REDIS_IO_LOAD ? "load" : "save", op->key->ptr); | |
801 | ||
802 | if (op->type == REDIS_IO_LOAD) { | |
803 | cacheCreateIOJob(REDIS_IOJOB_LOAD,op->db,op->key,NULL,0); | |
804 | } else { | |
805 | time_t expire = -1; | |
806 | ||
807 | /* Lookup the key, in order to put the current value in the IO | |
808 | * Job. Otherwise if the key does not exists we schedule a disk | |
809 | * store delete operation, setting the value to NULL. */ | |
810 | de = dictFind(op->db->dict,op->key->ptr); | |
811 | if (de) { | |
812 | val = dictGetEntryVal(de); | |
813 | expire = getExpire(op->db,op->key); | |
814 | } else { | |
815 | /* Setting the value to NULL tells the IO thread to delete | |
816 | * the key on disk. */ | |
817 | val = NULL; | |
818 | } | |
819 | cacheCreateIOJob(REDIS_IOJOB_SAVE,op->db,op->key,val,expire); | |
820 | } | |
821 | /* Mark the operation as in progress. */ | |
822 | cacheScheduleIODelFlag(op->db,op->key,op->type); | |
823 | cacheScheduleIOAddFlag(op->db,op->key, | |
824 | (op->type == REDIS_IO_LOAD) ? REDIS_IO_LOADINPROG : | |
825 | REDIS_IO_SAVEINPROG); | |
826 | /* Finally remove the operation from the queue. | |
827 | * But we'll have trace of it in the hash table. */ | |
828 | listDelNode(server.cache_io_queue,ln); | |
829 | decrRefCount(op->key); | |
830 | zfree(op); | |
831 | pushed++; | |
832 | } | |
833 | return pushed; | |
834 | } | |
835 | ||
836 | void cacheCron(void) { | |
837 | /* Push jobs */ | |
838 | cacheScheduleIOPushJobs(0); | |
839 | ||
840 | /* Reclaim memory from the object cache */ | |
841 | while (server.ds_enabled && zmalloc_used_memory() > | |
842 | server.cache_max_memory) | |
843 | { | |
844 | int done = 0; | |
845 | ||
846 | if (cacheFreeOneEntry() == REDIS_OK) done++; | |
847 | if (negativeCacheEvictOneEntry() == REDIS_OK) done++; | |
848 | if (done == 0) break; /* nothing more to free */ | |
849 | } | |
850 | } | |
851 | ||
852 | /* ========== Disk store cache - Blocking clients on missing keys =========== */ | |
853 | ||
854 | /* This function makes the clinet 'c' waiting for the key 'key' to be loaded. | |
855 | * If the key is already in memory we don't need to block. | |
856 | * | |
857 | * FIXME: we should try if it's actually better to suspend the client | |
858 | * accessing an object that is being saved, and awake it only when | |
859 | * the saving was completed. | |
860 | * | |
861 | * Otherwise if the key is not in memory, we block the client and start | |
862 | * an IO Job to load it: | |
863 | * | |
864 | * the key is added to the io_keys list in the client structure, and also | |
865 | * in the hash table mapping swapped keys to waiting clients, that is, | |
866 | * server.io_waited_keys. */ | |
867 | int waitForSwappedKey(redisClient *c, robj *key) { | |
868 | struct dictEntry *de; | |
869 | list *l; | |
870 | ||
871 | /* Return ASAP if the key is in memory */ | |
872 | de = dictFind(c->db->dict,key->ptr); | |
873 | if (de != NULL) return 0; | |
874 | ||
875 | /* Don't wait for keys we are sure are not on disk either */ | |
876 | if (!cacheKeyMayExist(c->db,key)) return 0; | |
877 | ||
878 | /* Add the key to the list of keys this client is waiting for. | |
879 | * This maps clients to keys they are waiting for. */ | |
880 | listAddNodeTail(c->io_keys,key); | |
881 | incrRefCount(key); | |
882 | ||
883 | /* Add the client to the swapped keys => clients waiting map. */ | |
884 | de = dictFind(c->db->io_keys,key); | |
885 | if (de == NULL) { | |
886 | int retval; | |
887 | ||
888 | /* For every key we take a list of clients blocked for it */ | |
889 | l = listCreate(); | |
890 | retval = dictAdd(c->db->io_keys,key,l); | |
891 | incrRefCount(key); | |
892 | redisAssert(retval == DICT_OK); | |
893 | } else { | |
894 | l = dictGetEntryVal(de); | |
895 | } | |
896 | listAddNodeTail(l,c); | |
897 | ||
898 | /* Are we already loading the key from disk? If not create a job */ | |
899 | if (de == NULL) | |
900 | cacheScheduleIO(c->db,key,REDIS_IO_LOAD); | |
901 | return 1; | |
902 | } | |
903 | ||
904 | /* Preload keys for any command with first, last and step values for | |
905 | * the command keys prototype, as defined in the command table. */ | |
906 | void waitForMultipleSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) { | |
907 | int j, last; | |
908 | if (cmd->vm_firstkey == 0) return; | |
909 | last = cmd->vm_lastkey; | |
910 | if (last < 0) last = argc+last; | |
911 | for (j = cmd->vm_firstkey; j <= last; j += cmd->vm_keystep) { | |
912 | redisAssert(j < argc); | |
913 | waitForSwappedKey(c,argv[j]); | |
914 | } | |
915 | } | |
916 | ||
917 | /* Preload keys needed for the ZUNIONSTORE and ZINTERSTORE commands. | |
918 | * Note that the number of keys to preload is user-defined, so we need to | |
919 | * apply a sanity check against argc. */ | |
920 | void zunionInterBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) { | |
921 | int i, num; | |
922 | REDIS_NOTUSED(cmd); | |
923 | ||
924 | num = atoi(argv[2]->ptr); | |
925 | if (num > (argc-3)) return; | |
926 | for (i = 0; i < num; i++) { | |
927 | waitForSwappedKey(c,argv[3+i]); | |
928 | } | |
929 | } | |
930 | ||
931 | /* Preload keys needed to execute the entire MULTI/EXEC block. | |
932 | * | |
933 | * This function is called by blockClientOnSwappedKeys when EXEC is issued, | |
934 | * and will block the client when any command requires a swapped out value. */ | |
935 | void execBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) { | |
936 | int i, margc; | |
937 | struct redisCommand *mcmd; | |
938 | robj **margv; | |
939 | REDIS_NOTUSED(cmd); | |
940 | REDIS_NOTUSED(argc); | |
941 | REDIS_NOTUSED(argv); | |
942 | ||
943 | if (!(c->flags & REDIS_MULTI)) return; | |
944 | for (i = 0; i < c->mstate.count; i++) { | |
945 | mcmd = c->mstate.commands[i].cmd; | |
946 | margc = c->mstate.commands[i].argc; | |
947 | margv = c->mstate.commands[i].argv; | |
948 | ||
949 | if (mcmd->vm_preload_proc != NULL) { | |
950 | mcmd->vm_preload_proc(c,mcmd,margc,margv); | |
951 | } else { | |
952 | waitForMultipleSwappedKeys(c,mcmd,margc,margv); | |
953 | } | |
954 | } | |
955 | } | |
956 | ||
957 | /* Is this client attempting to run a command against swapped keys? | |
958 | * If so, block it ASAP, load the keys in background, then resume it. | |
959 | * | |
960 | * The important idea about this function is that it can fail! If keys will | |
961 | * still be swapped when the client is resumed, this key lookups will | |
962 | * just block loading keys from disk. In practical terms this should only | |
963 | * happen with SORT BY command or if there is a bug in this function. | |
964 | * | |
965 | * Return 1 if the client is marked as blocked, 0 if the client can | |
966 | * continue as the keys it is going to access appear to be in memory. */ | |
967 | int blockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd) { | |
968 | if (cmd->vm_preload_proc != NULL) { | |
969 | cmd->vm_preload_proc(c,cmd,c->argc,c->argv); | |
970 | } else { | |
971 | waitForMultipleSwappedKeys(c,cmd,c->argc,c->argv); | |
972 | } | |
973 | ||
974 | /* If the client was blocked for at least one key, mark it as blocked. */ | |
975 | if (listLength(c->io_keys)) { | |
976 | c->flags |= REDIS_IO_WAIT; | |
977 | aeDeleteFileEvent(server.el,c->fd,AE_READABLE); | |
978 | server.cache_blocked_clients++; | |
979 | return 1; | |
980 | } else { | |
981 | return 0; | |
982 | } | |
983 | } | |
984 | ||
985 | /* Remove the 'key' from the list of blocked keys for a given client. | |
986 | * | |
987 | * The function returns 1 when there are no longer blocking keys after | |
988 | * the current one was removed (and the client can be unblocked). */ | |
989 | int dontWaitForSwappedKey(redisClient *c, robj *key) { | |
990 | list *l; | |
991 | listNode *ln; | |
992 | listIter li; | |
993 | struct dictEntry *de; | |
994 | ||
995 | /* The key object might be destroyed when deleted from the c->io_keys | |
996 | * list (and the "key" argument is physically the same object as the | |
997 | * object inside the list), so we need to protect it. */ | |
998 | incrRefCount(key); | |
999 | ||
1000 | /* Remove the key from the list of keys this client is waiting for. */ | |
1001 | listRewind(c->io_keys,&li); | |
1002 | while ((ln = listNext(&li)) != NULL) { | |
1003 | if (equalStringObjects(ln->value,key)) { | |
1004 | listDelNode(c->io_keys,ln); | |
1005 | break; | |
1006 | } | |
1007 | } | |
1008 | redisAssert(ln != NULL); | |
1009 | ||
1010 | /* Remove the client form the key => waiting clients map. */ | |
1011 | de = dictFind(c->db->io_keys,key); | |
1012 | redisAssert(de != NULL); | |
1013 | l = dictGetEntryVal(de); | |
1014 | ln = listSearchKey(l,c); | |
1015 | redisAssert(ln != NULL); | |
1016 | listDelNode(l,ln); | |
1017 | if (listLength(l) == 0) | |
1018 | dictDelete(c->db->io_keys,key); | |
1019 | ||
1020 | decrRefCount(key); | |
1021 | return listLength(c->io_keys) == 0; | |
1022 | } | |
1023 | ||
1024 | /* Every time we now a key was loaded back in memory, we handle clients | |
1025 | * waiting for this key if any. */ | |
1026 | void handleClientsBlockedOnSwappedKey(redisDb *db, robj *key) { | |
1027 | struct dictEntry *de; | |
1028 | list *l; | |
1029 | listNode *ln; | |
1030 | int len; | |
1031 | ||
1032 | de = dictFind(db->io_keys,key); | |
1033 | if (!de) return; | |
1034 | ||
1035 | l = dictGetEntryVal(de); | |
1036 | len = listLength(l); | |
1037 | /* Note: we can't use something like while(listLength(l)) as the list | |
1038 | * can be freed by the calling function when we remove the last element. */ | |
1039 | while (len--) { | |
1040 | ln = listFirst(l); | |
1041 | redisClient *c = ln->value; | |
1042 | ||
1043 | if (dontWaitForSwappedKey(c,key)) { | |
1044 | /* Put the client in the list of clients ready to go as we | |
1045 | * loaded all the keys about it. */ | |
1046 | listAddNodeTail(server.io_ready_clients,c); | |
1047 | } | |
1048 | } | |
1049 | } |