1 /* Blue Sky: File Systems in the Cloud
3 * Copyright (C) 2009 The Regents of the University of California
4 * Written by Michael Vrable <mvrable@cs.ucsd.edu>
14 #include "bluesky-private.h"
16 // Rough size limit for a log segment. This is not a firm limit and there are
17 // no absolute guarantees on the size of a log segment.
18 #define CLOUDLOG_SEGMENT_SIZE (4 << 20)
20 // Maximum number of segments to attempt to upload concurrently
21 int cloudlog_concurrent_uploads = 32;
23 BlueSkyCloudID bluesky_cloudlog_new_id()
26 bluesky_crypt_random_bytes((uint8_t *)&id.bytes, sizeof(id));
30 gchar *bluesky_cloudlog_id_to_string(BlueSkyCloudID id)
32 char buf[sizeof(BlueSkyCloudID) * 2 + 1];
35 for (int i = 0; i < sizeof(BlueSkyCloudID); i++) {
36 sprintf(&buf[2*i], "%02x", (uint8_t)(id.bytes[i]));
42 BlueSkyCloudID bluesky_cloudlog_id_from_string(const gchar *idstr)
45 memset(&id, 0, sizeof(id));
46 for (int i = 0; i < 2*sizeof(BlueSkyCloudID); i++) {
49 g_warning("Short cloud id: %s\n", idstr);
53 if (c >= '0' && c <= '9')
55 else if (c >= 'a' && c <= 'f')
58 g_warning("Bad character in cloud id: %s\n", idstr);
59 id.bytes[i / 2] += val << (i % 2 ? 0 : 4);
64 gboolean bluesky_cloudlog_equal(gconstpointer a, gconstpointer b)
66 BlueSkyCloudID *id1 = (BlueSkyCloudID *)a, *id2 = (BlueSkyCloudID *)b;
68 return memcmp(id1, id2, sizeof(BlueSkyCloudID)) == 0;
71 guint bluesky_cloudlog_hash(gconstpointer a)
73 BlueSkyCloudID *id = (BlueSkyCloudID *)a;
75 // Assume that bits in the ID are randomly chosen so that any subset of the
76 // bits can be used as a hash key.
77 return *(guint *)(&id->bytes);
80 /* Formatting of cloud log segments. This handles grouping items together
81 * before writing a batch to the cloud, handling indirection through items like
82 * the inode map, etc. */
84 BlueSkyCloudLog *bluesky_cloudlog_new(BlueSkyFS *fs, const BlueSkyCloudID *id)
86 BlueSkyCloudLog *log = g_new0(BlueSkyCloudLog, 1);
88 log->lock = g_mutex_new();
89 log->cond = g_cond_new();
91 log->type = LOGTYPE_UNKNOWN;
93 memcpy(&log->id, id, sizeof(BlueSkyCloudID));
95 log->id = bluesky_cloudlog_new_id();
96 log->links = g_array_new(FALSE, TRUE, sizeof(BlueSkyCloudLog *));
97 g_atomic_int_set(&log->refcount, 1);
102 /* Helper function for updating memory usage statistics for a filesystem (the
103 * cache_log_* variables). This will increment (type=1) or decrement (type=-1)
104 * the counter associated with the current state of the cloud log item. The
105 * item should be locked or otherwise protected from concurrent access. */
106 void bluesky_cloudlog_stats_update(BlueSkyCloudLog *log, int type)
108 BlueSkyFS *fs = log->fs;
110 if (log->location_flags & CLOUDLOG_CLOUD) {
111 g_atomic_int_add(&fs->cache_log_cloud, type);
112 } else if (log->location_flags & CLOUDLOG_JOURNAL) {
113 g_atomic_int_add(&fs->cache_log_journal, type);
114 } else if (log->pending_write & CLOUDLOG_JOURNAL) {
115 g_atomic_int_add(&fs->cache_log_journal, type);
116 } else if (log->data != NULL) {
117 g_atomic_int_add(&fs->cache_log_dirty, type);
121 /* The reference held by the hash table does not count towards the reference
122 * count. When a new object is created, it initially has a reference count of
123 * 1 for the creator, and similarly fetching an item from the hash table will
124 * also create a reference. If the reference count drops to zero,
125 * bluesky_cloudlog_unref attempts to remove the object from the hash
126 * table--but there is a potential race since another thread might read the
127 * object from the hash table at the same time. So an object with a reference
128 * count of zero may still be resurrected, in which case we need to abort the
129 * destruction. Once the object is gone from the hash table, and if the
130 * reference count is still zero, it can actually be deleted. */
131 void bluesky_cloudlog_ref(BlueSkyCloudLog *log)
136 g_atomic_int_inc(&log->refcount);
139 void bluesky_cloudlog_unref(BlueSkyCloudLog *log)
144 if (g_atomic_int_dec_and_test(&log->refcount)) {
145 BlueSkyFS *fs = log->fs;
147 g_mutex_lock(fs->lock);
148 if (g_atomic_int_get(&log->refcount) > 0) {
149 g_mutex_unlock(fs->lock);
153 if (!g_hash_table_remove(fs->locations, &log->id)) {
155 g_warning("Could not find and remove cloud log item from hash table!");
157 g_mutex_unlock(fs->lock);
159 bluesky_cloudlog_stats_update(log, -1);
160 log->type = LOGTYPE_INVALID;
161 g_mutex_free(log->lock);
162 g_cond_free(log->cond);
163 for (int i = 0; i < log->links->len; i++) {
164 BlueSkyCloudLog *c = g_array_index(log->links,
165 BlueSkyCloudLog *, i);
166 bluesky_cloudlog_unref(c);
168 g_array_unref(log->links);
169 bluesky_string_unref(log->data);
174 /* For locking reasons cloudlog unrefs may sometimes need to be performed in
175 * the future. We launch a thread for handling these delayed unreference
177 static gpointer cloudlog_unref_thread(gpointer q)
179 GAsyncQueue *queue = (GAsyncQueue *)q;
182 BlueSkyCloudLog *item = (BlueSkyCloudLog *)g_async_queue_pop(queue);
183 bluesky_cloudlog_unref(item);
189 void bluesky_cloudlog_unref_delayed(BlueSkyCloudLog *log)
192 g_async_queue_push(log->fs->unref_queue, log);
195 /* Erase the information contained within the in-memory cloud log
196 * representation. This does not free up the item itself, but frees the data
197 * and references to other log items and resets the type back to unknown. If
198 * the object was written out to persistent storage, all state about it can be
199 * recovered by loading the object back in. The object must be locked before
200 * calling this function. */
201 void bluesky_cloudlog_erase(BlueSkyCloudLog *log)
203 g_assert(log->data_lock_count == 0);
205 if (log->type == LOGTYPE_UNKNOWN)
208 log->type = LOGTYPE_UNKNOWN;
210 bluesky_string_unref(log->data);
212 log->data_lock_count = 0;
214 for (int i = 0; i < log->links->len; i++) {
215 BlueSkyCloudLog *c = g_array_index(log->links,
216 BlueSkyCloudLog *, i);
217 bluesky_cloudlog_unref(c);
219 g_array_unref(log->links);
220 log->links = g_array_new(FALSE, TRUE, sizeof(BlueSkyCloudLog *));
223 /* Start a write of the object to the local log. */
224 void bluesky_cloudlog_sync(BlueSkyCloudLog *log)
226 bluesky_log_item_submit(log, log->fs->log);
229 /* Add the given entry to the global hash table containing cloud log entries.
230 * Takes ownership of the caller's reference. */
231 void bluesky_cloudlog_insert_locked(BlueSkyCloudLog *log)
233 g_hash_table_insert(log->fs->locations, &log->id, log);
236 void bluesky_cloudlog_insert(BlueSkyCloudLog *log)
238 g_mutex_lock(log->fs->lock);
239 bluesky_cloudlog_insert_locked(log);
240 g_mutex_unlock(log->fs->lock);
243 /* Look up the cloud log entry for the given ID. If create is TRUE and the
244 * item does not exist, create a special pending entry that can later be filled
245 * in when the real item is loaded. The returned item has a reference held.
246 * As a special case, if a null ID is provided then NULL is returned. */
247 BlueSkyCloudLog *bluesky_cloudlog_get(BlueSkyFS *fs, BlueSkyCloudID id)
249 static BlueSkyCloudID id0 = {{0}};
251 if (memcmp(&id, &id0, sizeof(BlueSkyCloudID)) == 0)
254 g_mutex_lock(fs->lock);
255 BlueSkyCloudLog *item;
256 item = g_hash_table_lookup(fs->locations, &id);
258 item = bluesky_cloudlog_new(fs, &id);
259 bluesky_cloudlog_stats_update(item, 1);
260 bluesky_cloudlog_insert_locked(item);
262 bluesky_cloudlog_ref(item);
264 g_mutex_unlock(fs->lock);
268 /* Work to fetch a cloudlog item in a background thread. The item will be
269 * locked while the fetch is in progress and unlocked when it completes. */
270 static GThreadPool *fetch_pool;
272 static void background_fetch_task(gpointer p, gpointer unused)
274 BlueSkyCloudLog *item = (BlueSkyCloudLog *)p;
276 g_mutex_lock(item->lock);
277 g_mutex_unlock(item->lock);
278 bluesky_cloudlog_unref(item);
281 void bluesky_cloudlog_background_fetch(BlueSkyCloudLog *item)
283 bluesky_cloudlog_ref(item);
284 g_thread_pool_push(fetch_pool, item, NULL);
287 /* Attempt to prefetch a cloud log item. This does not guarantee that it will
288 * be made available, but does make it more likely that a future call to
289 * bluesky_cloudlog_fetch will complete quickly. Item must be locked? */
290 void bluesky_cloudlog_prefetch(BlueSkyCloudLog *item)
292 if (item->data != NULL)
295 /* When operating in a non log-structured mode, simply start a background
296 * fetch immediately when asked to prefetch. */
297 if (bluesky_options.disable_aggregation) {
298 bluesky_cloudlog_background_fetch(item);
302 /* TODO: Some of the code here is duplicated with bluesky_log_map_object.
303 * Refactor to fix that. */
304 BlueSkyFS *fs = item->fs;
305 BlueSkyCacheFile *map = NULL;
307 /* First, check to see if the journal still contains a copy of the item and
308 * if so update the atime on the journal so it is likely to be kept around
309 * until we need it. */
310 if ((item->location_flags | item->pending_write) & CLOUDLOG_JOURNAL) {
311 map = bluesky_cachefile_lookup(fs, -1, item->log_seq, TRUE);
313 map->atime = bluesky_get_current_time();
314 bluesky_cachefile_unref(map);
315 g_mutex_unlock(map->lock);
320 item->location_flags &= ~CLOUDLOG_JOURNAL;
321 if (!(item->location_flags & CLOUDLOG_CLOUD))
324 map = bluesky_cachefile_lookup(fs,
325 item->location.directory,
326 item->location.sequence,
331 /* At this point, we have information about the log segment containing the
332 * item we need. If our item is already fetched, we have nothing to do
333 * except update the atime. If not, queue up a fetch of our object. */
334 const BlueSkyRangesetItem *rangeitem;
335 rangeitem = bluesky_rangeset_lookup(map->items,
336 item->location.offset);
337 if (rangeitem == NULL) {
338 if (map->prefetches == NULL)
339 map->prefetches = bluesky_rangeset_new();
341 gchar *id = bluesky_cloudlog_id_to_string(item->id);
343 g_print("Need to prefetch %s\n", id);
346 bluesky_rangeset_insert(map->prefetches,
347 item->location.offset,
348 item->location.size, NULL);
350 uint64_t start, length;
351 bluesky_rangeset_get_extents(map->prefetches, &start, &length);
353 g_print("Range to prefetch: %"PRIu64" + %"PRIu64"\n",
357 bluesky_cachefile_unref(map);
358 g_mutex_unlock(map->lock);
361 /* Ensure that a cloud log item is loaded in memory, and if not read it in.
362 * TODO: Make asynchronous, and make this also fetch from the cloud. Right now
363 * we only read from the log. Log item must be locked. */
364 void bluesky_cloudlog_fetch(BlueSkyCloudLog *log)
366 if (log->data != NULL)
369 BlueSkyProfile *profile = bluesky_profile_get();
371 bluesky_profile_add_event(profile, g_strdup_printf("Fetch log entry"));
373 /* There are actually two cases: a full deserialization if we have not ever
374 * read the object before, and a partial deserialization where the metadata
375 * is already in memory and we just need to remap the data. If the object
376 * type has not yet been set, we'll need to read and parse the metadata.
377 * Once that is done, we can fall through the case of remapping the data
379 if (log->type == LOGTYPE_UNKNOWN) {
380 BlueSkyRCStr *raw = bluesky_log_map_object(log, FALSE);
381 g_assert(raw != NULL);
382 bluesky_deserialize_cloudlog(log, raw->data, raw->len);
383 bluesky_string_unref(raw);
386 /* At this point all metadata should be available and we need only remap
387 * the object data. */
388 log->data = bluesky_log_map_object(log, TRUE);
390 if (log->data == NULL) {
391 g_error("Unable to fetch cloudlog entry!");
395 bluesky_profile_add_event(profile, g_strdup_printf("Fetch complete"));
396 g_cond_broadcast(log->cond);
399 BlueSkyCloudPointer bluesky_cloudlog_serialize(BlueSkyCloudLog *log,
402 BlueSkyCloudLogState *state = fs->log_state;
404 if ((log->location_flags | log->pending_write) & CLOUDLOG_CLOUD) {
405 return log->location;
408 for (int i = 0; i < log->links->len; i++) {
409 BlueSkyCloudLog *ref = g_array_index(log->links,
410 BlueSkyCloudLog *, i);
412 bluesky_cloudlog_serialize(ref, fs);
415 /* FIXME: Ought lock to be taken earlier? */
416 g_mutex_lock(log->lock);
417 bluesky_cloudlog_fetch(log);
418 g_assert(log->data != NULL);
420 bluesky_cloudlog_stats_update(log, -1);
422 GString *data1 = g_string_new("");
423 GString *data2 = g_string_new("");
424 GString *data3 = g_string_new("");
425 bluesky_serialize_cloudlog(log, data1, data2, data3);
427 log->location = state->location;
428 log->location.offset = state->data->len;
429 log->data_size = data1->len;
431 struct cloudlog_header header;
432 memcpy(header.magic, CLOUDLOG_MAGIC, 4);
433 memset(header.crypt_auth, sizeof(header.crypt_auth), 0);
434 memset(header.crypt_iv, sizeof(header.crypt_iv), 0);
435 header.type = log->type + '0';
436 header.size1 = GUINT32_TO_LE(data1->len);
437 header.size2 = GUINT32_TO_LE(data2->len);
438 header.size3 = GUINT32_TO_LE(data3->len);
440 header.inum = GUINT64_TO_LE(log->inum);
442 g_string_append_len(state->data, (const char *)&header, sizeof(header));
443 g_string_append_len(state->data, data1->str, data1->len);
444 g_string_append_len(state->data, data2->str, data2->len);
445 g_string_append_len(state->data, data3->str, data3->len);
447 log->location.size = state->data->len - log->location.offset;
449 g_string_free(data1, TRUE);
450 g_string_free(data2, TRUE);
451 g_string_free(data3, TRUE);
453 /* If the object we flushed was an inode, update the inode map. */
454 if (log->type == LOGTYPE_INODE) {
455 g_mutex_lock(fs->lock);
456 InodeMapEntry *entry = bluesky_inode_map_lookup(fs->inode_map,
458 bluesky_cloudlog_unref_delayed(entry->item);
460 bluesky_cloudlog_ref(entry->item);
461 g_mutex_unlock(fs->lock);
464 /* TODO: We should mark the objects as committed on the cloud until the
465 * data is flushed and acknowledged. */
466 log->pending_write |= CLOUDLOG_CLOUD;
467 bluesky_cloudlog_stats_update(log, 1);
468 state->writeback_list = g_slist_prepend(state->writeback_list, log);
469 bluesky_cloudlog_ref(log);
470 g_mutex_unlock(log->lock);
472 if (state->data->len > CLOUDLOG_SEGMENT_SIZE
473 || bluesky_options.disable_aggregation)
475 bluesky_cloudlog_flush(fs);
478 return log->location;
481 static void cloudlog_flush_complete(BlueSkyStoreAsync *async,
482 SerializedRecord *record)
484 g_print("Write of %s to cloud complete, status = %d\n",
485 async->key, async->result);
487 g_mutex_lock(record->lock);
488 if (async->result >= 0) {
489 while (record->items != NULL) {
490 BlueSkyCloudLog *item = (BlueSkyCloudLog *)record->items->data;
491 g_mutex_lock(item->lock);
492 bluesky_cloudlog_stats_update(item, -1);
493 item->pending_write &= ~CLOUDLOG_CLOUD;
494 item->location_flags |= CLOUDLOG_CLOUD;
495 bluesky_cloudlog_stats_update(item, 1);
496 g_mutex_unlock(item->lock);
497 bluesky_cloudlog_unref(item);
499 record->items = g_slist_delete_link(record->items, record->items);
502 bluesky_string_unref(record->data);
504 g_slist_free(record->items);
505 record->items = NULL;
506 record->complete = TRUE;
508 BlueSkyCloudLogState *state = record->fs->log_state;
509 g_mutex_lock(state->uploads_pending_lock);
510 state->uploads_pending--;
511 g_cond_broadcast(state->uploads_pending_cond);
512 g_mutex_unlock(state->uploads_pending_lock);
514 g_cond_broadcast(record->cond);
516 g_print("Write should be resubmitted...\n");
518 BlueSkyStoreAsync *async2 = bluesky_store_async_new(async->store);
519 async2->op = STORE_OP_PUT;
520 async2->key = g_strdup(async->key);
521 async2->data = record->data;
522 async2->profile = async->profile;
523 bluesky_string_ref(record->data);
524 bluesky_store_async_submit(async2);
525 bluesky_store_async_add_notifier(async2,
526 (GFunc)cloudlog_flush_complete,
528 bluesky_store_async_unref(async2);
530 g_mutex_unlock(record->lock);
533 /* Finish up a partially-written cloud log segment and flush it to storage. */
534 static void cloud_flush_background(SerializedRecord *record)
536 bluesky_cloudlog_encrypt(record->raw_data, record->fs->keys);
537 record->data = bluesky_string_new_from_gstring(record->raw_data);
538 record->raw_data = NULL;
540 BlueSkyStoreAsync *async = bluesky_store_async_new(record->fs->store);
541 async->op = STORE_OP_PUT;
542 async->key = record->key;
543 async->data = record->data;
544 bluesky_string_ref(record->data);
545 bluesky_store_async_submit(async);
546 bluesky_store_async_add_notifier(async,
547 (GFunc)cloudlog_flush_complete,
549 bluesky_store_async_unref(async);
552 void bluesky_cloudlog_flush(BlueSkyFS *fs)
554 BlueSkyCloudLogState *state = fs->log_state;
555 if (state->data == NULL || state->data->len == 0)
558 g_mutex_lock(state->uploads_pending_lock);
559 while (state->uploads_pending > cloudlog_concurrent_uploads)
560 g_cond_wait(state->uploads_pending_cond, state->uploads_pending_lock);
561 state->uploads_pending++;
562 g_mutex_unlock(state->uploads_pending_lock);
564 /* TODO: Append some type of commit record to the log segment? */
566 g_print("Serializing %zd bytes of data to cloud\n", state->data->len);
567 SerializedRecord *record = g_new0(SerializedRecord, 1);
569 record->raw_data = state->data;
571 record->items = state->writeback_list;
572 record->lock = g_mutex_new();
573 record->cond = g_cond_new();
574 state->writeback_list = NULL;
576 record->key = g_strdup_printf("log-%08d-%08d",
577 state->location.directory,
578 state->location.sequence);
580 state->pending_segments = g_list_prepend(state->pending_segments, record);
582 /* Encryption of data and upload happen in the background, for additional
583 * parallelism when uploading large amounts of data. */
584 g_thread_create((GThreadFunc)cloud_flush_background, record, FALSE, NULL);
586 state->location.sequence++;
587 state->location.offset = 0;
588 state->data = g_string_new("");
591 /* Make an encryption pass over a cloud log segment to encrypt private data in
593 void bluesky_cloudlog_encrypt(GString *segment, BlueSkyCryptKeys *keys)
595 char *data = segment->str;
596 size_t remaining_size = segment->len;
598 while (remaining_size >= sizeof(struct cloudlog_header)) {
599 struct cloudlog_header *header = (struct cloudlog_header *)data;
600 size_t item_size = sizeof(struct cloudlog_header)
601 + GUINT32_FROM_LE(header->size1)
602 + GUINT32_FROM_LE(header->size2)
603 + GUINT32_FROM_LE(header->size3);
604 if (item_size > remaining_size)
606 bluesky_crypt_block_encrypt(data, item_size, keys);
609 remaining_size -= item_size;
613 /* Make an decryption pass over a cloud log segment to decrypt items which were
614 * encrypted. Also computes a list of all offsets which at which valid
615 * cloud log items are found and adds those offsets to items (if non-NULL).
617 * If allow_unauth is set to true, then allow a limited set of unauthenticated
618 * items that may have been rewritten by a file system cleaner. These include
619 * the checkpoint and inode map records only; other items must still pass
621 void bluesky_cloudlog_decrypt(char *segment, size_t len,
622 BlueSkyCryptKeys *keys,
623 BlueSkyRangeset *items,
624 gboolean allow_unauth)
626 char *data = segment;
627 size_t remaining_size = len;
630 while (remaining_size >= sizeof(struct cloudlog_header)) {
631 struct cloudlog_header *header = (struct cloudlog_header *)data;
632 size_t item_size = sizeof(struct cloudlog_header)
633 + GUINT32_FROM_LE(header->size1)
634 + GUINT32_FROM_LE(header->size2)
635 + GUINT32_FROM_LE(header->size3);
636 if (item_size > remaining_size)
638 if (bluesky_crypt_block_decrypt(data, item_size, keys, allow_unauth)) {
641 g_print(" data item at %zx\n", offset);
642 bluesky_rangeset_insert(items, offset, item_size,
643 GINT_TO_POINTER(TRUE));
646 g_warning("Unauthenticated data at offset %zd", offset);
648 bluesky_rangeset_insert(items, offset, item_size,
649 GINT_TO_POINTER(TRUE));
655 remaining_size -= item_size;
659 void bluesky_cloudlog_threads_init(BlueSkyFS *fs)
661 fs->unref_queue = g_async_queue_new();
662 g_thread_create(cloudlog_unref_thread, fs->unref_queue, FALSE, NULL);
663 fetch_pool = g_thread_pool_new(background_fetch_task, NULL, 40, FALSE,