Add a target size for the cache, and prune the cache when it gets larger.
[bluesky.git] / bluesky / log.c
1 /* Blue Sky: File Systems in the Cloud
2  *
3  * Copyright (C) 2010  The Regents of the University of California
4  * Written by Michael Vrable <mvrable@cs.ucsd.edu>
5  *
6  * TODO: Licensing
7  */
8
9 #define _GNU_SOURCE
10 #define _ATFILE_SOURCE
11
12 #include <stdio.h>
13 #include <stdint.h>
14 #include <stdlib.h>
15 #include <glib.h>
16 #include <string.h>
17 #include <errno.h>
18 #include <sys/types.h>
19 #include <sys/stat.h>
20 #include <fcntl.h>
21 #include <unistd.h>
22 #include <sys/mman.h>
23
24 #include "bluesky-private.h"
25
26 /* The logging layer for BlueSky.  This is used to write filesystem changes
27  * durably to disk so that they can be recovered in the event of a system
28  * crash. */
29
30 /* The logging layer takes care out writing out a sequence of log records to
31  * disk.  On disk, each record consists of a header, a data payload, and a
32  * footer.  The footer contains a checksum of the record, meant to help with
33  * identifying corrupt log records (we would assume because the log record was
34  * only incompletely written out before a crash, which should only happen for
35  * log records that were not considered committed). */
36
37 // Rough size limit for a log segment.  This is not a firm limit and there are
38 // no absolute guarantees on the size of a log segment.
39 #define LOG_SEGMENT_SIZE (1 << 22)
40
41 // Target amount of disk space to use for the journal and cache files, in
42 // kilobytes.
43 #define DISK_CACHE_SIZE_TARGET (64 * 1024)
44
45 #define HEADER_MAGIC 0x676f4c0a
46 #define FOOTER_MAGIC 0x2e435243
47
48 struct log_header {
49     uint32_t magic;             // HEADER_MAGIC
50     uint64_t offset;            // Starting byte offset of the log header
51     uint32_t size;              // Size of the data item (bytes)
52     BlueSkyCloudID id;          // Object identifier
53 } __attribute__((packed));
54
55 struct log_footer {
56     uint32_t magic;             // FOOTER_MAGIC
57     uint32_t crc;               // Computed from log_header to log_footer.magic
58 } __attribute__((packed));
59
60 static void writebuf(int fd, const char *buf, size_t len)
61 {
62     while (len > 0) {
63         ssize_t written;
64         written = write(fd, buf, len);
65         if (written < 0 && errno == EINTR)
66             continue;
67         g_assert(written >= 0);
68         buf += written;
69         len -= written;
70     }
71 }
72
73 static void log_commit(BlueSkyLog *log)
74 {
75     int batchsize = 0;
76
77     if (log->fd < 0)
78         return;
79
80     fdatasync(log->fd);
81     while (log->committed != NULL) {
82         BlueSkyCloudLog *item = (BlueSkyCloudLog *)log->committed->data;
83         g_mutex_lock(item->lock);
84         bluesky_cloudlog_stats_update(item, -1);
85         item->pending_write &= ~CLOUDLOG_JOURNAL;
86         item->location_flags |= CLOUDLOG_JOURNAL;
87         bluesky_cloudlog_stats_update(item, 1);
88         g_cond_signal(item->cond);
89         g_mutex_unlock(item->lock);
90         log->committed = g_slist_delete_link(log->committed, log->committed);
91         bluesky_cloudlog_unref(item);
92         batchsize++;
93     }
94
95     if (bluesky_verbose && batchsize > 1)
96         g_print("Log batch size: %d\n", batchsize);
97 }
98
99 static gboolean log_open(BlueSkyLog *log)
100 {
101     char logname[64];
102
103     if (log->fd >= 0) {
104         log_commit(log);
105         close(log->fd);
106         log->seq_num++;
107         log->fd = -1;
108     }
109
110     if (log->current_log != NULL) {
111         bluesky_cachefile_unref(log->current_log);
112         log->current_log = NULL;
113     }
114
115     while (log->fd < 0) {
116         g_snprintf(logname, sizeof(logname), "journal-%08d", log->seq_num);
117         log->fd = openat(log->dirfd, logname, O_CREAT|O_WRONLY|O_EXCL, 0600);
118         if (log->fd < 0 && errno == EEXIST) {
119             fprintf(stderr, "Log file %s already exists...\n", logname);
120             log->seq_num++;
121             continue;
122         } else if (log->fd < 0) {
123             fprintf(stderr, "Error opening logfile %s: %m\n", logname);
124             return FALSE;
125         }
126     }
127
128     log->current_log = bluesky_cachefile_lookup(log->fs, -1, log->seq_num);
129     g_assert(log->current_log != NULL);
130     g_mutex_unlock(log->current_log->lock);
131
132     if (ftruncate(log->fd, LOG_SEGMENT_SIZE) < 0) {
133         fprintf(stderr, "Unable to truncate logfile %s: %m\n", logname);
134     }
135     fsync(log->fd);
136     fsync(log->dirfd);
137     return TRUE;
138 }
139
140 /* All log writes (at least for a single log) are made by one thread, so we
141  * don't need to worry about concurrent access to the log file.  Log items to
142  * write are pulled off a queue (and so may be posted by any thread).
143  * fdatasync() is used to ensure the log items are stable on disk.
144  *
145  * The log is broken up into separate files, roughly of size LOG_SEGMENT_SIZE
146  * each.  If a log segment is not currently open (log->fd is negative), a new
147  * one is created.  Log segment filenames are assigned sequentially.
148  *
149  * Log replay ought to be implemented later, and ought to set the initial
150  * sequence number appropriately.
151  */
152 static gpointer log_thread(gpointer d)
153 {
154     BlueSkyLog *log = (BlueSkyLog *)d;
155
156     while (TRUE) {
157         if (log->fd < 0) {
158             if (!log_open(log)) {
159                 return NULL;
160             }
161         }
162
163         BlueSkyCloudLog *item
164             = (BlueSkyCloudLog *)g_async_queue_pop(log->queue);
165         g_mutex_lock(item->lock);
166         g_assert(item->data != NULL);
167
168         /* The item may have already been written to the journal... */
169         if ((item->location_flags | item->pending_write) & CLOUDLOG_JOURNAL) {
170             g_mutex_unlock(item->lock);
171             bluesky_cloudlog_unref(item);
172             g_atomic_int_add(&item->data_lock_count, -1);
173             continue;
174         }
175
176         bluesky_cloudlog_stats_update(item, -1);
177         item->pending_write |= CLOUDLOG_JOURNAL;
178         bluesky_cloudlog_stats_update(item, 1);
179
180         struct log_header header;
181         struct log_footer footer;
182         size_t size = sizeof(header) + sizeof(footer) + item->data->len;
183         off_t offset = 0;
184         if (log->fd >= 0)
185             offset = lseek(log->fd, 0, SEEK_CUR);
186
187         /* Check whether the item would overflow the allocated journal size.
188          * If so, start a new log segment.  We only allow oversized log
189          * segments if they contain a single log entry. */
190         if (offset + size >= LOG_SEGMENT_SIZE && offset > 0) {
191             log_open(log);
192             offset = 0;
193         }
194
195         header.magic = GUINT32_TO_LE(HEADER_MAGIC);
196         header.offset = GUINT64_TO_LE(offset);
197         header.size = GUINT32_TO_LE(item->data->len);
198         header.id = item->id;
199         footer.magic = GUINT32_TO_LE(FOOTER_MAGIC);
200
201         uint32_t crc = BLUESKY_CRC32C_SEED;
202
203         writebuf(log->fd, (const char *)&header, sizeof(header));
204         crc = crc32c(crc, (const char *)&header, sizeof(header));
205
206         writebuf(log->fd, item->data->data, item->data->len);
207         crc = crc32c(crc, item->data->data, item->data->len);
208
209         crc = crc32c(crc, (const char *)&footer,
210                      sizeof(footer) - sizeof(uint32_t));
211         footer.crc = crc32c_finalize(crc);
212         writebuf(log->fd, (const char *)&footer, sizeof(footer));
213
214         item->log_seq = log->seq_num;
215         item->log_offset = offset + sizeof(header);
216         item->log_size = item->data->len;
217
218         offset += sizeof(header) + sizeof(footer) + item->data->len;
219
220         /* Since we have just written a new dirty object to the journal,
221          * increment the count of live dirty objects in that journal file.  The
222          * count will be decremented when objects are deleted or written to the
223          * cloud. */
224         if (!(item->location_flags & CLOUDLOG_CLOUD)) {
225             g_atomic_int_add(&log->current_log->dirty_refs, 1);
226             item->dirty_journal = log->current_log;
227         }
228
229         /* Replace the log item's string data with a memory-mapped copy of the
230          * data, now that it has been written to the log file.  (Even if it
231          * isn't yet on disk, it should at least be in the page cache and so
232          * available to memory map.) */
233         bluesky_string_unref(item->data);
234         item->data = NULL;
235         bluesky_cloudlog_fetch(item);
236
237         log->committed  = g_slist_prepend(log->committed, item);
238         g_atomic_int_add(&item->data_lock_count, -1);
239         g_mutex_unlock(item->lock);
240
241         /* Force an if there are no other log items currently waiting to be
242          * written. */
243         if (g_async_queue_length(log->queue) <= 0)
244             log_commit(log);
245     }
246
247     return NULL;
248 }
249
250 BlueSkyLog *bluesky_log_new(const char *log_directory)
251 {
252     BlueSkyLog *log = g_new0(BlueSkyLog, 1);
253
254     log->log_directory = g_strdup(log_directory);
255     log->fd = -1;
256     log->seq_num = 0;
257     log->queue = g_async_queue_new();
258     log->mmap_lock = g_mutex_new();
259     log->mmap_cache = g_hash_table_new(g_str_hash, g_str_equal);
260
261     log->dirfd = open(log->log_directory, O_DIRECTORY);
262     if (log->dirfd < 0) {
263         fprintf(stderr, "Unable to open logging directory: %m\n");
264         return NULL;
265     }
266
267     g_thread_create(log_thread, log, FALSE, NULL);
268
269     return log;
270 }
271
272 void bluesky_log_item_submit(BlueSkyCloudLog *item, BlueSkyLog *log)
273 {
274     bluesky_cloudlog_ref(item);
275     g_atomic_int_add(&item->data_lock_count, 1);
276     g_async_queue_push(log->queue, item);
277 }
278
279 void bluesky_log_finish_all(GList *log_items)
280 {
281     while (log_items != NULL) {
282         BlueSkyCloudLog *item = (BlueSkyCloudLog *)log_items->data;
283
284         g_mutex_lock(item->lock);
285         while ((item->pending_write & CLOUDLOG_JOURNAL))
286             g_cond_wait(item->cond, item->lock);
287         g_mutex_unlock(item->lock);
288         bluesky_cloudlog_unref(item);
289
290         log_items = g_list_delete_link(log_items, log_items);
291     }
292 }
293
294 /* Memory-map the given log object into memory (read-only) and return a pointer
295  * to it. */
296 static int page_size = 0;
297
298 void bluesky_cachefile_unref(BlueSkyCacheFile *cachefile)
299 {
300     g_atomic_int_add(&cachefile->refcount, -1);
301 }
302
303 static void cloudlog_fetch_complete(BlueSkyStoreAsync *async,
304                                     BlueSkyCacheFile *cachefile)
305 {
306     g_print("Fetch of %s from cloud complete, status = %d\n",
307             async->key, async->result);
308
309     if (async->result < 0)
310         return;
311
312     g_mutex_lock(cachefile->lock);
313     char *pathname = g_strdup_printf("%s/%s", cachefile->log->log_directory,
314                                      cachefile->filename);
315     if (!g_file_set_contents(pathname, async->data->data, async->data->len,
316                              NULL))
317     {
318         g_print("Error writing out fetched file to cache!\n");
319     }
320     g_free(pathname);
321     cachefile->fetching = FALSE;
322     cachefile->ready = TRUE;
323     bluesky_cachefile_unref(cachefile);
324     g_cond_broadcast(cachefile->cond);
325     g_mutex_unlock(cachefile->lock);
326 }
327
328 /* Find the BlueSkyCacheFile object for the given journal or cloud log segment.
329  * Returns the object in the locked state and with a reference taken. */
330 BlueSkyCacheFile *bluesky_cachefile_lookup(BlueSkyFS *fs,
331                                            int clouddir, int log_seq)
332 {
333     if (page_size == 0) {
334         page_size = getpagesize();
335     }
336
337     BlueSkyLog *log = fs->log;
338
339     struct stat statbuf;
340     char logname[64];
341     int type;
342
343     // A request for a local log file
344     if (clouddir < 0) {
345         sprintf(logname, "journal-%08d", log_seq);
346         type = CLOUDLOG_JOURNAL;
347     } else {
348         sprintf(logname, "log-%08d-%08d", clouddir, log_seq);
349         type = CLOUDLOG_CLOUD;
350     }
351
352     BlueSkyCacheFile *map;
353     g_mutex_lock(log->mmap_lock);
354     map = g_hash_table_lookup(log->mmap_cache, logname);
355
356     if (map == NULL
357         && type == CLOUDLOG_JOURNAL
358         && fstatat(log->dirfd, logname, &statbuf, 0) < 0) {
359         /* A stale reference to a journal file which doesn't exist any longer
360          * because it was reclaimed.  Return NULL. */
361     } else if (map == NULL) {
362         g_print("Adding cache file %s\n", logname);
363
364         map = g_new0(BlueSkyCacheFile, 1);
365         map->type = type;
366         map->lock = g_mutex_new();
367         map->type = type;
368         g_mutex_lock(map->lock);
369         map->cond = g_cond_new();
370         map->filename = g_strdup(logname);
371         map->log_seq = log_seq;
372         map->log = log;
373         g_atomic_int_set(&map->mapcount, 0);
374         g_atomic_int_set(&map->refcount, 0);
375
376         g_hash_table_insert(log->mmap_cache, map->filename, map);
377
378         // If the log file is stored in the cloud, we may need to fetch it
379         if (clouddir >= 0) {
380             g_atomic_int_inc(&map->refcount);
381             map->fetching = TRUE;
382             g_print("Starting fetch of %s from cloud\n", logname);
383             BlueSkyStoreAsync *async = bluesky_store_async_new(fs->store);
384             async->op = STORE_OP_GET;
385             async->key = g_strdup(logname);
386             bluesky_store_async_add_notifier(async,
387                                              (GFunc)cloudlog_fetch_complete,
388                                              map);
389             bluesky_store_async_submit(async);
390             bluesky_store_async_unref(async);
391         }
392     } else {
393         g_mutex_lock(map->lock);
394     }
395
396     g_mutex_unlock(log->mmap_lock);
397     if (map != NULL)
398         g_atomic_int_inc(&map->refcount);
399     return map;
400 }
401
402 BlueSkyRCStr *bluesky_log_map_object(BlueSkyFS *fs, int log_dir,
403                                      int log_seq, int log_offset, int log_size)
404 {
405     if (page_size == 0) {
406         page_size = getpagesize();
407     }
408
409     BlueSkyLog *log = fs->log;
410     BlueSkyCacheFile *map = bluesky_cachefile_lookup(fs, log_dir, log_seq);
411
412     if (map == NULL) {
413         return NULL;
414     }
415
416     if (map->addr == NULL) {
417         while (!map->ready && map->fetching) {
418             g_print("Waiting for log segment to be fetched from cloud...\n");
419             g_cond_wait(map->cond, map->lock);
420         }
421
422         int fd = openat(log->dirfd, map->filename, O_RDONLY);
423
424         if (fd < 0) {
425             fprintf(stderr, "Error opening logfile %s: %m\n", map->filename);
426             bluesky_cachefile_unref(map);
427             g_mutex_unlock(map->lock);
428             return NULL;
429         }
430
431         off_t length = lseek(fd, 0, SEEK_END);
432         map->addr = (const char *)mmap(NULL, length, PROT_READ, MAP_SHARED,
433                                        fd, 0);
434         g_atomic_int_add(&log->disk_used, -(map->len / 1024));
435         map->len = length;
436         g_atomic_int_add(&log->disk_used, map->len / 1024);
437
438         g_print("Re-mapped log segment %d...\n", log_seq);
439         g_atomic_int_inc(&map->refcount);
440
441         close(fd);
442     }
443
444     g_mutex_unlock(log->mmap_lock);
445
446     BlueSkyRCStr *str;
447     map->atime = bluesky_get_current_time();
448     str = bluesky_string_new_from_mmap(map, log_offset, log_size);
449     bluesky_cachefile_unref(map);
450     g_mutex_unlock(map->lock);
451     return str;
452 }
453
454 void bluesky_mmap_unref(BlueSkyCacheFile *mmap)
455 {
456     if (mmap == NULL)
457         return;
458
459     if (g_atomic_int_dec_and_test(&mmap->mapcount)) {
460         g_mutex_lock(mmap->lock);
461         if (g_atomic_int_get(&mmap->mapcount) == 0) {
462             g_print("Unmapped log segment %d...\n", mmap->log_seq);
463             munmap((void *)mmap->addr, mmap->len);
464             mmap->addr = NULL;
465             g_atomic_int_add(&mmap->refcount, -1);
466         }
467         g_mutex_unlock(mmap->lock);
468     }
469 }
470
471 /* Scan through all currently-stored files in the journal/cache and garbage
472  * collect old unused ones, if needed. */
473 static void gather_cachefiles(gpointer key, gpointer value, gpointer user_data)
474 {
475     GList **files = (GList **)user_data;
476     *files = g_list_prepend(*files, value);
477 }
478
479 static gint compare_cachefiles(gconstpointer a, gconstpointer b)
480 {
481     int64_t ta, tb;
482
483     ta = ((BlueSkyCacheFile *)a)->atime;
484     tb = ((BlueSkyCacheFile *)b)->atime;
485     if (ta < tb)
486         return -1;
487     else if (ta > tb)
488         return 1;
489     else
490         return 0;
491 }
492
493 void bluesky_cachefile_gc(BlueSkyFS *fs)
494 {
495     GList *files = NULL;
496
497     g_mutex_lock(fs->log->mmap_lock);
498     g_hash_table_foreach(fs->log->mmap_cache, gather_cachefiles, &files);
499
500     /* Sort based on atime.  The atime should be stable since it shouln't be
501      * updated except by threads which can grab the mmap_lock, which we already
502      * hold. */
503     files = g_list_sort(files, compare_cachefiles);
504
505     /* Walk the list of files, starting with the oldest, deleting files if
506      * possible until enough space has been reclaimed. */
507     g_print("\nScanning cache: (total size = %d kB)\n", fs->log->disk_used);
508     while (files != NULL) {
509         BlueSkyCacheFile *cachefile = (BlueSkyCacheFile *)files->data;
510         /* Try to lock the structure, but if the lock is held by another thread
511          * then we'll just skip the file on this pass. */
512         if (g_mutex_trylock(cachefile->lock)) {
513             int64_t age = bluesky_get_current_time() - cachefile->atime;
514             g_print("%s addr=%p mapcount=%d refcount=%d dirty=%d atime_age=%f",
515                     cachefile->filename, cachefile->addr, cachefile->mapcount,
516                     cachefile->refcount, cachefile->dirty_refs, age / 1e6);
517             if (cachefile->fetching)
518                 g_print(" (fetching)");
519             g_print("\n");
520
521             if (g_atomic_int_get(&fs->log->disk_used) > DISK_CACHE_SIZE_TARGET
522                 && g_atomic_int_get(&cachefile->refcount) == 0
523                 && g_atomic_int_get(&cachefile->mapcount) == 0
524                 && g_atomic_int_get(&cachefile->dirty_refs) == 0)
525             {
526                 g_print("   ...deleting\n");
527                 if (unlinkat(fs->log->dirfd, cachefile->filename, 0) < 0) {
528                     fprintf(stderr, "Unable to unlink journal %s: %m\n",
529                             cachefile->filename);
530                 }
531
532                 g_atomic_int_add(&fs->log->disk_used, -(cachefile->len / 1024));
533                 g_hash_table_remove(fs->log->mmap_cache, cachefile->filename);
534                 g_mutex_unlock(cachefile->lock);
535                 g_mutex_free(cachefile->lock);
536                 g_cond_free(cachefile->cond);
537                 g_free(cachefile->filename);
538                 g_free(cachefile);
539             } else {
540                 g_mutex_unlock(cachefile->lock);
541             }
542         }
543         files = g_list_delete_link(files, files);
544     }
545     g_list_free(files);
546
547     g_mutex_unlock(fs->log->mmap_lock);
548 }