Only treat an async storage operation as finished when notifiers finish.
[bluesky.git] / bluesky / store.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 <stdint.h>
10 #include <glib.h>
11 #include <string.h>
12
13 #include "bluesky-private.h"
14
15 /* Interaction with cloud storage.  We expose very simple GET/PUT style
16  * interface, which different backends can implement.  Available backends
17  * (will) include Amazon S3 and a simple local store for testing purposes.
18  * Operations may be performed asynchronously. */
19
20 struct _BlueSkyStore {
21     const BlueSkyStoreImplementation *impl;
22     gpointer handle;
23
24     GMutex *lock;
25     GCond *cond_idle;
26     int pending;                /* Count of operations not yet complete. */
27 };
28
29 GHashTable *store_implementations;
30
31 /* Thread pool for calling notifier functions when an operation completes.
32  * These are called in a separate thread for locking reasons: we want to call
33  * the notifiers without the lock on the async object held, but completion
34  * occurs when the lock is held--so we need some way to defer the call.  This
35  * isn't really optimal from a cache-locality standpoint. */
36 static GThreadPool *notifier_thread_pool;
37
38 void bluesky_store_register(const BlueSkyStoreImplementation *impl,
39                             const gchar *name)
40 {
41     g_hash_table_insert(store_implementations, g_strdup(name), (gpointer)impl);
42 }
43
44 BlueSkyStore *bluesky_store_new(const gchar *type)
45 {
46     const BlueSkyStoreImplementation *impl;
47
48     gchar *scheme, *path;
49     scheme = g_strdup(type);
50     path = strchr(scheme, ':');
51     if (path != NULL) {
52         *path = '\0';
53         path++;
54     }
55
56     impl = g_hash_table_lookup(store_implementations, scheme);
57     if (impl == NULL) {
58         g_free(scheme);
59         return NULL;
60     }
61
62     gpointer handle = impl->create(path);
63     if (handle == NULL) {
64         g_free(scheme);
65         return NULL;
66     }
67
68     BlueSkyStore *store = g_new(BlueSkyStore, 1);
69     store->impl = impl;
70     store->handle = handle;
71     store->lock = g_mutex_new();
72     store->cond_idle = g_cond_new();
73     store->pending = 0;
74     g_free(scheme);
75     return store;
76 }
77
78 void bluesky_store_free(BlueSkyStore *store)
79 {
80     store->impl->destroy(store->handle);
81     g_free(store);
82 }
83
84 BlueSkyStoreAsync *bluesky_store_async_new(BlueSkyStore *store)
85 {
86     BlueSkyStoreAsync *async;
87
88     async = g_new(BlueSkyStoreAsync, 1);
89     async->store = store;
90     async->lock = g_mutex_new();
91     async->completion_cond = g_cond_new();
92     async->refcount = 1;
93     async->status = ASYNC_NEW;
94     async->op = STORE_OP_NONE;
95     async->key = NULL;
96     async->data = NULL;
97     async->result = -1;
98     async->notifiers = NULL;
99     async->notifier_count = 0;
100     async->store_private = NULL;
101
102     return async;
103 }
104
105 gpointer bluesky_store_async_get_handle(BlueSkyStoreAsync *async)
106 {
107     return async->store->handle;
108 }
109
110 void bluesky_store_async_ref(BlueSkyStoreAsync *async)
111 {
112     if (async == NULL)
113         return;
114
115     g_return_if_fail(g_atomic_int_get(&async->refcount) > 0);
116
117     g_atomic_int_inc(&async->refcount);
118 }
119
120 void bluesky_store_async_unref(BlueSkyStoreAsync *async)
121 {
122     if (async == NULL)
123         return;
124
125     if (g_atomic_int_dec_and_test(&async->refcount)) {
126         async->store->impl->cleanup(async->store->handle, async);
127         g_mutex_free(async->lock);
128         g_cond_free(async->completion_cond);
129         g_free(async->key);
130         bluesky_string_unref(async->data);
131         g_free(async);
132     }
133 }
134
135 /* Block until the given operation has completed. */
136 void bluesky_store_async_wait(BlueSkyStoreAsync *async)
137 {
138     g_return_if_fail(async != NULL);
139     g_mutex_lock(async->lock);
140
141     if (async->status == ASYNC_NEW) {
142         g_error("bluesky_store_async_wait on a new async object!\n");
143         g_mutex_unlock(async->lock);
144         return;
145     }
146
147     while (async->status != ASYNC_COMPLETE
148            || g_atomic_int_get(&async->notifier_count) > 0) {
149         g_cond_wait(async->completion_cond, async->lock);
150     }
151
152     g_mutex_unlock(async->lock);
153 }
154
155 /* Add a notifier function to be called when the operation completes. */
156 void bluesky_store_async_add_notifier(BlueSkyStoreAsync *async,
157                                       GFunc func, gpointer user_data)
158 {
159     struct BlueSkyNotifierList *nl = g_new(struct BlueSkyNotifierList, 1);
160     g_mutex_lock(async->lock);
161     nl->next = async->notifiers;
162     nl->func = func;
163     nl->async = async; bluesky_store_async_ref(async);
164     nl->user_data = user_data;
165     g_atomic_int_inc(&async->notifier_count);
166     if (async->status == ASYNC_COMPLETE) {
167         g_thread_pool_push(notifier_thread_pool, nl, NULL);
168     } else {
169         async->notifiers = nl;
170     }
171     g_mutex_unlock(async->lock);
172 }
173
174 /* Mark an asynchronous operation as complete.  This should only be called by
175  * the store implementations.  The lock should be held when calling this
176  * function.  Any notifier functions will be called, but in a separate thread
177  * and without the lock held. */
178 void bluesky_store_async_mark_complete(BlueSkyStoreAsync *async)
179 {
180     g_return_if_fail(async->status != ASYNC_COMPLETE);
181
182     bluesky_time_hires elapsed = bluesky_now_hires() - async->start_time;
183
184     g_mutex_lock(async->store->lock);
185     async->store->pending--;
186     if (async->store->pending == 0)
187         g_cond_broadcast(async->store->cond_idle);
188     g_mutex_unlock(async->store->lock);
189
190     async->status = ASYNC_COMPLETE;
191     g_cond_broadcast(async->completion_cond);
192
193     while (async->notifiers != NULL) {
194         struct BlueSkyNotifierList *nl = async->notifiers;
195         async->notifiers = nl->next;
196         g_thread_pool_push(notifier_thread_pool, nl, NULL);
197     }
198
199     g_log("bluesky/store", G_LOG_LEVEL_DEBUG,
200           "[%p] complete: elapsed = %"PRIi64" ns",
201           async, elapsed);
202 }
203
204 void bluesky_store_async_submit(BlueSkyStoreAsync *async)
205 {
206     BlueSkyStore *store = async->store;
207
208     async->start_time = bluesky_now_hires();
209
210     g_log("bluesky/store", G_LOG_LEVEL_DEBUG, "[%p] submit: %s %s",
211           async,
212           async->op == STORE_OP_GET ? "GET"
213             : async->op == STORE_OP_PUT ? "PUT"
214             : async->op == STORE_OP_DELETE ? "DELETE"
215             : async->op == STORE_OP_BARRIER ? "BARRIER" : "???",
216           async->key);
217
218     /* Barriers are handled specially, and not handed down the storage
219      * implementation layer. */
220     if (async->op == STORE_OP_BARRIER) {
221         async->status = ASYNC_RUNNING;
222         if (GPOINTER_TO_INT(async->store_private) == 0)
223             bluesky_store_async_mark_complete(async);
224         return;
225     }
226
227     g_mutex_lock(async->store->lock);
228     async->store->pending++;
229     g_mutex_unlock(async->store->lock);
230
231     store->impl->submit(store->handle, async);
232
233     if (bluesky_options.synchronous_stores)
234         bluesky_store_async_wait(async);
235 }
236
237 static void op_complete(gpointer a, gpointer b)
238 {
239     BlueSkyStoreAsync *barrier = (BlueSkyStoreAsync *)b;
240
241     bluesky_store_async_ref(barrier);
242     g_mutex_lock(barrier->lock);
243     barrier->store_private
244         = GINT_TO_POINTER(GPOINTER_TO_INT(barrier->store_private) - 1);
245     if (GPOINTER_TO_INT(barrier->store_private) == 0
246             && barrier->status != ASYNC_NEW) {
247         bluesky_store_async_mark_complete(barrier);
248     }
249     g_mutex_unlock(barrier->lock);
250     bluesky_store_async_unref(barrier);
251 }
252
253 /* Add the given operation to the barrier.  The barrier will not complete until
254  * all operations added to it have completed. */
255 void bluesky_store_add_barrier(BlueSkyStoreAsync *barrier,
256                                BlueSkyStoreAsync *async)
257 {
258     g_return_if_fail(barrier->op == STORE_OP_BARRIER);
259     barrier->store_private
260         = GINT_TO_POINTER(GPOINTER_TO_INT(barrier->store_private) + 1);
261     bluesky_store_async_add_notifier(async, op_complete, barrier);
262 }
263
264 static void notifier_task(gpointer n, gpointer s)
265 {
266     struct BlueSkyNotifierList *notifier = (struct BlueSkyNotifierList *)n;
267
268     notifier->func(notifier->async, notifier->user_data);
269     if (g_atomic_int_dec_and_test(&notifier->async->notifier_count)) {
270         g_cond_broadcast(notifier->async->completion_cond);
271     }
272     bluesky_store_async_unref(notifier->async);
273     g_free(notifier);
274 }
275
276 void bluesky_store_sync(BlueSkyStore *store)
277 {
278     g_mutex_lock(store->lock);
279     g_print("Waiting for pending store operations to complete...\n");
280     while (store->pending > 0) {
281         g_cond_wait(store->cond_idle, store->lock);
282     }
283     g_mutex_unlock(store->lock);
284     g_print("Operations are complete.\n");
285 }
286
287 /* Convenience wrappers that perform a single operation synchronously. */
288 BlueSkyRCStr *bluesky_store_get(BlueSkyStore *store, const gchar *key)
289 {
290     BlueSkyStoreAsync *async = bluesky_store_async_new(store);
291     async->op = STORE_OP_GET;
292     async->key = g_strdup(key);
293     bluesky_store_async_submit(async);
294
295     bluesky_store_async_wait(async);
296
297     BlueSkyRCStr *data = async->data;
298     bluesky_string_ref(data);
299     bluesky_store_async_unref(async);
300     return data;
301 }
302
303 void bluesky_store_put(BlueSkyStore *store,
304                        const gchar *key, BlueSkyRCStr *val)
305 {
306     BlueSkyStoreAsync *async = bluesky_store_async_new(store);
307     async->op = STORE_OP_PUT;
308     async->key = g_strdup(key);
309     bluesky_string_ref(val);
310     async->data = val;
311     bluesky_store_async_submit(async);
312
313     bluesky_store_async_wait(async);
314     bluesky_store_async_unref(async);
315 }
316
317 /* Simple in-memory data store for test purposes. */
318 typedef struct {
319     GMutex *lock;
320
321     /* TODO: A hashtable isn't optimal for list queries... */
322     GHashTable *store;
323 } MemStore;
324
325 static gpointer memstore_create(const gchar *path)
326 {
327     MemStore *store = g_new(MemStore, 1);
328     store->lock = g_mutex_new();
329     store->store = g_hash_table_new_full(g_str_hash, g_str_equal,
330                                          g_free,
331                                          (GDestroyNotify)bluesky_string_unref);
332
333     return (gpointer)store;
334 }
335
336 static void memstore_destroy(gpointer store)
337 {
338     /* TODO */
339 }
340
341 static BlueSkyRCStr *memstore_get(gpointer st, const gchar *key)
342 {
343     MemStore *store = (MemStore *)st;
344     BlueSkyRCStr *s = g_hash_table_lookup(store->store, key);
345     if (s != NULL)
346         bluesky_string_ref(s);
347     return s;
348 }
349
350 static void memstore_put(gpointer s, const gchar *key, BlueSkyRCStr *val)
351 {
352     MemStore *store = (MemStore *)s;
353     bluesky_string_ref(val);
354     g_hash_table_insert(store->store, g_strdup(key), val);
355 }
356
357 static void memstore_submit(gpointer s, BlueSkyStoreAsync *async)
358 {
359     g_return_if_fail(async->status == ASYNC_NEW);
360     g_return_if_fail(async->op != STORE_OP_NONE);
361
362     switch (async->op) {
363     case STORE_OP_GET:
364         async->data = memstore_get(s, async->key);
365         break;
366
367     case STORE_OP_PUT:
368         memstore_put(s, async->key, async->data);
369         break;
370
371     default:
372         g_warning("Uknown operation type for MemStore: %d\n", async->op);
373         return;
374     }
375
376     bluesky_store_async_mark_complete(async);
377 }
378
379 static void memstore_cleanup(gpointer store, BlueSkyStoreAsync *async)
380 {
381 }
382
383 static BlueSkyStoreImplementation memstore_impl = {
384     .create = memstore_create,
385     .destroy = memstore_destroy,
386     .submit = memstore_submit,
387     .cleanup = memstore_cleanup,
388 };
389
390 /* Store implementation which writes data as files to disk. */
391 static gpointer filestore_create(const gchar *path)
392 {
393     return GINT_TO_POINTER(1);
394 }
395
396 static void filestore_destroy()
397 {
398 }
399
400 static BlueSkyRCStr *filestore_get(const gchar *key)
401 {
402     gchar *contents = NULL;
403     gsize length;
404     GError *error = NULL;
405
406     g_file_get_contents(key, &contents, &length, &error);
407     if (contents == NULL)
408         return NULL;
409
410     return bluesky_string_new(contents, length);
411 }
412
413 static void filestore_put(const gchar *key, BlueSkyRCStr *val)
414 {
415     g_file_set_contents(key, val->data, val->len, NULL);
416 }
417
418 static void filestore_submit(gpointer s, BlueSkyStoreAsync *async)
419 {
420     g_return_if_fail(async->status == ASYNC_NEW);
421     g_return_if_fail(async->op != STORE_OP_NONE);
422
423     switch (async->op) {
424     case STORE_OP_GET:
425         async->data = filestore_get(async->key);
426         async->result = 0;
427         break;
428
429     case STORE_OP_PUT:
430         filestore_put(async->key, async->data);
431         async->result = 0;
432         break;
433
434     default:
435         g_warning("Uknown operation type for FileStore: %d\n", async->op);
436         return;
437     }
438
439     bluesky_store_async_mark_complete(async);
440 }
441
442 static void filestore_cleanup(gpointer store, BlueSkyStoreAsync *async)
443 {
444 }
445
446 static BlueSkyStoreImplementation filestore_impl = {
447     .create = filestore_create,
448     .destroy = filestore_destroy,
449     .submit = filestore_submit,
450     .cleanup = filestore_cleanup,
451 };
452
453 void bluesky_store_init()
454 {
455     store_implementations = g_hash_table_new(g_str_hash, g_str_equal);
456     notifier_thread_pool = g_thread_pool_new(notifier_task, NULL, -1, FALSE,
457                                              NULL);
458     bluesky_store_register(&memstore_impl, "mem");
459     bluesky_store_register(&filestore_impl, "file");
460 }