Debugging/refcount cleanups.
[bluesky.git] / bluesky / log.c
1 /* Blue Sky: File Systems in the Cloud
2  *
3  * Copyright (C) 2010  The Regents of the University of California
4  * Written by Michael Vrable <mvrable@cs.ucsd.edu>
5  *
6  * TODO: Licensing
7  */
8
9 #define _GNU_SOURCE
10 #define _ATFILE_SOURCE
11
12 #include <stdio.h>
13 #include <stdint.h>
14 #include <stdlib.h>
15 #include <glib.h>
16 #include <string.h>
17 #include <errno.h>
18 #include <sys/types.h>
19 #include <sys/stat.h>
20 #include <fcntl.h>
21 #include <unistd.h>
22 #include <sys/mman.h>
23
24 #include "bluesky-private.h"
25
26 /* The logging layer for BlueSky.  This is used to write filesystem changes
27  * durably to disk so that they can be recovered in the event of a system
28  * crash. */
29
30 /* The logging layer takes care out writing out a sequence of log records to
31  * disk.  On disk, each record consists of a header, a data payload, and a
32  * footer.  The footer contains a checksum of the record, meant to help with
33  * identifying corrupt log records (we would assume because the log record was
34  * only incompletely written out before a crash, which should only happen for
35  * log records that were not considered committed). */
36
37 // Rough size limit for a log segment.  This is not a firm limit and there are
38 // no absolute guarantees on the size of a log segment.
39 #define LOG_SEGMENT_SIZE (1 << 24)
40
41 #define HEADER_MAGIC 0x676f4c0a
42 #define FOOTER_MAGIC 0x2e435243
43
44 struct log_header {
45     uint32_t magic;             // HEADER_MAGIC
46     uint64_t offset;            // Starting byte offset of the log header
47     uint32_t size;              // Size of the data item (bytes)
48     BlueSkyCloudID id;          // Object identifier
49 } __attribute__((packed));
50
51 struct log_footer {
52     uint32_t magic;             // FOOTER_MAGIC
53     uint32_t crc;               // Computed from log_header to log_footer.magic
54 } __attribute__((packed));
55
56 static void writebuf(int fd, const char *buf, size_t len)
57 {
58     while (len > 0) {
59         ssize_t written;
60         written = write(fd, buf, len);
61         if (written < 0 && errno == EINTR)
62             continue;
63         g_assert(written >= 0);
64         buf += written;
65         len -= written;
66     }
67 }
68
69 static void log_commit(BlueSkyLog *log)
70 {
71     int batchsize = 0;
72
73     if (log->fd < 0)
74         return;
75
76     fdatasync(log->fd);
77     while (log->committed != NULL) {
78         BlueSkyCloudLog *item = (BlueSkyCloudLog *)log->committed->data;
79         g_mutex_lock(item->lock);
80         bluesky_cloudlog_stats_update(item, -1);
81         item->pending_write &= ~CLOUDLOG_JOURNAL;
82         item->location_flags |= CLOUDLOG_JOURNAL;
83         bluesky_cloudlog_stats_update(item, 1);
84         g_cond_signal(item->cond);
85         g_mutex_unlock(item->lock);
86         log->committed = g_slist_delete_link(log->committed, log->committed);
87         bluesky_cloudlog_unref(item);
88         batchsize++;
89     }
90
91     if (bluesky_verbose && batchsize > 1)
92         g_print("Log batch size: %d\n", batchsize);
93 }
94
95 static gboolean log_open(BlueSkyLog *log)
96 {
97     char logname[64];
98
99     if (log->fd >= 0) {
100         log_commit(log);
101         close(log->fd);
102         log->seq_num++;
103         log->fd = -1;
104     }
105
106     while (log->fd < 0) {
107         g_snprintf(logname, sizeof(logname), "journal-%08d", log->seq_num);
108         log->fd = openat(log->dirfd, logname, O_CREAT|O_WRONLY|O_EXCL, 0600);
109         if (log->fd < 0 && errno == EEXIST) {
110             fprintf(stderr, "Log file %s already exists...\n", logname);
111             log->seq_num++;
112             continue;
113         } else if (log->fd < 0) {
114             fprintf(stderr, "Error opening logfile %s: %m\n", logname);
115             return FALSE;
116         }
117     }
118
119     if (ftruncate(log->fd, LOG_SEGMENT_SIZE) < 0) {
120         fprintf(stderr, "Unable to truncate logfile %s: %m\n", logname);
121     }
122     fsync(log->fd);
123     fsync(log->dirfd);
124     return TRUE;
125 }
126
127 /* All log writes (at least for a single log) are made by one thread, so we
128  * don't need to worry about concurrent access to the log file.  Log items to
129  * write are pulled off a queue (and so may be posted by any thread).
130  * fdatasync() is used to ensure the log items are stable on disk.
131  *
132  * The log is broken up into separate files, roughly of size LOG_SEGMENT_SIZE
133  * each.  If a log segment is not currently open (log->fd is negative), a new
134  * one is created.  Log segment filenames are assigned sequentially.
135  *
136  * Log replay ought to be implemented later, and ought to set the initial
137  * sequence number appropriately.
138  */
139 static gpointer log_thread(gpointer d)
140 {
141     BlueSkyLog *log = (BlueSkyLog *)d;
142
143     while (TRUE) {
144         if (log->fd < 0) {
145             if (!log_open(log)) {
146                 return NULL;
147             }
148         }
149
150         BlueSkyCloudLog *item
151             = (BlueSkyCloudLog *)g_async_queue_pop(log->queue);
152         g_mutex_lock(item->lock);
153         g_assert(item->data != NULL);
154
155         /* The item may have already been written to the journal... */
156         if ((item->location_flags | item->pending_write) & CLOUDLOG_JOURNAL) {
157             g_mutex_unlock(item->lock);
158             bluesky_cloudlog_unref(item);
159             g_atomic_int_add(&item->data_lock_count, -1);
160             continue;
161         }
162
163         bluesky_cloudlog_stats_update(item, -1);
164         item->pending_write |= CLOUDLOG_JOURNAL;
165         bluesky_cloudlog_stats_update(item, 1);
166
167         struct log_header header;
168         struct log_footer footer;
169         size_t size = sizeof(header) + sizeof(footer) + item->data->len;
170         off_t offset = 0;
171         if (log->fd >= 0)
172             offset = lseek(log->fd, 0, SEEK_CUR);
173
174         /* Check whether the item would overflow the allocated journal size.
175          * If so, start a new log segment.  We only allow oversized log
176          * segments if they contain a single log entry. */
177         if (offset + size >= LOG_SEGMENT_SIZE && offset > 0) {
178             log_open(log);
179             offset = 0;
180         }
181
182         header.magic = GUINT32_TO_LE(HEADER_MAGIC);
183         header.offset = GUINT64_TO_LE(offset);
184         header.size = GUINT32_TO_LE(item->data->len);
185         header.id = item->id;
186         footer.magic = GUINT32_TO_LE(FOOTER_MAGIC);
187
188         uint32_t crc = BLUESKY_CRC32C_SEED;
189
190         writebuf(log->fd, (const char *)&header, sizeof(header));
191         crc = crc32c(crc, (const char *)&header, sizeof(header));
192
193         writebuf(log->fd, item->data->data, item->data->len);
194         crc = crc32c(crc, item->data->data, item->data->len);
195
196         crc = crc32c(crc, (const char *)&footer,
197                      sizeof(footer) - sizeof(uint32_t));
198         footer.crc = crc32c_finalize(crc);
199         writebuf(log->fd, (const char *)&footer, sizeof(footer));
200
201         item->log_seq = log->seq_num;
202         item->log_offset = offset + sizeof(header);
203         item->log_size = item->data->len;
204
205         offset += sizeof(header) + sizeof(footer) + item->data->len;
206
207         /* Replace the log item's string data with a memory-mapped copy of the
208          * data, now that it has been written to the log file.  (Even if it
209          * isn't yet on disk, it should at least be in the page cache and so
210          * available to memory map.) */
211         bluesky_string_unref(item->data);
212         item->data = NULL;
213         bluesky_cloudlog_fetch(item);
214
215         log->committed  = g_slist_prepend(log->committed, item);
216         g_atomic_int_add(&item->data_lock_count, -1);
217         g_mutex_unlock(item->lock);
218
219         /* Force an if there are no other log items currently waiting to be
220          * written. */
221         if (g_async_queue_length(log->queue) <= 0)
222             log_commit(log);
223     }
224
225     return NULL;
226 }
227
228 BlueSkyLog *bluesky_log_new(const char *log_directory)
229 {
230     BlueSkyLog *log = g_new0(BlueSkyLog, 1);
231
232     log->log_directory = g_strdup(log_directory);
233     log->fd = -1;
234     log->seq_num = 0;
235     log->queue = g_async_queue_new();
236     log->mmap_lock = g_mutex_new();
237     log->mmap_cache = g_hash_table_new(NULL, NULL);
238
239     log->dirfd = open(log->log_directory, O_DIRECTORY);
240     if (log->dirfd < 0) {
241         fprintf(stderr, "Unable to open logging directory: %m\n");
242         return NULL;
243     }
244
245     g_thread_create(log_thread, log, FALSE, NULL);
246
247     return log;
248 }
249
250 void bluesky_log_item_submit(BlueSkyCloudLog *item, BlueSkyLog *log)
251 {
252     bluesky_cloudlog_ref(item);
253     g_atomic_int_add(&item->data_lock_count, 1);
254     g_async_queue_push(log->queue, item);
255 }
256
257 void bluesky_log_finish_all(GList *log_items)
258 {
259     while (log_items != NULL) {
260         BlueSkyCloudLog *item = (BlueSkyCloudLog *)log_items->data;
261
262         g_mutex_lock(item->lock);
263         while ((item->pending_write & CLOUDLOG_JOURNAL))
264             g_cond_wait(item->cond, item->lock);
265         g_mutex_unlock(item->lock);
266         bluesky_cloudlog_unref(item);
267
268         log_items = g_list_delete_link(log_items, log_items);
269     }
270 }
271
272 /* Memory-map the given log object into memory (read-only) and return a pointer
273  * to it. */
274 static int page_size = 0;
275
276 static void cloudlog_fetch_complete(BlueSkyStoreAsync *async,
277                                     BlueSkyCacheFile *cachefile)
278 {
279     g_print("Fetch of %s from cloud complete, status = %d\n",
280             async->key, async->result);
281
282     if (async->result < 0)
283         return;
284
285     g_mutex_lock(cachefile->lock);
286     char *pathname = g_strdup_printf("%s/%s", cachefile->log->log_directory,
287                                      cachefile->filename);
288     if (!g_file_set_contents(pathname, async->data->data, async->data->len,
289                              NULL))
290     {
291         g_print("Error writing out fetched file to cache!\n");
292     }
293     g_free(pathname);
294     cachefile->fetching = FALSE;
295     cachefile->ready = TRUE;
296     g_cond_broadcast(cachefile->cond);
297     g_mutex_unlock(cachefile->lock);
298 }
299
300 /* Find the BlueSkyCacheFile object for the given journal or cloud log segment.
301  * Returns the object in the locked state. */
302 BlueSkyCacheFile *bluesky_cachefile_lookup(BlueSkyFS *fs,
303                                          int clouddir, int log_seq)
304 {
305     if (page_size == 0) {
306         page_size = getpagesize();
307     }
308
309     BlueSkyLog *log = fs->log;
310
311     BlueSkyCacheFile *map;
312     g_mutex_lock(log->mmap_lock);
313     map = g_hash_table_lookup(log->mmap_cache, GINT_TO_POINTER(log_seq));
314
315     if (map == NULL) {
316         char *logname;
317
318         // A request for a local log file
319         if (clouddir < 0) {
320             logname = g_strdup_printf("journal-%08d", log_seq);
321         } else {
322             logname = g_strdup_printf("log-%08d-%08d", clouddir, log_seq);
323         }
324
325         /* TODO: stat() call */
326         map = g_new0(BlueSkyCacheFile, 1);
327         map->type = CLOUDLOG_JOURNAL;
328         map->lock = g_mutex_new();
329         g_mutex_lock(map->lock);
330         map->cond = g_cond_new();
331         map->filename = logname;
332         map->log_seq = log_seq;
333         map->log = log;
334         g_atomic_int_set(&map->mapcount, 0);
335
336         g_hash_table_insert(log->mmap_cache, GINT_TO_POINTER(log_seq), map);
337
338         // If the log file is stored in the cloud, we may need to fetch it
339         if (clouddir >= 0) {
340             map->fetching = TRUE;
341             g_print("Starting fetch of %s from cloud\n", logname);
342             BlueSkyStoreAsync *async = bluesky_store_async_new(fs->store);
343             async->op = STORE_OP_GET;
344             async->key = g_strdup(logname);
345             bluesky_store_async_add_notifier(async,
346                                              (GFunc)cloudlog_fetch_complete,
347                                              map);
348             bluesky_store_async_submit(async);
349             bluesky_store_async_unref(async);
350         }
351     } else {
352         g_mutex_lock(map->lock);
353     }
354
355     g_mutex_unlock(log->mmap_lock);
356     return map;
357 }
358
359 BlueSkyRCStr *bluesky_log_map_object(BlueSkyFS *fs, int log_dir,
360                                      int log_seq, int log_offset, int log_size)
361 {
362     if (page_size == 0) {
363         page_size = getpagesize();
364     }
365
366     BlueSkyLog *log = fs->log;
367     BlueSkyCacheFile *map = bluesky_cachefile_lookup(fs, log_dir, log_seq);
368
369     if (map == NULL) {
370         return NULL;
371     }
372
373     if (map->addr == NULL) {
374         while (!map->ready && map->fetching) {
375             g_print("Waiting for log segment to be fetched from cloud...\n");
376             g_cond_wait(map->cond, map->lock);
377         }
378
379         int fd = openat(log->dirfd, map->filename, O_RDONLY);
380
381         if (fd < 0) {
382             fprintf(stderr, "Error opening logfile %s: %m\n", map->filename);
383             g_mutex_unlock(map->lock);
384             return NULL;
385         }
386
387         off_t length = lseek(fd, 0, SEEK_END);
388         map->addr = (const char *)mmap(NULL, length, PROT_READ, MAP_SHARED,
389                                        fd, 0);
390         map->len = length;
391
392         g_print("Re-mapped log segment %d...\n", log_seq);
393
394         close(fd);
395     }
396
397     g_mutex_unlock(log->mmap_lock);
398
399     BlueSkyRCStr *str;
400     str = bluesky_string_new_from_mmap(map, log_offset, log_size);
401     g_mutex_unlock(map->lock);
402     return str;
403 }
404
405 void bluesky_mmap_unref(BlueSkyCacheFile *mmap)
406 {
407     if (mmap == NULL)
408         return;
409
410     if (g_atomic_int_dec_and_test(&mmap->mapcount)) {
411         g_mutex_lock(mmap->lock);
412         if (g_atomic_int_get(&mmap->mapcount) > 0) {
413             g_print("Unmapped log segment %d...\n", mmap->log_seq);
414             munmap((void *)mmap->addr, mmap->len);
415             mmap->addr = NULL;
416             return;
417         }
418         g_mutex_unlock(mmap->lock);
419     }
420 }
421