Remove debugging messages when decrypting cloud log segments.
[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 char *bluesky_store_lookup_last(BlueSkyStore *store, const char *prefix)
91 {
92     return store->impl->lookup_last(store->handle, prefix);
93 }
94
95 BlueSkyStoreAsync *bluesky_store_async_new(BlueSkyStore *store)
96 {
97     BlueSkyStoreAsync *async;
98
99     async = g_new(BlueSkyStoreAsync, 1);
100     async->store = store;
101     async->lock = g_mutex_new();
102     async->completion_cond = g_cond_new();
103     async->refcount = 1;
104     async->status = ASYNC_NEW;
105     async->op = STORE_OP_NONE;
106     async->key = NULL;
107     async->data = NULL;
108     async->result = -1;
109     async->notifiers = NULL;
110     async->notifier_count = 0;
111     async->barrier = NULL;
112     async->store_private = NULL;
113
114     return async;
115 }
116
117 gpointer bluesky_store_async_get_handle(BlueSkyStoreAsync *async)
118 {
119     return async->store->handle;
120 }
121
122 void bluesky_store_async_ref(BlueSkyStoreAsync *async)
123 {
124     if (async == NULL)
125         return;
126
127     g_return_if_fail(g_atomic_int_get(&async->refcount) > 0);
128
129     g_atomic_int_inc(&async->refcount);
130 }
131
132 void bluesky_store_async_unref(BlueSkyStoreAsync *async)
133 {
134     if (async == NULL)
135         return;
136
137     if (g_atomic_int_dec_and_test(&async->refcount)) {
138         async->store->impl->cleanup(async->store->handle, async);
139         g_mutex_free(async->lock);
140         g_cond_free(async->completion_cond);
141         g_free(async->key);
142         bluesky_string_unref(async->data);
143         g_free(async);
144     }
145 }
146
147 /* Block until the given operation has completed. */
148 void bluesky_store_async_wait(BlueSkyStoreAsync *async)
149 {
150     g_return_if_fail(async != NULL);
151     g_mutex_lock(async->lock);
152
153     if (async->status == ASYNC_NEW) {
154         g_error("bluesky_store_async_wait on a new async object!\n");
155         g_mutex_unlock(async->lock);
156         return;
157     }
158
159     while (async->status != ASYNC_COMPLETE
160            || g_atomic_int_get(&async->notifier_count) > 0) {
161         g_cond_wait(async->completion_cond, async->lock);
162     }
163
164     g_mutex_unlock(async->lock);
165 }
166
167 /* Add a notifier function to be called when the operation completes. */
168 void bluesky_store_async_add_notifier(BlueSkyStoreAsync *async,
169                                       GFunc func, gpointer user_data)
170 {
171     struct BlueSkyNotifierList *nl = g_new(struct BlueSkyNotifierList, 1);
172     g_mutex_lock(async->lock);
173     nl->next = async->notifiers;
174     nl->func = func;
175     nl->async = async; bluesky_store_async_ref(async);
176     nl->user_data = user_data;
177     g_atomic_int_inc(&async->notifier_count);
178     if (async->status == ASYNC_COMPLETE) {
179         g_thread_pool_push(notifier_thread_pool, nl, NULL);
180     } else {
181         async->notifiers = nl;
182     }
183     g_mutex_unlock(async->lock);
184 }
185
186 static void op_complete(gpointer a, gpointer b)
187 {
188     BlueSkyStoreAsync *barrier = (BlueSkyStoreAsync *)b;
189
190     bluesky_store_async_ref(barrier);
191     g_mutex_lock(barrier->lock);
192     barrier->store_private
193         = GINT_TO_POINTER(GPOINTER_TO_INT(barrier->store_private) - 1);
194     if (GPOINTER_TO_INT(barrier->store_private) == 0
195             && barrier->status != ASYNC_NEW) {
196         bluesky_store_async_mark_complete(barrier);
197     }
198     g_mutex_unlock(barrier->lock);
199     bluesky_store_async_unref(barrier);
200 }
201
202 /* Mark an asynchronous operation as complete.  This should only be called by
203  * the store implementations.  The lock should be held when calling this
204  * function.  Any notifier functions will be called, but in a separate thread
205  * and without the lock held. */
206 void bluesky_store_async_mark_complete(BlueSkyStoreAsync *async)
207 {
208     g_return_if_fail(async->status != ASYNC_COMPLETE);
209
210     bluesky_time_hires elapsed = bluesky_now_hires() - async->start_time;
211     bluesky_time_hires latency = bluesky_now_hires() - async->exec_time;
212
213     if (async->op != STORE_OP_BARRIER) {
214         g_mutex_lock(async->store->lock);
215         async->store->pending--;
216         if (async->store->pending == 0)
217             g_cond_broadcast(async->store->cond_idle);
218         g_mutex_unlock(async->store->lock);
219     }
220
221     async->status = ASYNC_COMPLETE;
222     g_cond_broadcast(async->completion_cond);
223
224     if (async->barrier != NULL && async->notifiers == NULL)
225         op_complete(async, async->barrier);
226
227     while (async->notifiers != NULL) {
228         struct BlueSkyNotifierList *nl = async->notifiers;
229         async->notifiers = nl->next;
230         g_thread_pool_push(notifier_thread_pool, nl, NULL);
231     }
232
233     if (bluesky_verbose) {
234         g_log("bluesky/store", G_LOG_LEVEL_DEBUG,
235               "[%p] complete: elapsed = %"PRIi64" ns, latency = %"PRIi64" ns",
236               async, elapsed, latency);
237     }
238
239     if (async->data) {
240         if (async->op == STORE_OP_GET) {
241             bluesky_stats_add(async->store->stats_get, async->data->len);
242         } else if (async->op == STORE_OP_PUT) {
243             bluesky_stats_add(async->store->stats_put, async->data->len);
244         }
245     }
246 }
247
248 void bluesky_store_async_submit(BlueSkyStoreAsync *async)
249 {
250     BlueSkyStore *store = async->store;
251
252     async->start_time = bluesky_now_hires();
253
254     // Backends should fill this in with a better estimate of the actual time
255     // processing was started, if there could be a delay from submission time.
256     async->exec_time = bluesky_now_hires();
257
258     if (bluesky_verbose) {
259         g_log("bluesky/store", G_LOG_LEVEL_DEBUG, "[%p] submit: %s %s",
260               async,
261               async->op == STORE_OP_GET ? "GET"
262                 : async->op == STORE_OP_PUT ? "PUT"
263                 : async->op == STORE_OP_DELETE ? "DELETE"
264                 : async->op == STORE_OP_BARRIER ? "BARRIER" : "???",
265               async->key);
266     }
267
268     /* Barriers are handled specially, and not handed down the storage
269      * implementation layer. */
270     if (async->op == STORE_OP_BARRIER) {
271         async->status = ASYNC_RUNNING;
272         if (GPOINTER_TO_INT(async->store_private) == 0)
273             bluesky_store_async_mark_complete(async);
274         return;
275     }
276
277     g_mutex_lock(async->store->lock);
278     async->store->pending++;
279     g_mutex_unlock(async->store->lock);
280
281     store->impl->submit(store->handle, async);
282
283     if (bluesky_options.synchronous_stores)
284         bluesky_store_async_wait(async);
285 }
286
287 /* Add the given operation to the barrier.  The barrier will not complete until
288  * all operations added to it have completed. */
289 void bluesky_store_add_barrier(BlueSkyStoreAsync *barrier,
290                                BlueSkyStoreAsync *async)
291 {
292     g_return_if_fail(barrier->op == STORE_OP_BARRIER);
293
294     g_mutex_lock(barrier->lock);
295     barrier->store_private
296         = GINT_TO_POINTER(GPOINTER_TO_INT(barrier->store_private) + 1);
297     g_mutex_unlock(barrier->lock);
298
299     g_mutex_lock(async->lock);
300     if (async->barrier == NULL && async->status != ASYNC_COMPLETE) {
301         async->barrier = barrier;
302         g_mutex_unlock(async->lock);
303     } else {
304         if (async->barrier != NULL)
305             g_warning("Adding async to more than one barrier!\n");
306         g_mutex_unlock(async->lock);
307         bluesky_store_async_add_notifier(async, op_complete, barrier);
308     }
309 }
310
311 static void notifier_task(gpointer n, gpointer s)
312 {
313     struct BlueSkyNotifierList *notifier = (struct BlueSkyNotifierList *)n;
314
315     notifier->func(notifier->async, notifier->user_data);
316     if (g_atomic_int_dec_and_test(&notifier->async->notifier_count)) {
317         g_mutex_lock(notifier->async->lock);
318         if (notifier->async->barrier != NULL)
319             op_complete(notifier->async, notifier->async->barrier);
320         g_cond_broadcast(notifier->async->completion_cond);
321         g_mutex_unlock(notifier->async->lock);
322     }
323     bluesky_store_async_unref(notifier->async);
324     g_free(notifier);
325 }
326
327 void bluesky_store_sync(BlueSkyStore *store)
328 {
329     g_mutex_lock(store->lock);
330     if (bluesky_verbose) {
331         g_log("bluesky/store", G_LOG_LEVEL_DEBUG,
332               "Waiting for pending store operations to complete...");
333     }
334     while (store->pending > 0) {
335         g_cond_wait(store->cond_idle, store->lock);
336     }
337     g_mutex_unlock(store->lock);
338     if (bluesky_verbose) {
339         g_log("bluesky/store", G_LOG_LEVEL_DEBUG, "Operations are complete.");
340     }
341 }
342
343 /* Convenience wrappers that perform a single operation synchronously. */
344 BlueSkyRCStr *bluesky_store_get(BlueSkyStore *store, const gchar *key)
345 {
346     BlueSkyStoreAsync *async = bluesky_store_async_new(store);
347     async->op = STORE_OP_GET;
348     async->key = g_strdup(key);
349     bluesky_store_async_submit(async);
350
351     bluesky_store_async_wait(async);
352
353     BlueSkyRCStr *data = async->data;
354     bluesky_string_ref(data);
355     bluesky_store_async_unref(async);
356     return data;
357 }
358
359 void bluesky_store_put(BlueSkyStore *store,
360                        const gchar *key, BlueSkyRCStr *val)
361 {
362     BlueSkyStoreAsync *async = bluesky_store_async_new(store);
363     async->op = STORE_OP_PUT;
364     async->key = g_strdup(key);
365     bluesky_string_ref(val);
366     async->data = val;
367     bluesky_store_async_submit(async);
368
369     bluesky_store_async_wait(async);
370     bluesky_store_async_unref(async);
371 }
372
373 /* Simple in-memory data store for test purposes. */
374 typedef struct {
375     GMutex *lock;
376
377     /* TODO: A hashtable isn't optimal for list queries... */
378     GHashTable *store;
379 } MemStore;
380
381 static gpointer memstore_create(const gchar *path)
382 {
383     MemStore *store = g_new(MemStore, 1);
384     store->lock = g_mutex_new();
385     store->store = g_hash_table_new_full(g_str_hash, g_str_equal,
386                                          g_free,
387                                          (GDestroyNotify)bluesky_string_unref);
388
389     return (gpointer)store;
390 }
391
392 static void memstore_destroy(gpointer store)
393 {
394     /* TODO */
395 }
396
397 static BlueSkyRCStr *memstore_get(gpointer st, const gchar *key)
398 {
399     MemStore *store = (MemStore *)st;
400     BlueSkyRCStr *s = g_hash_table_lookup(store->store, key);
401     if (s != NULL)
402         bluesky_string_ref(s);
403     return s;
404 }
405
406 static void memstore_put(gpointer s, const gchar *key, BlueSkyRCStr *val)
407 {
408     MemStore *store = (MemStore *)s;
409     bluesky_string_ref(val);
410     g_hash_table_insert(store->store, g_strdup(key), val);
411 }
412
413 static void memstore_submit(gpointer s, BlueSkyStoreAsync *async)
414 {
415     g_return_if_fail(async->status == ASYNC_NEW);
416     g_return_if_fail(async->op != STORE_OP_NONE);
417
418     switch (async->op) {
419     case STORE_OP_GET:
420         async->data = memstore_get(s, async->key);
421         break;
422
423     case STORE_OP_PUT:
424         memstore_put(s, async->key, async->data);
425         break;
426
427     default:
428         g_warning("Uknown operation type for MemStore: %d\n", async->op);
429         return;
430     }
431
432     bluesky_store_async_mark_complete(async);
433 }
434
435 static void memstore_cleanup(gpointer store, BlueSkyStoreAsync *async)
436 {
437 }
438
439 static BlueSkyStoreImplementation memstore_impl = {
440     .create = memstore_create,
441     .destroy = memstore_destroy,
442     .submit = memstore_submit,
443     .cleanup = memstore_cleanup,
444 };
445
446 /* Store implementation which writes data as files to disk. */
447 static gpointer filestore_create(const gchar *path)
448 {
449     return GINT_TO_POINTER(1);
450 }
451
452 static void filestore_destroy()
453 {
454 }
455
456 static BlueSkyRCStr *filestore_get(const gchar *key)
457 {
458     gchar *contents = NULL;
459     gsize length;
460     GError *error = NULL;
461
462     g_file_get_contents(key, &contents, &length, &error);
463     if (contents == NULL)
464         return NULL;
465
466     return bluesky_string_new(contents, length);
467 }
468
469 static void filestore_put(const gchar *key, BlueSkyRCStr *val)
470 {
471     g_file_set_contents(key, val->data, val->len, NULL);
472 }
473
474 static void filestore_submit(gpointer s, BlueSkyStoreAsync *async)
475 {
476     g_return_if_fail(async->status == ASYNC_NEW);
477     g_return_if_fail(async->op != STORE_OP_NONE);
478
479     switch (async->op) {
480     case STORE_OP_GET:
481         async->data = filestore_get(async->key);
482         async->result = 0;
483         break;
484
485     case STORE_OP_PUT:
486         filestore_put(async->key, async->data);
487         async->result = 0;
488         break;
489
490     default:
491         g_warning("Uknown operation type for FileStore: %d\n", async->op);
492         return;
493     }
494
495     bluesky_store_async_mark_complete(async);
496 }
497
498 static void filestore_cleanup(gpointer store, BlueSkyStoreAsync *async)
499 {
500 }
501
502 static char *filestore_lookup_last(gpointer store, const char *prefix)
503 {
504     char *last = NULL;
505     GDir *dir = g_dir_open(".", 0, NULL);
506     if (dir == NULL) {
507         g_warning("Unable to open directory for listing");
508         return NULL;
509     }
510
511     const gchar *file;
512     while ((file = g_dir_read_name(dir)) != NULL) {
513         if (strncmp(file, prefix, strlen(prefix)) == 0) {
514             if (last == NULL || strcmp(file, last) > 0) {
515                 g_free(last);
516                 last = g_strdup(file);
517             }
518         }
519     }
520     g_dir_close(dir);
521
522     return last;
523 }
524
525 static BlueSkyStoreImplementation filestore_impl = {
526     .create = filestore_create,
527     .destroy = filestore_destroy,
528     .submit = filestore_submit,
529     .cleanup = filestore_cleanup,
530     .lookup_last = filestore_lookup_last,
531 };
532
533 /* A store implementation which simply discards all data, for testing. */
534 static gpointer nullstore_create(const gchar *path)
535 {
536     return (gpointer)nullstore_create;
537 }
538
539 static void nullstore_destroy(gpointer store)
540 {
541 }
542
543 static void nullstore_submit(gpointer s, BlueSkyStoreAsync *async)
544 {
545     bluesky_store_async_mark_complete(async);
546 }
547
548 static void nullstore_cleanup(gpointer store, BlueSkyStoreAsync *async)
549 {
550 }
551
552 static BlueSkyStoreImplementation nullstore_impl = {
553     .create = nullstore_create,
554     .destroy = nullstore_destroy,
555     .submit = nullstore_submit,
556     .cleanup = nullstore_cleanup,
557 };
558
559 void bluesky_store_init()
560 {
561     store_implementations = g_hash_table_new(g_str_hash, g_str_equal);
562     notifier_thread_pool = g_thread_pool_new(notifier_task, NULL,
563                                              bluesky_max_threads, FALSE, NULL);
564     bluesky_store_register(&memstore_impl, "mem");
565     bluesky_store_register(&filestore_impl, "file");
566     bluesky_store_register(&nullstore_impl, "null");
567 }