1 /* Blue Sky: File Systems in the Cloud
3 * Copyright (C) 2010 The Regents of the University of California
4 * Written by Michael Vrable <mvrable@cs.ucsd.edu>
10 #define _ATFILE_SOURCE
18 #include <sys/types.h>
24 #include "bluesky-private.h"
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
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). */
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)
41 // Target amount of disk space to use for the journal and cache files, in
43 #define DISK_CACHE_SIZE_TARGET (64 * 1024)
45 #define HEADER_MAGIC 0x676f4c0a
46 #define FOOTER_MAGIC 0x2e435243
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));
56 uint32_t magic; // FOOTER_MAGIC
57 uint32_t crc; // Computed from log_header to log_footer.magic
58 } __attribute__((packed));
60 static void writebuf(int fd, const char *buf, size_t len)
64 written = write(fd, buf, len);
65 if (written < 0 && errno == EINTR)
67 g_assert(written >= 0);
73 static void log_commit(BlueSkyLog *log)
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);
95 if (bluesky_verbose && batchsize > 1)
96 g_print("Log batch size: %d\n", batchsize);
99 static gboolean log_open(BlueSkyLog *log)
110 if (log->current_log != NULL) {
111 bluesky_cachefile_unref(log->current_log);
112 log->current_log = NULL;
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);
122 } else if (log->fd < 0) {
123 fprintf(stderr, "Error opening logfile %s: %m\n", logname);
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);
132 if (ftruncate(log->fd, LOG_SEGMENT_SIZE) < 0) {
133 fprintf(stderr, "Unable to truncate logfile %s: %m\n", logname);
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.
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.
149 * Log replay ought to be implemented later, and ought to set the initial
150 * sequence number appropriately.
152 static gpointer log_thread(gpointer d)
154 BlueSkyLog *log = (BlueSkyLog *)d;
158 if (!log_open(log)) {
163 BlueSkyCloudLog *item
164 = (BlueSkyCloudLog *)g_async_queue_pop(log->queue);
165 g_mutex_lock(item->lock);
166 g_assert(item->data != NULL);
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);
176 bluesky_cloudlog_stats_update(item, -1);
177 item->pending_write |= CLOUDLOG_JOURNAL;
178 bluesky_cloudlog_stats_update(item, 1);
180 struct log_header header;
181 struct log_footer footer;
182 size_t size = sizeof(header) + sizeof(footer) + item->data->len;
185 offset = lseek(log->fd, 0, SEEK_CUR);
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) {
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);
201 uint32_t crc = BLUESKY_CRC32C_SEED;
203 writebuf(log->fd, (const char *)&header, sizeof(header));
204 crc = crc32c(crc, (const char *)&header, sizeof(header));
206 writebuf(log->fd, item->data->data, item->data->len);
207 crc = crc32c(crc, item->data->data, item->data->len);
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));
214 item->log_seq = log->seq_num;
215 item->log_offset = offset + sizeof(header);
216 item->log_size = item->data->len;
218 offset += sizeof(header) + sizeof(footer) + item->data->len;
220 /* Replace the log item's string data with a memory-mapped copy of the
221 * data, now that it has been written to the log file. (Even if it
222 * isn't yet on disk, it should at least be in the page cache and so
223 * available to memory map.) */
224 bluesky_string_unref(item->data);
226 bluesky_cloudlog_fetch(item);
228 log->committed = g_slist_prepend(log->committed, item);
229 g_atomic_int_add(&item->data_lock_count, -1);
230 g_mutex_unlock(item->lock);
232 /* Force an if there are no other log items currently waiting to be
234 if (g_async_queue_length(log->queue) <= 0)
241 BlueSkyLog *bluesky_log_new(const char *log_directory)
243 BlueSkyLog *log = g_new0(BlueSkyLog, 1);
245 log->log_directory = g_strdup(log_directory);
248 log->queue = g_async_queue_new();
249 log->mmap_lock = g_mutex_new();
250 log->mmap_cache = g_hash_table_new(g_str_hash, g_str_equal);
252 log->dirfd = open(log->log_directory, O_DIRECTORY);
253 if (log->dirfd < 0) {
254 fprintf(stderr, "Unable to open logging directory: %m\n");
258 g_thread_create(log_thread, log, FALSE, NULL);
263 void bluesky_log_item_submit(BlueSkyCloudLog *item, BlueSkyLog *log)
265 bluesky_cloudlog_ref(item);
266 g_atomic_int_add(&item->data_lock_count, 1);
267 g_async_queue_push(log->queue, item);
270 void bluesky_log_finish_all(GList *log_items)
272 while (log_items != NULL) {
273 BlueSkyCloudLog *item = (BlueSkyCloudLog *)log_items->data;
275 g_mutex_lock(item->lock);
276 while ((item->pending_write & CLOUDLOG_JOURNAL))
277 g_cond_wait(item->cond, item->lock);
278 g_mutex_unlock(item->lock);
279 bluesky_cloudlog_unref(item);
281 log_items = g_list_delete_link(log_items, log_items);
285 /* Memory-map the given log object into memory (read-only) and return a pointer
287 static int page_size = 0;
289 void bluesky_cachefile_unref(BlueSkyCacheFile *cachefile)
291 g_atomic_int_add(&cachefile->refcount, -1);
294 static void cloudlog_fetch_complete(BlueSkyStoreAsync *async,
295 BlueSkyCacheFile *cachefile);
297 static void cloudlog_fetch_start(BlueSkyCacheFile *cachefile)
299 g_atomic_int_inc(&cachefile->refcount);
300 cachefile->fetching = TRUE;
301 g_print("Starting fetch of %s from cloud\n", cachefile->filename);
302 BlueSkyStoreAsync *async = bluesky_store_async_new(cachefile->fs->store);
303 async->op = STORE_OP_GET;
304 async->key = g_strdup(cachefile->filename);
305 bluesky_store_async_add_notifier(async,
306 (GFunc)cloudlog_fetch_complete,
308 bluesky_store_async_submit(async);
309 bluesky_store_async_unref(async);
312 static void cloudlog_fetch_complete(BlueSkyStoreAsync *async,
313 BlueSkyCacheFile *cachefile)
315 g_print("Fetch of %s from cloud complete, status = %d\n",
316 async->key, async->result);
318 g_mutex_lock(cachefile->lock);
319 if (async->result >= 0) {
320 char *pathname = g_strdup_printf("%s/%s",
321 cachefile->log->log_directory,
322 cachefile->filename);
323 if (!g_file_set_contents(pathname, async->data->data, async->data->len,
325 g_print("Error writing out fetched file to cache!\n");
328 cachefile->fetching = FALSE;
329 cachefile->ready = TRUE;
331 g_print("Error fetching from cloud, retrying...\n");
332 cloudlog_fetch_start(cachefile);
335 bluesky_cachefile_unref(cachefile);
336 g_cond_broadcast(cachefile->cond);
337 g_mutex_unlock(cachefile->lock);
340 /* Find the BlueSkyCacheFile object for the given journal or cloud log segment.
341 * Returns the object in the locked state and with a reference taken. */
342 BlueSkyCacheFile *bluesky_cachefile_lookup(BlueSkyFS *fs,
343 int clouddir, int log_seq)
345 if (page_size == 0) {
346 page_size = getpagesize();
349 BlueSkyLog *log = fs->log;
355 // A request for a local log file
357 sprintf(logname, "journal-%08d", log_seq);
358 type = CLOUDLOG_JOURNAL;
360 sprintf(logname, "log-%08d-%08d", clouddir, log_seq);
361 type = CLOUDLOG_CLOUD;
364 BlueSkyCacheFile *map;
365 g_mutex_lock(log->mmap_lock);
366 map = g_hash_table_lookup(log->mmap_cache, logname);
369 && type == CLOUDLOG_JOURNAL
370 && fstatat(log->dirfd, logname, &statbuf, 0) < 0) {
371 /* A stale reference to a journal file which doesn't exist any longer
372 * because it was reclaimed. Return NULL. */
373 } else if (map == NULL) {
374 g_print("Adding cache file %s\n", logname);
376 map = g_new0(BlueSkyCacheFile, 1);
379 map->lock = g_mutex_new();
381 g_mutex_lock(map->lock);
382 map->cond = g_cond_new();
383 map->filename = g_strdup(logname);
384 map->log_seq = log_seq;
386 g_atomic_int_set(&map->mapcount, 0);
387 g_atomic_int_set(&map->refcount, 0);
389 g_hash_table_insert(log->mmap_cache, map->filename, map);
391 // If the log file is stored in the cloud, we may need to fetch it
393 cloudlog_fetch_start(map);
395 g_mutex_lock(map->lock);
398 g_mutex_unlock(log->mmap_lock);
400 g_atomic_int_inc(&map->refcount);
404 BlueSkyRCStr *bluesky_log_map_object(BlueSkyFS *fs, int log_dir,
405 int log_seq, int log_offset, int log_size)
407 if (page_size == 0) {
408 page_size = getpagesize();
411 BlueSkyLog *log = fs->log;
412 BlueSkyCacheFile *map = bluesky_cachefile_lookup(fs, log_dir, log_seq);
418 if (map->addr == NULL) {
419 while (!map->ready && map->fetching) {
420 g_print("Waiting for log segment to be fetched from cloud...\n");
421 g_cond_wait(map->cond, map->lock);
424 int fd = openat(log->dirfd, map->filename, O_RDONLY);
427 fprintf(stderr, "Error opening logfile %s: %m\n", map->filename);
428 bluesky_cachefile_unref(map);
429 g_mutex_unlock(map->lock);
433 off_t length = lseek(fd, 0, SEEK_END);
434 map->addr = (const char *)mmap(NULL, length, PROT_READ, MAP_SHARED,
436 g_atomic_int_add(&log->disk_used, -(map->len / 1024));
438 g_atomic_int_add(&log->disk_used, map->len / 1024);
440 g_print("Re-mapped log segment %d...\n", log_seq);
441 g_atomic_int_inc(&map->refcount);
446 g_mutex_unlock(log->mmap_lock);
449 map->atime = bluesky_get_current_time();
450 str = bluesky_string_new_from_mmap(map, log_offset, log_size);
451 bluesky_cachefile_unref(map);
452 g_mutex_unlock(map->lock);
456 void bluesky_mmap_unref(BlueSkyCacheFile *mmap)
461 if (g_atomic_int_dec_and_test(&mmap->mapcount)) {
462 g_mutex_lock(mmap->lock);
463 if (g_atomic_int_get(&mmap->mapcount) == 0) {
464 g_print("Unmapped log segment %d...\n", mmap->log_seq);
465 munmap((void *)mmap->addr, mmap->len);
467 g_atomic_int_add(&mmap->refcount, -1);
469 g_mutex_unlock(mmap->lock);
473 /* Scan through all currently-stored files in the journal/cache and garbage
474 * collect old unused ones, if needed. */
475 static void gather_cachefiles(gpointer key, gpointer value, gpointer user_data)
477 GList **files = (GList **)user_data;
478 *files = g_list_prepend(*files, value);
481 static gint compare_cachefiles(gconstpointer a, gconstpointer b)
485 ta = ((BlueSkyCacheFile *)a)->atime;
486 tb = ((BlueSkyCacheFile *)b)->atime;
495 void bluesky_cachefile_gc(BlueSkyFS *fs)
499 g_mutex_lock(fs->log->mmap_lock);
500 g_hash_table_foreach(fs->log->mmap_cache, gather_cachefiles, &files);
502 /* Sort based on atime. The atime should be stable since it shouln't be
503 * updated except by threads which can grab the mmap_lock, which we already
505 files = g_list_sort(files, compare_cachefiles);
507 /* Walk the list of files, starting with the oldest, deleting files if
508 * possible until enough space has been reclaimed. */
509 g_print("\nScanning cache: (total size = %d kB)\n", fs->log->disk_used);
510 while (files != NULL) {
511 BlueSkyCacheFile *cachefile = (BlueSkyCacheFile *)files->data;
512 /* Try to lock the structure, but if the lock is held by another thread
513 * then we'll just skip the file on this pass. */
514 if (g_mutex_trylock(cachefile->lock)) {
515 int64_t age = bluesky_get_current_time() - cachefile->atime;
516 g_print("%s addr=%p mapcount=%d refcount=%d atime_age=%f",
517 cachefile->filename, cachefile->addr, cachefile->mapcount,
518 cachefile->refcount, age / 1e6);
519 if (cachefile->fetching)
520 g_print(" (fetching)");
523 if (g_atomic_int_get(&fs->log->disk_used) > DISK_CACHE_SIZE_TARGET
524 && g_atomic_int_get(&cachefile->refcount) == 0
525 && g_atomic_int_get(&cachefile->mapcount) == 0)
527 g_print(" ...deleting\n");
528 if (unlinkat(fs->log->dirfd, cachefile->filename, 0) < 0) {
529 fprintf(stderr, "Unable to unlink journal %s: %m\n",
530 cachefile->filename);
533 g_atomic_int_add(&fs->log->disk_used, -(cachefile->len / 1024));
534 g_hash_table_remove(fs->log->mmap_cache, cachefile->filename);
535 g_mutex_unlock(cachefile->lock);
536 g_mutex_free(cachefile->lock);
537 g_cond_free(cachefile->cond);
538 g_free(cachefile->filename);
541 g_mutex_unlock(cachefile->lock);
544 files = g_list_delete_link(files, files);
548 g_mutex_unlock(fs->log->mmap_lock);