Make cloud storage more robust.
[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)
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     log->id = bluesky_cloudlog_new_id();
90     log->links = g_array_new(FALSE, TRUE, sizeof(BlueSkyCloudLog *));
91     g_atomic_int_set(&log->refcount, 1);
92
93     return log;
94 }
95
96 /* Helper function for updating memory usage statistics for a filesystem (the
97  * cache_log_* variables).  This will increment (type=1) or decrement (type=-1)
98  * the counter associated with the current state of the cloud log item.  The
99  * item should be locked or otherwise protected from concurrent access. */
100 void bluesky_cloudlog_stats_update(BlueSkyCloudLog *log, int type)
101 {
102     BlueSkyFS *fs = log->fs;
103
104     if (log->location_flags & CLOUDLOG_CLOUD) {
105         g_atomic_int_add(&fs->cache_log_cloud, type);
106     } else if (log->location_flags & CLOUDLOG_JOURNAL) {
107         g_atomic_int_add(&fs->cache_log_journal, type);
108     } else if (log->pending_write & CLOUDLOG_JOURNAL) {
109         g_atomic_int_add(&fs->cache_log_journal, type);
110     } else if (log->data != NULL) {
111         g_atomic_int_add(&fs->cache_log_dirty, type);
112     }
113 }
114
115 /* The reference held by the hash table does not count towards the reference
116  * count.  When a new object is created, it initially has a reference count of
117  * 1 for the creator, and similarly fetching an item from the hash table will
118  * also create a reference.  If the reference count drops to zero,
119  * bluesky_cloudlog_unref attempts to remove the object from the hash
120  * table--but there is a potential race since another thread might read the
121  * object from the hash table at the same time.  So an object with a reference
122  * count of zero may still be resurrected, in which case we need to abort the
123  * destruction.  Once the object is gone from the hash table, and if the
124  * reference count is still zero, it can actually be deleted. */
125 void bluesky_cloudlog_ref(BlueSkyCloudLog *log)
126 {
127     if (log == NULL)
128         return;
129
130     g_atomic_int_inc(&log->refcount);
131 }
132
133 void bluesky_cloudlog_unref(BlueSkyCloudLog *log)
134 {
135     if (log == NULL)
136         return;
137
138     if (g_atomic_int_dec_and_test(&log->refcount)) {
139         BlueSkyFS *fs = log->fs;
140
141         g_mutex_lock(fs->lock);
142         if (g_atomic_int_get(&log->refcount) > 0) {
143             g_mutex_unlock(fs->lock);
144             return;
145         }
146
147         g_hash_table_remove(fs->locations, &log->id);
148         g_mutex_unlock(fs->lock);
149
150         bluesky_cloudlog_stats_update(log, -1);
151         log->type = LOGTYPE_INVALID;
152         g_mutex_free(log->lock);
153         g_cond_free(log->cond);
154         for (int i = 0; i < log->links->len; i++) {
155             BlueSkyCloudLog *c = g_array_index(log->links,
156                                                BlueSkyCloudLog *, i);
157             bluesky_cloudlog_unref(c);
158         }
159         g_array_unref(log->links);
160         bluesky_string_unref(log->data);
161         if (log->dirty_journal != NULL)
162             g_atomic_int_add(&log->dirty_journal->dirty_refs, -1);
163         g_free(log);
164     }
165 }
166
167 /* Start a write of the object to the local log. */
168 void bluesky_cloudlog_sync(BlueSkyCloudLog *log)
169 {
170     bluesky_log_item_submit(log, log->fs->log);
171 }
172
173 /* Add the given entry to the global hash table containing cloud log entries.
174  * Takes ownership of the caller's reference. */
175 void bluesky_cloudlog_insert(BlueSkyCloudLog *log)
176 {
177     g_mutex_lock(log->fs->lock);
178     g_hash_table_insert(log->fs->locations, &log->id, log);
179     g_mutex_unlock(log->fs->lock);
180 }
181
182 struct log_header {
183     char magic[4];
184     uint32_t size;
185     BlueSkyCloudID id;
186     uint32_t pointer_count;
187 } __attribute__((packed));
188
189 struct logref {
190     BlueSkyCloudID id;
191     BlueSkyCloudPointer location;
192 } __attribute__((packed));
193
194 struct log_footer {
195     char refmagic[4];
196     struct logref refs[0];
197 };
198
199 /* Ensure that a cloud log item is loaded in memory, and if not read it in.
200  * TODO: Make asynchronous, and make this also fetch from the cloud.  Right now
201  * we only read from the log.  Log item must be locked. */
202 void bluesky_cloudlog_fetch(BlueSkyCloudLog *log)
203 {
204     if (log->data != NULL)
205         return;
206
207     if ((log->location_flags | log->pending_write) & CLOUDLOG_JOURNAL) {
208         bluesky_cloudlog_stats_update(log, -1);
209         log->data = bluesky_log_map_object(log->fs, -1, log->log_seq,
210                                            log->log_offset, log->log_size);
211         bluesky_cloudlog_stats_update(log, 1);
212     }
213
214     if (log->data == NULL && (log->location_flags & CLOUDLOG_CLOUD)) {
215         log->location_flags &= ~CLOUDLOG_JOURNAL;
216         bluesky_cloudlog_stats_update(log, -1);
217         log->data = bluesky_log_map_object(log->fs, log->location.directory,
218                                            log->location.sequence,
219                                            log->location.offset,
220                                            log->location.size);
221         bluesky_cloudlog_stats_update(log, 1);
222     }
223
224     if (log->data == NULL) {
225         g_error("Unable to fetch cloudlog entry!");
226     }
227
228     g_cond_broadcast(log->cond);
229 }
230
231 BlueSkyCloudPointer bluesky_cloudlog_serialize(BlueSkyCloudLog *log,
232                                                BlueSkyFS *fs)
233 {
234     BlueSkyCloudLogState *state = fs->log_state;
235
236     if (log->location_flags & CLOUDLOG_CLOUD) {
237         return log->location;
238     }
239
240     for (int i = 0; i < log->links->len; i++) {
241         BlueSkyCloudLog *ref = g_array_index(log->links,
242                                              BlueSkyCloudLog *, i);
243         if (ref != NULL)
244             bluesky_cloudlog_serialize(ref, fs);
245     }
246
247     g_mutex_lock(log->lock);
248     bluesky_cloudlog_fetch(log);
249     g_assert(log->data != NULL);
250
251     bluesky_cloudlog_stats_update(log, -1);
252
253     /* TODO: Right now offset/size are set to the raw data, but we should add
254      * header parsing to the code which loads objects back in. */
255     log->location = state->location;
256     log->location.offset = state->data->len + sizeof(struct log_header);
257     log->location.size = log->data->len;
258         /* = sizeof(struct log_header) + sizeof(BlueSkyCloudID) * 0
259            + log->data->len; */
260
261     struct log_header header;
262     memcpy(header.magic, "AgI ", 4);
263     header.size = GUINT32_TO_LE(log->location.size);
264     header.id = log->id;
265     header.pointer_count = GUINT32_TO_LE(0);
266
267     g_string_append_len(state->data, (const char *)&header, sizeof(header));
268     g_string_append_len(state->data, log->data->data, log->data->len);
269
270     /* TODO: We should mark the objects as committed on the cloud until the
271      * data is flushed and acknowledged. */
272     log->pending_write |= CLOUDLOG_CLOUD;
273     bluesky_cloudlog_stats_update(log, 1);
274     state->writeback_list = g_slist_prepend(state->writeback_list, log);
275     bluesky_cloudlog_ref(log);
276     g_mutex_unlock(log->lock);
277
278     if (state->data->len > CLOUDLOG_SEGMENT_SIZE)
279         bluesky_cloudlog_flush(fs);
280
281     return log->location;
282 }
283
284 typedef struct {
285     BlueSkyRCStr *data;
286     GSList *items;
287 } SerializedRecord;
288
289 static void cloudlog_flush_complete(BlueSkyStoreAsync *async,
290                                     SerializedRecord *record)
291 {
292     g_print("Write of %s to cloud complete, status = %d\n",
293             async->key, async->result);
294
295     if (async->result >= 0) {
296         while (record->items != NULL) {
297             BlueSkyCloudLog *item = (BlueSkyCloudLog *)record->items->data;
298             g_mutex_lock(item->lock);
299             bluesky_cloudlog_stats_update(item, -1);
300             item->pending_write &= ~CLOUDLOG_CLOUD;
301             item->location_flags |= CLOUDLOG_CLOUD;
302             bluesky_cloudlog_stats_update(item, 1);
303             if (item->dirty_journal != NULL) {
304                 g_atomic_int_add(&item->dirty_journal->dirty_refs, -1);
305                 item->dirty_journal = NULL;
306             }
307             g_mutex_unlock(item->lock);
308             bluesky_cloudlog_unref(item);
309
310             record->items = g_slist_delete_link(record->items, record->items);
311         }
312
313         bluesky_string_unref(record->data);
314         g_slist_free(record->items);
315         g_free(record);
316     } else {
317         g_print("Write should be resubmitted...\n");
318
319         BlueSkyStoreAsync *async2 = bluesky_store_async_new(async->store);
320         async2->op = STORE_OP_PUT;
321         async2->key = g_strdup(async->key);
322         async2->data = record->data;
323         bluesky_string_ref(record->data);
324         bluesky_store_async_submit(async2);
325         bluesky_store_async_add_notifier(async2,
326                                          (GFunc)cloudlog_flush_complete,
327                                          record);
328         bluesky_store_async_unref(async2);
329     }
330 }
331
332 /* Finish up a partially-written cloud log segment and flush it to storage. */
333 void bluesky_cloudlog_flush(BlueSkyFS *fs)
334 {
335     BlueSkyCloudLogState *state = fs->log_state;
336     if (state->data == NULL || state->data->len == 0)
337         return;
338
339     /* TODO: Append some type of commit record to the log segment? */
340
341     g_print("Serializing %zd bytes of data to cloud\n", state->data->len);
342     SerializedRecord *record = g_new0(SerializedRecord, 1);
343     record->data = bluesky_string_new_from_gstring(state->data);
344     record->items = state->writeback_list;
345     state->writeback_list = NULL;
346
347     BlueSkyStoreAsync *async = bluesky_store_async_new(fs->store);
348     async->op = STORE_OP_PUT;
349     async->key = g_strdup_printf("log-%08d-%08d",
350                                  state->location.directory,
351                                  state->location.sequence);
352     async->data = record->data;
353     bluesky_string_ref(record->data);
354     bluesky_store_async_submit(async);
355     bluesky_store_async_add_notifier(async,
356                                      (GFunc)cloudlog_flush_complete,
357                                      record);
358     bluesky_store_async_unref(async);
359
360     state->location.sequence++;
361     state->location.offset = 0;
362     state->data = g_string_new("");
363 }