]>
git.cameronkatri.com Git - cgit.git/blob - cache.c
1 /* cache.c: cache management
3 * Copyright (C) 2006-2014 cgit Development Team <cgit@lists.zx2c4.com>
5 * Licensed under GNU General Public License v2
6 * (see COPYING for full license text)
9 * The cache is just a directory structure where each file is a cache slot,
10 * and each filename is based on the hash of some key (e.g. the cgit url).
11 * Each file contains the full key followed by the cached content for that
19 #ifdef HAVE_LINUX_SENDFILE
20 #include <sys/sendfile.h>
23 #define CACHE_BUFSIZE (1024 * 4)
33 const char *cache_name
;
34 const char *lock_name
;
38 char buf
[CACHE_BUFSIZE
];
41 /* Open an existing cache slot and fill the cache buffer with
42 * (part of) the content of the cache file. Return 0 on success
43 * and errno otherwise.
45 static int open_slot(struct cache_slot
*slot
)
48 ssize_t bufkeylen
= -1;
50 slot
->cache_fd
= open(slot
->cache_name
, O_RDONLY
);
51 if (slot
->cache_fd
== -1)
54 if (fstat(slot
->cache_fd
, &slot
->cache_st
))
57 slot
->bufsize
= xread(slot
->cache_fd
, slot
->buf
, sizeof(slot
->buf
));
58 if (slot
->bufsize
< 0)
61 bufz
= memchr(slot
->buf
, 0, slot
->bufsize
);
63 bufkeylen
= bufz
- slot
->buf
;
66 slot
->match
= bufkeylen
== slot
->keylen
&&
67 !memcmp(slot
->key
, slot
->buf
, bufkeylen
+ 1);
72 /* Close the active cache slot */
73 static int close_slot(struct cache_slot
*slot
)
76 if (slot
->cache_fd
> 0) {
77 if (close(slot
->cache_fd
))
85 /* Print the content of the active cache slot (but skip the key). */
86 static int print_slot(struct cache_slot
*slot
)
88 #ifdef HAVE_LINUX_SENDFILE
92 start_off
= slot
->keylen
+ 1;
95 ret
= sendfile(STDOUT_FILENO
, slot
->cache_fd
, &start_off
,
96 slot
->cache_st
.st_size
- start_off
);
98 if (errno
== EAGAIN
|| errno
== EINTR
)
107 i
= lseek(slot
->cache_fd
, slot
->keylen
+ 1, SEEK_SET
);
108 if (i
!= slot
->keylen
+ 1)
112 i
= j
= xread(slot
->cache_fd
, slot
->buf
, sizeof(slot
->buf
));
114 j
= xwrite(STDOUT_FILENO
, slot
->buf
, i
);
115 } while (i
> 0 && j
== i
);
124 /* Check if the slot has expired */
125 static int is_expired(struct cache_slot
*slot
)
130 return slot
->cache_st
.st_mtime
+ slot
->ttl
* 60 < time(NULL
);
133 /* Check if the slot has been modified since we opened it.
134 * NB: If stat() fails, we pretend the file is modified.
136 static int is_modified(struct cache_slot
*slot
)
140 if (stat(slot
->cache_name
, &st
))
142 return (st
.st_ino
!= slot
->cache_st
.st_ino
||
143 st
.st_mtime
!= slot
->cache_st
.st_mtime
||
144 st
.st_size
!= slot
->cache_st
.st_size
);
147 /* Close an open lockfile */
148 static int close_lock(struct cache_slot
*slot
)
151 if (slot
->lock_fd
> 0) {
152 if (close(slot
->lock_fd
))
160 /* Create a lockfile used to store the generated content for a cache
161 * slot, and write the slot key + \0 into it.
162 * Returns 0 on success and errno otherwise.
164 static int lock_slot(struct cache_slot
*slot
)
166 struct flock lock
= {
168 .l_whence
= SEEK_SET
,
173 slot
->lock_fd
= open(slot
->lock_name
, O_RDWR
| O_CREAT
,
175 if (slot
->lock_fd
== -1)
177 if (fcntl(slot
->lock_fd
, F_SETLK
, &lock
) < 0) {
178 int saved_errno
= errno
;
179 close(slot
->lock_fd
);
183 if (xwrite(slot
->lock_fd
, slot
->key
, slot
->keylen
+ 1) < 0)
188 /* Release the current lockfile. If `replace_old_slot` is set the
189 * lockfile replaces the old cache slot, otherwise the lockfile is
192 static int unlock_slot(struct cache_slot
*slot
, int replace_old_slot
)
196 if (replace_old_slot
)
197 err
= rename(slot
->lock_name
, slot
->cache_name
);
199 err
= unlink(slot
->lock_name
);
201 /* Restore stdout and close the temporary FD. */
202 if (slot
->stdout_fd
>= 0) {
203 dup2(slot
->stdout_fd
, STDOUT_FILENO
);
204 close(slot
->stdout_fd
);
205 slot
->stdout_fd
= -1;
214 /* Generate the content for the current cache slot by redirecting
215 * stdout to the lock-fd and invoking the callback function
217 static int fill_slot(struct cache_slot
*slot
)
219 /* Preserve stdout */
220 slot
->stdout_fd
= dup(STDOUT_FILENO
);
221 if (slot
->stdout_fd
== -1)
224 /* Redirect stdout to lockfile */
225 if (dup2(slot
->lock_fd
, STDOUT_FILENO
) == -1)
228 /* Generate cache content */
231 /* Make sure any buffered data is flushed to the file */
235 /* update stat info */
236 if (fstat(slot
->lock_fd
, &slot
->cache_st
))
242 /* Crude implementation of 32-bit FNV-1 hash algorithm,
243 * see http://www.isthe.com/chongo/tech/comp/fnv/ for details
244 * about the magic numbers.
246 #define FNV_OFFSET 0x811c9dc5
247 #define FNV_PRIME 0x01000193
249 unsigned long hash_str(const char *str
)
251 unsigned long h
= FNV_OFFSET
;
252 unsigned char *s
= (unsigned char *)str
;
264 static int process_slot(struct cache_slot
*slot
)
268 err
= open_slot(slot
);
269 if (!err
&& slot
->match
) {
270 if (is_expired(slot
)) {
271 if (!lock_slot(slot
)) {
272 /* If the cachefile has been replaced between
273 * `open_slot` and `lock_slot`, we'll just
274 * serve the stale content from the original
275 * cachefile. This way we avoid pruning the
276 * newly generated slot. The same code-path
277 * is chosen if fill_slot() fails for some
280 * TODO? check if the new slot contains the
281 * same key as the old one, since we would
282 * prefer to serve the newest content.
283 * This will require us to open yet another
284 * file-descriptor and read and compare the
285 * key from the new file, so for now we're
286 * lazy and just ignore the new file.
288 if (is_modified(slot
) || fill_slot(slot
)) {
289 unlock_slot(slot
, 0);
293 unlock_slot(slot
, 1);
294 slot
->cache_fd
= slot
->lock_fd
;
298 if ((err
= print_slot(slot
)) != 0) {
299 cache_log("[cgit] error printing cache %s: %s (%d)\n",
308 /* If the cache slot does not exist (or its key doesn't match the
309 * current key), lets try to create a new cache slot for this
310 * request. If this fails (for whatever reason), lets just generate
311 * the content without caching it and fool the caller to believe
312 * everything worked out (but print a warning on stdout).
316 if ((err
= lock_slot(slot
)) != 0) {
317 cache_log("[cgit] Unable to lock slot %s: %s (%d)\n",
318 slot
->lock_name
, strerror(err
), err
);
323 if ((err
= fill_slot(slot
)) != 0) {
324 cache_log("[cgit] Unable to fill slot %s: %s (%d)\n",
325 slot
->lock_name
, strerror(err
), err
);
326 unlock_slot(slot
, 0);
331 // We've got a valid cache slot in the lock file, which
332 // is about to replace the old cache slot. But if we
333 // release the lockfile and then try to open the new cache
334 // slot, we might get a race condition with a concurrent
335 // writer for the same cache slot (with a different key).
336 // Lets avoid such a race by just printing the content of
338 slot
->cache_fd
= slot
->lock_fd
;
339 unlock_slot(slot
, 1);
340 if ((err
= print_slot(slot
)) != 0) {
341 cache_log("[cgit] error printing cache %s: %s (%d)\n",
350 /* Print cached content to stdout, generate the content if necessary. */
351 int cache_process(int size
, const char *path
, const char *key
, int ttl
,
356 struct strbuf filename
= STRBUF_INIT
;
357 struct strbuf lockname
= STRBUF_INIT
;
358 struct cache_slot slot
;
361 /* If the cache is disabled, just generate the content */
362 if (size
<= 0 || ttl
== 0) {
367 /* Verify input, calculate filenames */
369 cache_log("[cgit] Cache path not specified, caching is disabled\n");
375 hash
= hash_str(key
) % size
;
376 strbuf_addstr(&filename
, path
);
377 strbuf_ensure_end(&filename
, '/');
378 for (i
= 0; i
< 8; i
++) {
379 strbuf_addf(&filename
, "%x", (unsigned char)(hash
& 0xf));
382 strbuf_addbuf(&lockname
, &filename
);
383 strbuf_addstr(&lockname
, ".lock");
387 slot
.cache_name
= filename
.buf
;
388 slot
.lock_name
= lockname
.buf
;
390 slot
.keylen
= strlen(key
);
391 result
= process_slot(&slot
);
393 strbuf_release(&filename
);
394 strbuf_release(&lockname
);
398 /* Return a strftime formatted date/time
399 * NB: the result from this function is to shared memory
401 static char *sprintftime(const char *format
, time_t time
)
408 gmtime_r(&time
, &tm
);
409 strftime(buf
, sizeof(buf
)-1, format
, &tm
);
413 int cache_ls(const char *path
)
418 struct cache_slot slot
= { NULL
};
419 struct strbuf fullname
= STRBUF_INIT
;
423 cache_log("[cgit] cache path not specified\n");
429 cache_log("[cgit] unable to open path %s: %s (%d)\n",
430 path
, strerror(err
), err
);
433 strbuf_addstr(&fullname
, path
);
434 strbuf_ensure_end(&fullname
, '/');
435 prefixlen
= fullname
.len
;
436 while ((ent
= readdir(dir
)) != NULL
) {
437 if (strlen(ent
->d_name
) != 8)
439 strbuf_setlen(&fullname
, prefixlen
);
440 strbuf_addstr(&fullname
, ent
->d_name
);
441 slot
.cache_name
= fullname
.buf
;
442 if ((err
= open_slot(&slot
)) != 0) {
443 cache_log("[cgit] unable to open path %s: %s (%d)\n",
444 fullname
.buf
, strerror(err
), err
);
447 htmlf("%s %s %10"PRIuMAX
" %s\n",
449 sprintftime("%Y-%m-%d %H:%M:%S",
450 slot
.cache_st
.st_mtime
),
451 (uintmax_t)slot
.cache_st
.st_size
,
456 strbuf_release(&fullname
);
460 /* Print a message to stdout */
461 void cache_log(const char *format
, ...)
464 va_start(args
, format
);
465 vfprintf(stderr
, format
, args
);