Work on reducing memory pinned by the inode map.
[bluesky.git] / bluesky / cloudlog.c
1 /* Blue Sky: File Systems in the Cloud
2  *
3  * Copyright (C) 2009  The Regents of the University of California
4  * Written by Michael Vrable <mvrable@cs.ucsd.edu>
5  *
6  * TODO: Licensing
7  */
8
9 #include <stdio.h>
10 #include <stdint.h>
11 #include <glib.h>
12 #include <string.h>
13
14 #include "bluesky-private.h"
15
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)
19
20 BlueSkyCloudID bluesky_cloudlog_new_id()
21 {
22     BlueSkyCloudID id;
23     bluesky_crypt_random_bytes((uint8_t *)&id.bytes, sizeof(id));
24     return id;
25 }
26
27 gchar *bluesky_cloudlog_id_to_string(BlueSkyCloudID id)
28 {
29     char buf[sizeof(BlueSkyCloudID) * 2 + 1];
30     buf[0] = '\0';
31
32     for (int i = 0; i < sizeof(BlueSkyCloudID); i++) {
33         sprintf(&buf[2*i], "%02x", (uint8_t)(id.bytes[i]));
34     }
35
36     return g_strdup(buf);
37 }
38
39 BlueSkyCloudID bluesky_cloudlog_id_from_string(const gchar *idstr)
40 {
41     BlueSkyCloudID id;
42     memset(&id, 0, sizeof(id));
43     for (int i = 0; i < 2*sizeof(BlueSkyCloudID); i++) {
44         char c = idstr[i];
45         if (c == '\0') {
46             g_warning("Short cloud id: %s\n", idstr);
47             break;
48         }
49         int val = 0;
50         if (c >= '0' && c <= '9')
51             val = c - '0';
52         else if (c >= 'a' && c <= 'f')
53             val = c - 'a' + 10;
54         else
55             g_warning("Bad character in cloud id: %s\n", idstr);
56         id.bytes[i / 2] += val << (i % 2 ? 0 : 4);
57     }
58     return id;
59 }
60
61 gboolean bluesky_cloudlog_equal(gconstpointer a, gconstpointer b)
62 {
63     BlueSkyCloudID *id1 = (BlueSkyCloudID *)a, *id2 = (BlueSkyCloudID *)b;
64
65     return memcmp(id1, id2, sizeof(BlueSkyCloudID)) == 0;
66 }
67
68 guint bluesky_cloudlog_hash(gconstpointer a)
69 {
70     BlueSkyCloudID *id = (BlueSkyCloudID *)a;
71
72     // Assume that bits in the ID are randomly chosen so that any subset of the
73     // bits can be used as a hash key.
74     return *(guint *)(&id->bytes);
75 }
76
77 /* Formatting of cloud log segments.  This handles grouping items together
78  * before writing a batch to the cloud, handling indirection through items like
79  * the inode map, etc. */
80
81 BlueSkyCloudLog *bluesky_cloudlog_new(BlueSkyFS *fs, const BlueSkyCloudID *id)
82 {
83     BlueSkyCloudLog *log = g_new0(BlueSkyCloudLog, 1);
84
85     log->lock = g_mutex_new();
86     log->cond = g_cond_new();
87     log->fs = fs;
88     log->type = LOGTYPE_UNKNOWN;
89     if (id != NULL)
90         memcpy(&log->id, id, sizeof(BlueSkyCloudID));
91     else
92         log->id = bluesky_cloudlog_new_id();
93     log->links = g_array_new(FALSE, TRUE, sizeof(BlueSkyCloudLog *));
94     g_atomic_int_set(&log->refcount, 1);
95
96     return log;
97 }
98
99 /* Helper function for updating memory usage statistics for a filesystem (the
100  * cache_log_* variables).  This will increment (type=1) or decrement (type=-1)
101  * the counter associated with the current state of the cloud log item.  The
102  * item should be locked or otherwise protected from concurrent access. */
103 void bluesky_cloudlog_stats_update(BlueSkyCloudLog *log, int type)
104 {
105     BlueSkyFS *fs = log->fs;
106
107     if (log->location_flags & CLOUDLOG_CLOUD) {
108         g_atomic_int_add(&fs->cache_log_cloud, type);
109     } else if (log->location_flags & CLOUDLOG_JOURNAL) {
110         g_atomic_int_add(&fs->cache_log_journal, type);
111     } else if (log->pending_write & CLOUDLOG_JOURNAL) {
112         g_atomic_int_add(&fs->cache_log_journal, type);
113     } else if (log->data != NULL) {
114         g_atomic_int_add(&fs->cache_log_dirty, type);
115     }
116 }
117
118 /* The reference held by the hash table does not count towards the reference
119  * count.  When a new object is created, it initially has a reference count of
120  * 1 for the creator, and similarly fetching an item from the hash table will
121  * also create a reference.  If the reference count drops to zero,
122  * bluesky_cloudlog_unref attempts to remove the object from the hash
123  * table--but there is a potential race since another thread might read the
124  * object from the hash table at the same time.  So an object with a reference
125  * count of zero may still be resurrected, in which case we need to abort the
126  * destruction.  Once the object is gone from the hash table, and if the
127  * reference count is still zero, it can actually be deleted. */
128 void bluesky_cloudlog_ref(BlueSkyCloudLog *log)
129 {
130     if (log == NULL)
131         return;
132
133     g_atomic_int_inc(&log->refcount);
134 }
135
136 void bluesky_cloudlog_unref(BlueSkyCloudLog *log)
137 {
138     if (log == NULL)
139         return;
140
141     if (g_atomic_int_dec_and_test(&log->refcount)) {
142         BlueSkyFS *fs = log->fs;
143
144         g_mutex_lock(fs->lock);
145         if (g_atomic_int_get(&log->refcount) > 0) {
146             g_mutex_unlock(fs->lock);
147             return;
148         }
149
150         g_hash_table_remove(fs->locations, &log->id);
151         g_mutex_unlock(fs->lock);
152
153         bluesky_cloudlog_stats_update(log, -1);
154         log->type = LOGTYPE_INVALID;
155         g_mutex_free(log->lock);
156         g_cond_free(log->cond);
157         for (int i = 0; i < log->links->len; i++) {
158             BlueSkyCloudLog *c = g_array_index(log->links,
159                                                BlueSkyCloudLog *, i);
160             bluesky_cloudlog_unref(c);
161         }
162         g_array_unref(log->links);
163         bluesky_string_unref(log->data);
164         g_free(log);
165     }
166 }
167
168 /* For locking reasons cloudlog unrefs may sometimes need to be performed in
169  * the future.  We launch a thread for handling these delayed unreference
170  * requests. */
171 static gpointer cloudlog_unref_thread(gpointer q)
172 {
173     GAsyncQueue *queue = (GAsyncQueue *)q;
174
175     while (TRUE) {
176         BlueSkyCloudLog *item = (BlueSkyCloudLog *)g_async_queue_pop(queue);
177         bluesky_cloudlog_unref(item);
178     }
179
180     return NULL;
181 }
182
183 void bluesky_cloudlog_unref_delayed(BlueSkyCloudLog *log)
184 {
185     if (log != NULL)
186         g_async_queue_push(log->fs->unref_queue, log);
187 }
188
189 void bluesky_cloudlog_threads_init(BlueSkyFS *fs)
190 {
191     fs->unref_queue = g_async_queue_new();
192     g_thread_create(cloudlog_unref_thread, fs->unref_queue, FALSE, NULL);
193 }
194
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)
202 {
203     g_assert(log->data_lock_count == 0);
204
205     log->type = LOGTYPE_UNKNOWN;
206     log->data_size = 0;
207     bluesky_string_unref(log->data);
208     log->data = NULL;
209     log->data_lock_count = 0;
210
211     for (int i = 0; i < log->links->len; i++) {
212         BlueSkyCloudLog *c = g_array_index(log->links,
213                                            BlueSkyCloudLog *, i);
214         bluesky_cloudlog_unref(c);
215     }
216     g_array_unref(log->links);
217     log->links = g_array_new(FALSE, TRUE, sizeof(BlueSkyCloudLog *));
218 }
219
220 /* Start a write of the object to the local log. */
221 void bluesky_cloudlog_sync(BlueSkyCloudLog *log)
222 {
223     bluesky_log_item_submit(log, log->fs->log);
224 }
225
226 /* Add the given entry to the global hash table containing cloud log entries.
227  * Takes ownership of the caller's reference. */
228 void bluesky_cloudlog_insert_locked(BlueSkyCloudLog *log)
229 {
230     g_hash_table_insert(log->fs->locations, &log->id, log);
231 }
232
233 void bluesky_cloudlog_insert(BlueSkyCloudLog *log)
234 {
235     g_mutex_lock(log->fs->lock);
236     bluesky_cloudlog_insert_locked(log);
237     g_mutex_unlock(log->fs->lock);
238 }
239
240 /* Look up the cloud log entry for the given ID.  If create is TRUE and the
241  * item does not exist, create a special pending entry that can later be filled
242  * in when the real item is loaded.  The returned item has a reference held.
243  * As a special case, if a null ID is provided then NULL is returned. */
244 BlueSkyCloudLog *bluesky_cloudlog_get(BlueSkyFS *fs, BlueSkyCloudID id)
245 {
246     static BlueSkyCloudID id0 = {{0}};
247
248     if (memcmp(&id, &id0, sizeof(BlueSkyCloudID)) == 0)
249         return NULL;
250
251     g_mutex_lock(fs->lock);
252     BlueSkyCloudLog *item;
253     item = g_hash_table_lookup(fs->locations, &id);
254     if (item == NULL) {
255         item = bluesky_cloudlog_new(fs, &id);
256         g_hash_table_insert(fs->locations, &id, item);
257     } else {
258         bluesky_cloudlog_ref(item);
259     }
260     g_mutex_unlock(fs->lock);
261     return item;
262 }
263
264 /* Ensure that a cloud log item is loaded in memory, and if not read it in.
265  * TODO: Make asynchronous, and make this also fetch from the cloud.  Right now
266  * we only read from the log.  Log item must be locked. */
267 void bluesky_cloudlog_fetch(BlueSkyCloudLog *log)
268 {
269     if (log->data != NULL)
270         return;
271
272     /* There are actually two cases: a full deserialization if we have not ever
273      * read the object before, and a partial deserialization where the metadata
274      * is already in memory and we just need to remap the data.  If the object
275      * type has not yet been set, we'll need to read and parse the metadata.
276      * Once that is done, we can fall through the case of remapping the data
277      * itself. */
278     if (log->type == LOGTYPE_UNKNOWN) {
279         BlueSkyRCStr *raw = NULL;
280         if ((log->location_flags | log->pending_write) & CLOUDLOG_JOURNAL) {
281             raw = bluesky_log_map_object(log->fs, -1, log->log_seq,
282                                          log->log_offset, log->log_size);
283         }
284
285         if (raw == NULL && (log->location_flags & CLOUDLOG_CLOUD)) {
286             log->location_flags &= ~CLOUDLOG_JOURNAL;
287             raw = bluesky_log_map_object(log->fs,
288                                          log->location.directory,
289                                          log->location.sequence,
290                                          log->location.offset,
291                                          log->location.size);
292         }
293
294         g_assert(raw != NULL);
295         bluesky_deserialize_cloudlog(log, raw->data, raw->len);
296         bluesky_string_unref(raw);
297     }
298
299     /* At this point all metadata should be available and we need only remap
300      * the object data. */
301
302     int offset;
303     if ((log->location_flags | log->pending_write) & CLOUDLOG_JOURNAL) {
304         bluesky_cloudlog_stats_update(log, -1);
305         offset = log->log_offset + sizeof(struct log_header);
306         log->data = bluesky_log_map_object(log->fs, -1, log->log_seq,
307                                            offset, log->data_size);
308         bluesky_cloudlog_stats_update(log, 1);
309     }
310
311     if (log->data == NULL && (log->location_flags & CLOUDLOG_CLOUD)) {
312         log->location_flags &= ~CLOUDLOG_JOURNAL;
313         bluesky_cloudlog_stats_update(log, -1);
314         offset = log->location.offset + sizeof(struct cloudlog_header);
315         log->data = bluesky_log_map_object(log->fs, log->location.directory,
316                                            log->location.sequence,
317                                            offset, log->data_size);
318         bluesky_cloudlog_stats_update(log, 1);
319     }
320
321     if (log->data == NULL) {
322         g_error("Unable to fetch cloudlog entry!");
323     }
324
325     g_cond_broadcast(log->cond);
326 }
327
328 BlueSkyCloudPointer bluesky_cloudlog_serialize(BlueSkyCloudLog *log,
329                                                BlueSkyFS *fs)
330 {
331     BlueSkyCloudLogState *state = fs->log_state;
332
333     if ((log->location_flags | log->pending_write) & CLOUDLOG_CLOUD) {
334         return log->location;
335     }
336
337     for (int i = 0; i < log->links->len; i++) {
338         BlueSkyCloudLog *ref = g_array_index(log->links,
339                                              BlueSkyCloudLog *, i);
340         if (ref != NULL)
341             bluesky_cloudlog_serialize(ref, fs);
342     }
343
344     g_mutex_lock(log->lock);
345     bluesky_cloudlog_fetch(log);
346     g_assert(log->data != NULL);
347
348     bluesky_cloudlog_stats_update(log, -1);
349
350     GString *data1 = g_string_new("");
351     GString *data2 = g_string_new("");
352     GString *data3 = g_string_new("");
353     bluesky_serialize_cloudlog(log, data1, data2, data3);
354
355     log->location = state->location;
356     log->location.offset = state->data->len;
357     log->data_size = data1->len;
358
359     struct cloudlog_header header;
360     memcpy(header.magic, CLOUDLOG_MAGIC, 4);
361     memset(header.crypt_auth, sizeof(header.crypt_auth), 0);
362     memset(header.crypt_iv, sizeof(header.crypt_iv), 0);
363     header.type = log->type + '0';
364     header.size1 = GUINT32_TO_LE(data1->len);
365     header.size2 = GUINT32_TO_LE(data2->len);
366     header.size3 = GUINT32_TO_LE(data3->len);
367     header.id = log->id;
368     header.inum = GUINT64_TO_LE(log->inum);
369
370     g_string_append_len(state->data, (const char *)&header, sizeof(header));
371     g_string_append_len(state->data, data1->str, data1->len);
372     g_string_append_len(state->data, data2->str, data2->len);
373     g_string_append_len(state->data, data3->str, data3->len);
374
375     log->location.size = state->data->len - log->location.offset;
376
377     g_string_free(data1, TRUE);
378     g_string_free(data2, TRUE);
379     g_string_free(data3, TRUE);
380
381     /* If the object we flushed was an inode, update the inode map. */
382     if (log->type == LOGTYPE_INODE) {
383         g_mutex_lock(fs->lock);
384         InodeMapEntry *entry = bluesky_inode_map_lookup(fs->inode_map,
385                                                         log->inum, 1);
386         entry->item = log;
387         bluesky_cloudlog_ref(entry->item);
388         g_mutex_unlock(fs->lock);
389     }
390
391     /* TODO: We should mark the objects as committed on the cloud until the
392      * data is flushed and acknowledged. */
393     log->pending_write |= CLOUDLOG_CLOUD;
394     bluesky_cloudlog_stats_update(log, 1);
395     state->writeback_list = g_slist_prepend(state->writeback_list, log);
396     bluesky_cloudlog_ref(log);
397     g_mutex_unlock(log->lock);
398
399     if (state->data->len > CLOUDLOG_SEGMENT_SIZE)
400         bluesky_cloudlog_flush(fs);
401
402     return log->location;
403 }
404
405 static void cloudlog_flush_complete(BlueSkyStoreAsync *async,
406                                     SerializedRecord *record)
407 {
408     g_print("Write of %s to cloud complete, status = %d\n",
409             async->key, async->result);
410
411     g_mutex_lock(record->lock);
412     if (async->result >= 0) {
413         while (record->items != NULL) {
414             BlueSkyCloudLog *item = (BlueSkyCloudLog *)record->items->data;
415             g_mutex_lock(item->lock);
416             bluesky_cloudlog_stats_update(item, -1);
417             item->pending_write &= ~CLOUDLOG_CLOUD;
418             item->location_flags |= CLOUDLOG_CLOUD;
419             bluesky_cloudlog_stats_update(item, 1);
420             g_mutex_unlock(item->lock);
421             bluesky_cloudlog_unref(item);
422
423             record->items = g_slist_delete_link(record->items, record->items);
424         }
425
426         bluesky_string_unref(record->data);
427         record->data = NULL;
428         g_slist_free(record->items);
429         record->items = NULL;
430         record->complete = TRUE;
431         g_cond_broadcast(record->cond);
432     } else {
433         g_print("Write should be resubmitted...\n");
434
435         BlueSkyStoreAsync *async2 = bluesky_store_async_new(async->store);
436         async2->op = STORE_OP_PUT;
437         async2->key = g_strdup(async->key);
438         async2->data = record->data;
439         bluesky_string_ref(record->data);
440         bluesky_store_async_submit(async2);
441         bluesky_store_async_add_notifier(async2,
442                                          (GFunc)cloudlog_flush_complete,
443                                          record);
444         bluesky_store_async_unref(async2);
445     }
446     g_mutex_unlock(record->lock);
447 }
448
449 /* Finish up a partially-written cloud log segment and flush it to storage. */
450 void bluesky_cloudlog_flush(BlueSkyFS *fs)
451 {
452     BlueSkyCloudLogState *state = fs->log_state;
453     if (state->data == NULL || state->data->len == 0)
454         return;
455
456     /* TODO: Append some type of commit record to the log segment? */
457
458     g_print("Serializing %zd bytes of data to cloud\n", state->data->len);
459     SerializedRecord *record = g_new0(SerializedRecord, 1);
460     record->data = bluesky_string_new_from_gstring(state->data);
461     record->items = state->writeback_list;
462     record->lock = g_mutex_new();
463     record->cond = g_cond_new();
464     state->writeback_list = NULL;
465
466     BlueSkyStoreAsync *async = bluesky_store_async_new(fs->store);
467     async->op = STORE_OP_PUT;
468     async->key = g_strdup_printf("log-%08d-%08d",
469                                  state->location.directory,
470                                  state->location.sequence);
471     async->data = record->data;
472     bluesky_string_ref(record->data);
473     bluesky_store_async_submit(async);
474     bluesky_store_async_add_notifier(async,
475                                      (GFunc)cloudlog_flush_complete,
476                                      record);
477     bluesky_store_async_unref(async);
478
479     state->pending_segments = g_list_prepend(state->pending_segments, record);
480
481     state->location.sequence++;
482     state->location.offset = 0;
483     state->data = g_string_new("");
484 }