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