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_options.disable_read_aggregation) {
299 bluesky_cloudlog_background_fetch(item);
303 /* TODO: Some of the code here is duplicated with bluesky_log_map_object.
304 * Refactor to fix that. */
305 BlueSkyFS *fs = item->fs;
306 BlueSkyCacheFile *map = NULL;
308 /* First, check to see if the journal still contains a copy of the item and
309 * if so update the atime on the journal so it is likely to be kept around
310 * until we need it. */
311 if ((item->location_flags | item->pending_write) & CLOUDLOG_JOURNAL) {
312 map = bluesky_cachefile_lookup(fs, -1, item->log_seq, TRUE);
314 map->atime = bluesky_get_current_time();
315 bluesky_cachefile_unref(map);
316 g_mutex_unlock(map->lock);
321 item->location_flags &= ~CLOUDLOG_JOURNAL;
322 if (!(item->location_flags & CLOUDLOG_CLOUD))
325 map = bluesky_cachefile_lookup(fs,
326 item->location.directory,
327 item->location.sequence,
332 /* At this point, we have information about the log segment containing the
333 * item we need. If our item is already fetched, we have nothing to do
334 * except update the atime. If not, queue up a fetch of our object. */
335 const BlueSkyRangesetItem *rangeitem;
336 rangeitem = bluesky_rangeset_lookup(map->items,
337 item->location.offset);
338 if (rangeitem == NULL) {
339 if (map->prefetches == NULL)
340 map->prefetches = bluesky_rangeset_new();
342 gchar *id = bluesky_cloudlog_id_to_string(item->id);
344 g_print("Need to prefetch %s\n", id);
347 bluesky_rangeset_insert(map->prefetches,
348 item->location.offset,
349 item->location.size, NULL);
351 uint64_t start, length;
352 bluesky_rangeset_get_extents(map->prefetches, &start, &length);
354 g_print("Range to prefetch: %"PRIu64" + %"PRIu64"\n",
358 bluesky_cachefile_unref(map);
359 g_mutex_unlock(map->lock);
362 /* Ensure that a cloud log item is loaded in memory, and if not read it in.
363 * TODO: Make asynchronous, and make this also fetch from the cloud. Right now
364 * we only read from the log. Log item must be locked. */
365 void bluesky_cloudlog_fetch(BlueSkyCloudLog *log)
367 if (log->data != NULL)
370 BlueSkyProfile *profile = bluesky_profile_get();
372 bluesky_profile_add_event(profile, g_strdup_printf("Fetch log entry"));
374 /* There are actually two cases: a full deserialization if we have not ever
375 * read the object before, and a partial deserialization where the metadata
376 * is already in memory and we just need to remap the data. If the object
377 * type has not yet been set, we'll need to read and parse the metadata.
378 * Once that is done, we can fall through the case of remapping the data
380 if (log->type == LOGTYPE_UNKNOWN) {
381 BlueSkyRCStr *raw = bluesky_log_map_object(log, FALSE);
382 g_assert(raw != NULL);
383 bluesky_deserialize_cloudlog(log, raw->data, raw->len);
384 bluesky_string_unref(raw);
387 /* At this point all metadata should be available and we need only remap
388 * the object data. */
389 log->data = bluesky_log_map_object(log, TRUE);
391 if (log->data == NULL) {
392 g_error("Unable to fetch cloudlog entry!");
396 bluesky_profile_add_event(profile, g_strdup_printf("Fetch complete"));
397 g_cond_broadcast(log->cond);
400 BlueSkyCloudPointer bluesky_cloudlog_serialize(BlueSkyCloudLog *log,
403 BlueSkyCloudLogState *state = fs->log_state;
405 if ((log->location_flags | log->pending_write) & CLOUDLOG_CLOUD) {
406 return log->location;
409 for (int i = 0; i < log->links->len; i++) {
410 BlueSkyCloudLog *ref = g_array_index(log->links,
411 BlueSkyCloudLog *, i);
413 bluesky_cloudlog_serialize(ref, fs);
416 /* FIXME: Ought lock to be taken earlier? */
417 g_mutex_lock(log->lock);
418 bluesky_cloudlog_fetch(log);
419 g_assert(log->data != NULL);
421 bluesky_cloudlog_stats_update(log, -1);
423 GString *data1 = g_string_new("");
424 GString *data2 = g_string_new("");
425 GString *data3 = g_string_new("");
426 bluesky_serialize_cloudlog(log, data1, data2, data3);
428 log->location = state->location;
429 log->location.offset = state->data->len;
430 log->data_size = data1->len;
432 struct cloudlog_header header;
433 memcpy(header.magic, CLOUDLOG_MAGIC, 4);
434 memset(header.crypt_auth, sizeof(header.crypt_auth), 0);
435 memset(header.crypt_iv, sizeof(header.crypt_iv), 0);
436 header.type = log->type + '0';
437 header.size1 = GUINT32_TO_LE(data1->len);
438 header.size2 = GUINT32_TO_LE(data2->len);
439 header.size3 = GUINT32_TO_LE(data3->len);
441 header.inum = GUINT64_TO_LE(log->inum);
443 g_string_append_len(state->data, (const char *)&header, sizeof(header));
444 g_string_append_len(state->data, data1->str, data1->len);
445 g_string_append_len(state->data, data2->str, data2->len);
446 g_string_append_len(state->data, data3->str, data3->len);
448 log->location.size = state->data->len - log->location.offset;
450 g_string_free(data1, TRUE);
451 g_string_free(data2, TRUE);
452 g_string_free(data3, TRUE);
454 /* If the object we flushed was an inode, update the inode map. */
455 if (log->type == LOGTYPE_INODE) {
456 g_mutex_lock(fs->lock);
457 InodeMapEntry *entry = bluesky_inode_map_lookup(fs->inode_map,
459 bluesky_cloudlog_unref_delayed(entry->item);
461 bluesky_cloudlog_ref(entry->item);
462 g_mutex_unlock(fs->lock);
465 /* TODO: We should mark the objects as committed on the cloud until the
466 * data is flushed and acknowledged. */
467 log->pending_write |= CLOUDLOG_CLOUD;
468 bluesky_cloudlog_stats_update(log, 1);
469 state->writeback_list = g_slist_prepend(state->writeback_list, log);
470 bluesky_cloudlog_ref(log);
471 g_mutex_unlock(log->lock);
473 if (state->data->len > CLOUDLOG_SEGMENT_SIZE
474 || bluesky_options.disable_aggregation)
476 bluesky_cloudlog_flush(fs);
479 return log->location;
482 static void cloudlog_flush_complete(BlueSkyStoreAsync *async,
483 SerializedRecord *record)
485 g_print("Write of %s to cloud complete, status = %d\n",
486 async->key, async->result);
488 g_mutex_lock(record->lock);
489 if (async->result >= 0) {
490 while (record->items != NULL) {
491 BlueSkyCloudLog *item = (BlueSkyCloudLog *)record->items->data;
492 g_mutex_lock(item->lock);
493 bluesky_cloudlog_stats_update(item, -1);
494 item->pending_write &= ~CLOUDLOG_CLOUD;
495 item->location_flags |= CLOUDLOG_CLOUD;
496 bluesky_cloudlog_stats_update(item, 1);
497 g_mutex_unlock(item->lock);
498 bluesky_cloudlog_unref(item);
500 record->items = g_slist_delete_link(record->items, record->items);
503 bluesky_string_unref(record->data);
505 g_slist_free(record->items);
506 record->items = NULL;
507 record->complete = TRUE;
509 BlueSkyCloudLogState *state = record->fs->log_state;
510 g_mutex_lock(state->uploads_pending_lock);
511 state->uploads_pending--;
512 g_cond_broadcast(state->uploads_pending_cond);
513 g_mutex_unlock(state->uploads_pending_lock);
515 g_cond_broadcast(record->cond);
517 g_print("Write should be resubmitted...\n");
519 BlueSkyStoreAsync *async2 = bluesky_store_async_new(async->store);
520 async2->op = STORE_OP_PUT;
521 async2->key = g_strdup(async->key);
522 async2->data = record->data;
523 async2->profile = async->profile;
524 bluesky_string_ref(record->data);
525 bluesky_store_async_submit(async2);
526 bluesky_store_async_add_notifier(async2,
527 (GFunc)cloudlog_flush_complete,
529 bluesky_store_async_unref(async2);
531 g_mutex_unlock(record->lock);
534 /* Finish up a partially-written cloud log segment and flush it to storage. */
535 static void cloud_flush_background(SerializedRecord *record)
537 bluesky_cloudlog_encrypt(record->raw_data, record->fs->keys);
538 record->data = bluesky_string_new_from_gstring(record->raw_data);
539 record->raw_data = NULL;
541 BlueSkyStoreAsync *async = bluesky_store_async_new(record->fs->store);
542 async->op = STORE_OP_PUT;
543 async->key = record->key;
544 async->data = record->data;
545 bluesky_string_ref(record->data);
546 bluesky_store_async_submit(async);
547 bluesky_store_async_add_notifier(async,
548 (GFunc)cloudlog_flush_complete,
550 bluesky_store_async_unref(async);
553 void bluesky_cloudlog_flush(BlueSkyFS *fs)
555 BlueSkyCloudLogState *state = fs->log_state;
556 if (state->data == NULL || state->data->len == 0)
559 g_mutex_lock(state->uploads_pending_lock);
560 while (state->uploads_pending > cloudlog_concurrent_uploads)
561 g_cond_wait(state->uploads_pending_cond, state->uploads_pending_lock);
562 state->uploads_pending++;
563 g_mutex_unlock(state->uploads_pending_lock);
565 /* TODO: Append some type of commit record to the log segment? */
567 g_print("Serializing %zd bytes of data to cloud\n", state->data->len);
568 SerializedRecord *record = g_new0(SerializedRecord, 1);
570 record->raw_data = state->data;
572 record->items = state->writeback_list;
573 record->lock = g_mutex_new();
574 record->cond = g_cond_new();
575 state->writeback_list = NULL;
577 record->key = g_strdup_printf("log-%08d-%08d",
578 state->location.directory,
579 state->location.sequence);
581 state->pending_segments = g_list_prepend(state->pending_segments, record);
583 /* Encryption of data and upload happen in the background, for additional
584 * parallelism when uploading large amounts of data. */
585 g_thread_create((GThreadFunc)cloud_flush_background, record, FALSE, NULL);
587 state->location.sequence++;
588 state->location.offset = 0;
589 state->data = g_string_new("");
592 /* Make an encryption pass over a cloud log segment to encrypt private data in
594 void bluesky_cloudlog_encrypt(GString *segment, BlueSkyCryptKeys *keys)
596 char *data = segment->str;
597 size_t remaining_size = segment->len;
599 while (remaining_size >= sizeof(struct cloudlog_header)) {
600 struct cloudlog_header *header = (struct cloudlog_header *)data;
601 size_t item_size = sizeof(struct cloudlog_header)
602 + GUINT32_FROM_LE(header->size1)
603 + GUINT32_FROM_LE(header->size2)
604 + GUINT32_FROM_LE(header->size3);
605 if (item_size > remaining_size)
607 bluesky_crypt_block_encrypt(data, item_size, keys);
610 remaining_size -= item_size;
614 /* Make an decryption pass over a cloud log segment to decrypt items which were
615 * encrypted. Also computes a list of all offsets which at which valid
616 * cloud log items are found and adds those offsets to items (if non-NULL).
618 * If allow_unauth is set to true, then allow a limited set of unauthenticated
619 * items that may have been rewritten by a file system cleaner. These include
620 * the checkpoint and inode map records only; other items must still pass
622 void bluesky_cloudlog_decrypt(char *segment, size_t len,
623 BlueSkyCryptKeys *keys,
624 BlueSkyRangeset *items,
625 gboolean allow_unauth)
627 char *data = segment;
628 size_t remaining_size = len;
631 while (remaining_size >= sizeof(struct cloudlog_header)) {
632 struct cloudlog_header *header = (struct cloudlog_header *)data;
633 size_t item_size = sizeof(struct cloudlog_header)
634 + GUINT32_FROM_LE(header->size1)
635 + GUINT32_FROM_LE(header->size2)
636 + GUINT32_FROM_LE(header->size3);
637 if (item_size > remaining_size)
639 if (bluesky_crypt_block_decrypt(data, item_size, keys, allow_unauth)) {
642 g_print(" data item at %zx\n", offset);
643 bluesky_rangeset_insert(items, offset, item_size,
644 GINT_TO_POINTER(TRUE));
647 g_warning("Unauthenticated data at offset %zd", offset);
649 bluesky_rangeset_insert(items, offset, item_size,
650 GINT_TO_POINTER(TRUE));
656 remaining_size -= item_size;
660 void bluesky_cloudlog_threads_init(BlueSkyFS *fs)
662 fs->unref_queue = g_async_queue_new();
663 g_thread_create(cloudlog_unref_thread, fs->unref_queue, FALSE, NULL);
664 fetch_pool = g_thread_pool_new(background_fetch_task, NULL, 40, FALSE,