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