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