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 void bluesky_cloudlog_threads_init(BlueSkyFS *fs)
197 fs->unref_queue = g_async_queue_new();
198 g_thread_create(cloudlog_unref_thread, fs->unref_queue, FALSE, NULL);
201 /* Erase the information contained within the in-memory cloud log
202 * representation. This does not free up the item itself, but frees the data
203 * and references to other log items and resets the type back to unknown. If
204 * the object was written out to persistent storage, all state about it can be
205 * recovered by loading the object back in. The object must be locked before
206 * calling this function. */
207 void bluesky_cloudlog_erase(BlueSkyCloudLog *log)
209 g_assert(log->data_lock_count == 0);
211 if (log->type == LOGTYPE_UNKNOWN)
214 log->type = LOGTYPE_UNKNOWN;
216 bluesky_string_unref(log->data);
218 log->data_lock_count = 0;
220 for (int i = 0; i < log->links->len; i++) {
221 BlueSkyCloudLog *c = g_array_index(log->links,
222 BlueSkyCloudLog *, i);
223 bluesky_cloudlog_unref(c);
225 g_array_unref(log->links);
226 log->links = g_array_new(FALSE, TRUE, sizeof(BlueSkyCloudLog *));
229 /* Start a write of the object to the local log. */
230 void bluesky_cloudlog_sync(BlueSkyCloudLog *log)
232 bluesky_log_item_submit(log, log->fs->log);
235 /* Add the given entry to the global hash table containing cloud log entries.
236 * Takes ownership of the caller's reference. */
237 void bluesky_cloudlog_insert_locked(BlueSkyCloudLog *log)
239 g_hash_table_insert(log->fs->locations, &log->id, log);
242 void bluesky_cloudlog_insert(BlueSkyCloudLog *log)
244 g_mutex_lock(log->fs->lock);
245 bluesky_cloudlog_insert_locked(log);
246 g_mutex_unlock(log->fs->lock);
249 /* Look up the cloud log entry for the given ID. If create is TRUE and the
250 * item does not exist, create a special pending entry that can later be filled
251 * in when the real item is loaded. The returned item has a reference held.
252 * As a special case, if a null ID is provided then NULL is returned. */
253 BlueSkyCloudLog *bluesky_cloudlog_get(BlueSkyFS *fs, BlueSkyCloudID id)
255 static BlueSkyCloudID id0 = {{0}};
257 if (memcmp(&id, &id0, sizeof(BlueSkyCloudID)) == 0)
260 g_mutex_lock(fs->lock);
261 BlueSkyCloudLog *item;
262 item = g_hash_table_lookup(fs->locations, &id);
264 item = bluesky_cloudlog_new(fs, &id);
265 bluesky_cloudlog_stats_update(item, 1);
266 bluesky_cloudlog_insert_locked(item);
268 bluesky_cloudlog_ref(item);
270 g_mutex_unlock(fs->lock);
274 /* Attempt to prefetch a cloud log item. This does not guarantee that it will
275 * be made available, but does make it more likely that a future call to
276 * bluesky_cloudlog_fetch will complete quickly. Item must be locked? */
277 void bluesky_cloudlog_prefetch(BlueSkyCloudLog *item)
279 if (item->data != NULL)
282 /* TODO: Some of the code here is duplicated with bluesky_log_map_object.
283 * Refactor to fix that. */
284 BlueSkyFS *fs = item->fs;
285 BlueSkyCacheFile *map = NULL;
287 /* First, check to see if the journal still contains a copy of the item and
288 * if so update the atime on the journal so it is likely to be kept around
289 * until we need it. */
290 if ((item->location_flags | item->pending_write) & CLOUDLOG_JOURNAL) {
291 map = bluesky_cachefile_lookup(fs, -1, item->log_seq, TRUE);
293 map->atime = bluesky_get_current_time();
294 bluesky_cachefile_unref(map);
295 g_mutex_unlock(map->lock);
300 item->location_flags &= ~CLOUDLOG_JOURNAL;
301 if (!(item->location_flags & CLOUDLOG_CLOUD))
304 map = bluesky_cachefile_lookup(fs,
305 item->location.directory,
306 item->location.sequence,
311 /* At this point, we have information about the log segment containing the
312 * item we need. If our item is already fetched, we have nothing to do
313 * except update the atime. If not, queue up a fetch of our object. */
314 const BlueSkyRangesetItem *rangeitem;
315 rangeitem = bluesky_rangeset_lookup(map->items,
316 item->location.offset);
317 if (rangeitem == NULL) {
318 if (map->prefetches == NULL)
319 map->prefetches = bluesky_rangeset_new();
321 gchar *id = bluesky_cloudlog_id_to_string(item->id);
323 g_print("Need to prefetch %s\n", id);
326 bluesky_rangeset_insert(map->prefetches,
327 item->location.offset,
328 item->location.size, NULL);
330 uint64_t start, length;
331 bluesky_rangeset_get_extents(map->prefetches, &start, &length);
333 g_print("Range to prefetch: %"PRIu64" + %"PRIu64"\n",
337 bluesky_cachefile_unref(map);
338 g_mutex_unlock(map->lock);
341 /* Ensure that a cloud log item is loaded in memory, and if not read it in.
342 * TODO: Make asynchronous, and make this also fetch from the cloud. Right now
343 * we only read from the log. Log item must be locked. */
344 void bluesky_cloudlog_fetch(BlueSkyCloudLog *log)
346 if (log->data != NULL)
349 BlueSkyProfile *profile = bluesky_profile_get();
351 bluesky_profile_add_event(profile, g_strdup_printf("Fetch log entry"));
353 /* There are actually two cases: a full deserialization if we have not ever
354 * read the object before, and a partial deserialization where the metadata
355 * is already in memory and we just need to remap the data. If the object
356 * type has not yet been set, we'll need to read and parse the metadata.
357 * Once that is done, we can fall through the case of remapping the data
359 if (log->type == LOGTYPE_UNKNOWN) {
360 BlueSkyRCStr *raw = bluesky_log_map_object(log, FALSE);
361 g_assert(raw != NULL);
362 bluesky_deserialize_cloudlog(log, raw->data, raw->len);
363 bluesky_string_unref(raw);
366 /* At this point all metadata should be available and we need only remap
367 * the object data. */
368 log->data = bluesky_log_map_object(log, TRUE);
370 if (log->data == NULL) {
371 g_error("Unable to fetch cloudlog entry!");
375 bluesky_profile_add_event(profile, g_strdup_printf("Fetch complete"));
376 g_cond_broadcast(log->cond);
379 BlueSkyCloudPointer bluesky_cloudlog_serialize(BlueSkyCloudLog *log,
382 BlueSkyCloudLogState *state = fs->log_state;
384 if ((log->location_flags | log->pending_write) & CLOUDLOG_CLOUD) {
385 return log->location;
388 for (int i = 0; i < log->links->len; i++) {
389 BlueSkyCloudLog *ref = g_array_index(log->links,
390 BlueSkyCloudLog *, i);
392 bluesky_cloudlog_serialize(ref, fs);
395 /* FIXME: Ought lock to be taken earlier? */
396 g_mutex_lock(log->lock);
397 bluesky_cloudlog_fetch(log);
398 g_assert(log->data != NULL);
400 bluesky_cloudlog_stats_update(log, -1);
402 GString *data1 = g_string_new("");
403 GString *data2 = g_string_new("");
404 GString *data3 = g_string_new("");
405 bluesky_serialize_cloudlog(log, data1, data2, data3);
407 log->location = state->location;
408 log->location.offset = state->data->len;
409 log->data_size = data1->len;
411 struct cloudlog_header header;
412 memcpy(header.magic, CLOUDLOG_MAGIC, 4);
413 memset(header.crypt_auth, sizeof(header.crypt_auth), 0);
414 memset(header.crypt_iv, sizeof(header.crypt_iv), 0);
415 header.type = log->type + '0';
416 header.size1 = GUINT32_TO_LE(data1->len);
417 header.size2 = GUINT32_TO_LE(data2->len);
418 header.size3 = GUINT32_TO_LE(data3->len);
420 header.inum = GUINT64_TO_LE(log->inum);
422 g_string_append_len(state->data, (const char *)&header, sizeof(header));
423 g_string_append_len(state->data, data1->str, data1->len);
424 g_string_append_len(state->data, data2->str, data2->len);
425 g_string_append_len(state->data, data3->str, data3->len);
427 log->location.size = state->data->len - log->location.offset;
429 g_string_free(data1, TRUE);
430 g_string_free(data2, TRUE);
431 g_string_free(data3, TRUE);
433 /* If the object we flushed was an inode, update the inode map. */
434 if (log->type == LOGTYPE_INODE) {
435 g_mutex_lock(fs->lock);
436 InodeMapEntry *entry = bluesky_inode_map_lookup(fs->inode_map,
438 bluesky_cloudlog_unref_delayed(entry->item);
440 bluesky_cloudlog_ref(entry->item);
441 g_mutex_unlock(fs->lock);
444 /* TODO: We should mark the objects as committed on the cloud until the
445 * data is flushed and acknowledged. */
446 log->pending_write |= CLOUDLOG_CLOUD;
447 bluesky_cloudlog_stats_update(log, 1);
448 state->writeback_list = g_slist_prepend(state->writeback_list, log);
449 bluesky_cloudlog_ref(log);
450 g_mutex_unlock(log->lock);
452 if (state->data->len > CLOUDLOG_SEGMENT_SIZE)
453 bluesky_cloudlog_flush(fs);
455 return log->location;
458 static void cloudlog_flush_complete(BlueSkyStoreAsync *async,
459 SerializedRecord *record)
461 g_print("Write of %s to cloud complete, status = %d\n",
462 async->key, async->result);
464 g_mutex_lock(record->lock);
465 if (async->result >= 0) {
466 while (record->items != NULL) {
467 BlueSkyCloudLog *item = (BlueSkyCloudLog *)record->items->data;
468 g_mutex_lock(item->lock);
469 bluesky_cloudlog_stats_update(item, -1);
470 item->pending_write &= ~CLOUDLOG_CLOUD;
471 item->location_flags |= CLOUDLOG_CLOUD;
472 bluesky_cloudlog_stats_update(item, 1);
473 g_mutex_unlock(item->lock);
474 bluesky_cloudlog_unref(item);
476 record->items = g_slist_delete_link(record->items, record->items);
479 bluesky_string_unref(record->data);
481 g_slist_free(record->items);
482 record->items = NULL;
483 record->complete = TRUE;
485 BlueSkyCloudLogState *state = record->fs->log_state;
486 g_mutex_lock(state->uploads_pending_lock);
487 state->uploads_pending--;
488 g_cond_broadcast(state->uploads_pending_cond);
489 g_mutex_unlock(state->uploads_pending_lock);
491 g_cond_broadcast(record->cond);
493 g_print("Write should be resubmitted...\n");
495 BlueSkyStoreAsync *async2 = bluesky_store_async_new(async->store);
496 async2->op = STORE_OP_PUT;
497 async2->key = g_strdup(async->key);
498 async2->data = record->data;
499 async2->profile = async->profile;
500 bluesky_string_ref(record->data);
501 bluesky_store_async_submit(async2);
502 bluesky_store_async_add_notifier(async2,
503 (GFunc)cloudlog_flush_complete,
505 bluesky_store_async_unref(async2);
507 g_mutex_unlock(record->lock);
510 /* Finish up a partially-written cloud log segment and flush it to storage. */
511 static void cloud_flush_background(SerializedRecord *record)
513 bluesky_cloudlog_encrypt(record->raw_data, record->fs->keys);
514 record->data = bluesky_string_new_from_gstring(record->raw_data);
515 record->raw_data = NULL;
517 BlueSkyStoreAsync *async = bluesky_store_async_new(record->fs->store);
518 async->op = STORE_OP_PUT;
519 async->key = record->key;
520 async->data = record->data;
521 bluesky_string_ref(record->data);
522 bluesky_store_async_submit(async);
523 bluesky_store_async_add_notifier(async,
524 (GFunc)cloudlog_flush_complete,
526 bluesky_store_async_unref(async);
529 void bluesky_cloudlog_flush(BlueSkyFS *fs)
531 BlueSkyCloudLogState *state = fs->log_state;
532 if (state->data == NULL || state->data->len == 0)
535 g_mutex_lock(state->uploads_pending_lock);
536 while (state->uploads_pending > cloudlog_concurrent_uploads)
537 g_cond_wait(state->uploads_pending_cond, state->uploads_pending_lock);
538 state->uploads_pending++;
539 g_mutex_unlock(state->uploads_pending_lock);
541 /* TODO: Append some type of commit record to the log segment? */
543 g_print("Serializing %zd bytes of data to cloud\n", state->data->len);
544 SerializedRecord *record = g_new0(SerializedRecord, 1);
546 record->raw_data = state->data;
548 record->items = state->writeback_list;
549 record->lock = g_mutex_new();
550 record->cond = g_cond_new();
551 state->writeback_list = NULL;
553 record->key = g_strdup_printf("log-%08d-%08d",
554 state->location.directory,
555 state->location.sequence);
557 state->pending_segments = g_list_prepend(state->pending_segments, record);
559 /* Encryption of data and upload happen in the background, for additional
560 * parallelism when uploading large amounts of data. */
561 g_thread_create((GThreadFunc)cloud_flush_background, record, FALSE, NULL);
563 state->location.sequence++;
564 state->location.offset = 0;
565 state->data = g_string_new("");
568 /* Make an encryption pass over a cloud log segment to encrypt private data in
570 void bluesky_cloudlog_encrypt(GString *segment, BlueSkyCryptKeys *keys)
572 char *data = segment->str;
573 size_t remaining_size = segment->len;
575 while (remaining_size >= sizeof(struct cloudlog_header)) {
576 struct cloudlog_header *header = (struct cloudlog_header *)data;
577 size_t item_size = sizeof(struct cloudlog_header)
578 + GUINT32_FROM_LE(header->size1)
579 + GUINT32_FROM_LE(header->size2)
580 + GUINT32_FROM_LE(header->size3);
581 if (item_size > remaining_size)
583 bluesky_crypt_block_encrypt(data, item_size, keys);
586 remaining_size -= item_size;
590 /* Make an decryption pass over a cloud log segment to decrypt items which were
591 * encrypted. Also computes a list of all offsets which at which valid
592 * cloud log items are found and adds those offsets to items (if non-NULL).
594 * If allow_unauth is set to true, then allow a limited set of unauthenticated
595 * items that may have been rewritten by a file system cleaner. These include
596 * the checkpoint and inode map records only; other items must still pass
598 void bluesky_cloudlog_decrypt(char *segment, size_t len,
599 BlueSkyCryptKeys *keys,
600 BlueSkyRangeset *items,
601 gboolean allow_unauth)
603 char *data = segment;
604 size_t remaining_size = len;
607 while (remaining_size >= sizeof(struct cloudlog_header)) {
608 struct cloudlog_header *header = (struct cloudlog_header *)data;
609 size_t item_size = sizeof(struct cloudlog_header)
610 + GUINT32_FROM_LE(header->size1)
611 + GUINT32_FROM_LE(header->size2)
612 + GUINT32_FROM_LE(header->size3);
613 if (item_size > remaining_size)
615 if (bluesky_crypt_block_decrypt(data, item_size, keys, allow_unauth)) {
618 g_print(" data item at %zx\n", offset);
619 bluesky_rangeset_insert(items, offset, item_size,
620 GINT_TO_POINTER(TRUE));
623 g_warning("Unauthenticated data at offset %zd", offset);
625 bluesky_rangeset_insert(items, offset, item_size,
626 GINT_TO_POINTER(TRUE));
632 remaining_size -= item_size;