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