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