]>
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)
32 const char *cache_name
;
33 const char *lock_name
;
37 char buf
[CACHE_BUFSIZE
];
40 /* Open an existing cache slot and fill the cache buffer with
41 * (part of) the content of the cache file. Return 0 on success
42 * and errno otherwise.
44 static int open_slot(struct cache_slot
*slot
)
47 ssize_t bufkeylen
= -1;
49 slot
->cache_fd
= open(slot
->cache_name
, O_RDONLY
);
50 if (slot
->cache_fd
== -1)
53 if (fstat(slot
->cache_fd
, &slot
->cache_st
))
56 slot
->bufsize
= xread(slot
->cache_fd
, slot
->buf
, sizeof(slot
->buf
));
57 if (slot
->bufsize
< 0)
60 bufz
= memchr(slot
->buf
, 0, slot
->bufsize
);
62 bufkeylen
= bufz
- slot
->buf
;
65 slot
->match
= bufkeylen
== slot
->keylen
&&
66 !memcmp(slot
->key
, slot
->buf
, bufkeylen
+ 1);
71 /* Close the active cache slot */
72 static int close_slot(struct cache_slot
*slot
)
75 if (slot
->cache_fd
> 0) {
76 if (close(slot
->cache_fd
))
84 /* Print the content of the active cache slot (but skip the key). */
85 static int print_slot(struct cache_slot
*slot
)
87 #ifdef HAVE_LINUX_SENDFILE
91 start_off
= slot
->keylen
+ 1;
94 ret
= sendfile(STDOUT_FILENO
, slot
->cache_fd
, &start_off
,
95 slot
->cache_st
.st_size
- start_off
);
97 if (errno
== EAGAIN
|| errno
== EINTR
)
106 i
= lseek(slot
->cache_fd
, slot
->keylen
+ 1, SEEK_SET
);
107 if (i
!= slot
->keylen
+ 1)
111 i
= j
= xread(slot
->cache_fd
, slot
->buf
, sizeof(slot
->buf
));
113 j
= xwrite(STDOUT_FILENO
, slot
->buf
, i
);
114 } while (i
> 0 && j
== i
);
123 /* Check if the slot has expired */
124 static int is_expired(struct cache_slot
*slot
)
129 return slot
->cache_st
.st_mtime
+ slot
->ttl
* 60 < time(NULL
);
132 /* Check if the slot has been modified since we opened it.
133 * NB: If stat() fails, we pretend the file is modified.
135 static int is_modified(struct cache_slot
*slot
)
139 if (stat(slot
->cache_name
, &st
))
141 return (st
.st_ino
!= slot
->cache_st
.st_ino
||
142 st
.st_mtime
!= slot
->cache_st
.st_mtime
||
143 st
.st_size
!= slot
->cache_st
.st_size
);
146 /* Close an open lockfile */
147 static int close_lock(struct cache_slot
*slot
)
150 if (slot
->lock_fd
> 0) {
151 if (close(slot
->lock_fd
))
159 /* Create a lockfile used to store the generated content for a cache
160 * slot, and write the slot key + \0 into it.
161 * Returns 0 on success and errno otherwise.
163 static int lock_slot(struct cache_slot
*slot
)
165 struct flock lock
= {
167 .l_whence
= SEEK_SET
,
172 slot
->lock_fd
= open(slot
->lock_name
, O_RDWR
| O_CREAT
,
174 if (slot
->lock_fd
== -1)
176 if (fcntl(slot
->lock_fd
, F_SETLK
, &lock
) < 0) {
177 int saved_errno
= errno
;
178 close(slot
->lock_fd
);
182 if (xwrite(slot
->lock_fd
, slot
->key
, slot
->keylen
+ 1) < 0)
187 /* Release the current lockfile. If `replace_old_slot` is set the
188 * lockfile replaces the old cache slot, otherwise the lockfile is
191 static int unlock_slot(struct cache_slot
*slot
, int replace_old_slot
)
195 if (replace_old_slot
)
196 err
= rename(slot
->lock_name
, slot
->cache_name
);
198 err
= unlink(slot
->lock_name
);
206 /* Generate the content for the current cache slot by redirecting
207 * stdout to the lock-fd and invoking the callback function
209 static int fill_slot(struct cache_slot
*slot
)
213 /* Preserve stdout */
214 tmp
= dup(STDOUT_FILENO
);
218 /* Redirect stdout to lockfile */
219 if (dup2(slot
->lock_fd
, STDOUT_FILENO
) == -1) {
224 /* Generate cache content */
227 /* update stat info */
228 if (fstat(slot
->lock_fd
, &slot
->cache_st
)) {
234 if (dup2(tmp
, STDOUT_FILENO
) == -1) {
239 /* Close the temporary filedescriptor */
246 /* Crude implementation of 32-bit FNV-1 hash algorithm,
247 * see http://www.isthe.com/chongo/tech/comp/fnv/ for details
248 * about the magic numbers.
250 #define FNV_OFFSET 0x811c9dc5
251 #define FNV_PRIME 0x01000193
253 unsigned long hash_str(const char *str
)
255 unsigned long h
= FNV_OFFSET
;
256 unsigned char *s
= (unsigned char *)str
;
268 static int process_slot(struct cache_slot
*slot
)
272 err
= open_slot(slot
);
273 if (!err
&& slot
->match
) {
274 if (is_expired(slot
)) {
275 if (!lock_slot(slot
)) {
276 /* If the cachefile has been replaced between
277 * `open_slot` and `lock_slot`, we'll just
278 * serve the stale content from the original
279 * cachefile. This way we avoid pruning the
280 * newly generated slot. The same code-path
281 * is chosen if fill_slot() fails for some
284 * TODO? check if the new slot contains the
285 * same key as the old one, since we would
286 * prefer to serve the newest content.
287 * This will require us to open yet another
288 * file-descriptor and read and compare the
289 * key from the new file, so for now we're
290 * lazy and just ignore the new file.
292 if (is_modified(slot
) || fill_slot(slot
)) {
293 unlock_slot(slot
, 0);
297 unlock_slot(slot
, 1);
298 slot
->cache_fd
= slot
->lock_fd
;
302 if ((err
= print_slot(slot
)) != 0) {
303 cache_log("[cgit] error printing cache %s: %s (%d)\n",
312 /* If the cache slot does not exist (or its key doesn't match the
313 * current key), lets try to create a new cache slot for this
314 * request. If this fails (for whatever reason), lets just generate
315 * the content without caching it and fool the caller to belive
316 * everything worked out (but print a warning on stdout).
320 if ((err
= lock_slot(slot
)) != 0) {
321 cache_log("[cgit] Unable to lock slot %s: %s (%d)\n",
322 slot
->lock_name
, strerror(err
), err
);
327 if ((err
= fill_slot(slot
)) != 0) {
328 cache_log("[cgit] Unable to fill slot %s: %s (%d)\n",
329 slot
->lock_name
, strerror(err
), err
);
330 unlock_slot(slot
, 0);
335 // We've got a valid cache slot in the lock file, which
336 // is about to replace the old cache slot. But if we
337 // release the lockfile and then try to open the new cache
338 // slot, we might get a race condition with a concurrent
339 // writer for the same cache slot (with a different key).
340 // Lets avoid such a race by just printing the content of
342 slot
->cache_fd
= slot
->lock_fd
;
343 unlock_slot(slot
, 1);
344 if ((err
= print_slot(slot
)) != 0) {
345 cache_log("[cgit] error printing cache %s: %s (%d)\n",
354 /* Print cached content to stdout, generate the content if necessary. */
355 int cache_process(int size
, const char *path
, const char *key
, int ttl
,
360 struct strbuf filename
= STRBUF_INIT
;
361 struct strbuf lockname
= STRBUF_INIT
;
362 struct cache_slot slot
;
365 /* If the cache is disabled, just generate the content */
366 if (size
<= 0 || ttl
== 0) {
371 /* Verify input, calculate filenames */
373 cache_log("[cgit] Cache path not specified, caching is disabled\n");
379 hash
= hash_str(key
) % size
;
380 strbuf_addstr(&filename
, path
);
381 strbuf_ensure_end(&filename
, '/');
382 for (i
= 0; i
< 8; i
++) {
383 strbuf_addf(&filename
, "%x", (unsigned char)(hash
& 0xf));
386 strbuf_addbuf(&lockname
, &filename
);
387 strbuf_addstr(&lockname
, ".lock");
390 slot
.cache_name
= filename
.buf
;
391 slot
.lock_name
= lockname
.buf
;
393 slot
.keylen
= strlen(key
);
394 result
= process_slot(&slot
);
396 strbuf_release(&filename
);
397 strbuf_release(&lockname
);
401 /* Return a strftime formatted date/time
402 * NB: the result from this function is to shared memory
404 static char *sprintftime(const char *format
, time_t time
)
412 strftime(buf
, sizeof(buf
)-1, format
, tm
);
416 int cache_ls(const char *path
)
421 struct cache_slot slot
= { NULL
};
422 struct strbuf fullname
= STRBUF_INIT
;
426 cache_log("[cgit] cache path not specified\n");
432 cache_log("[cgit] unable to open path %s: %s (%d)\n",
433 path
, strerror(err
), err
);
436 strbuf_addstr(&fullname
, path
);
437 strbuf_ensure_end(&fullname
, '/');
438 prefixlen
= fullname
.len
;
439 while ((ent
= readdir(dir
)) != NULL
) {
440 if (strlen(ent
->d_name
) != 8)
442 strbuf_setlen(&fullname
, prefixlen
);
443 strbuf_addstr(&fullname
, ent
->d_name
);
444 slot
.cache_name
= fullname
.buf
;
445 if ((err
= open_slot(&slot
)) != 0) {
446 cache_log("[cgit] unable to open path %s: %s (%d)\n",
447 fullname
.buf
, strerror(err
), err
);
450 htmlf("%s %s %10"PRIuMAX
" %s\n",
452 sprintftime("%Y-%m-%d %H:%M:%S",
453 slot
.cache_st
.st_mtime
),
454 (uintmax_t)slot
.cache_st
.st_size
,
459 strbuf_release(&fullname
);
463 /* Print a message to stdout */
464 void cache_log(const char *format
, ...)
467 va_start(args
, format
);
468 vfprintf(stderr
, format
, args
);