Add checksumming to filesystem journal.
[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
23 #include "bluesky-private.h"
24
25 /* The logging layer for BlueSky.  This is used to write filesystem changes
26  * durably to disk so that they can be recovered in the event of a system
27  * crash. */
28
29 /* The logging layer takes care out writing out a sequence of log records to
30  * disk.  On disk, each record consists of a header, a data payload, and a
31  * footer.  The footer contains a checksum of the record, meant to help with
32  * identifying corrupt log records (we would assume because the log record was
33  * only incompletely written out before a crash, which should only happen for
34  * log records that were not considered committed). */
35
36 // Rough size limit for a log segment.  This is not a firm limit and there are
37 // no absolute guarantees on the size of a log segment.
38 #define LOG_SEGMENT_SIZE (1 << 23)
39
40 #define HEADER_MAGIC 0x676f4c0a
41 #define FOOTER_MAGIC 0x2e435243
42
43 struct log_header {
44     uint32_t magic;             // HEADER_MAGIC
45     uint64_t offset;            // Starting byte offset of the log header
46     uint32_t keysize;           // Size of the log key (bytes)
47     uint32_t size;              // Size of the data item (bytes)
48 } __attribute__((packed));
49
50 struct log_footer {
51     uint32_t magic;             // FOOTER_MAGIC
52     uint32_t crc;               // Computed from log_header to log_footer.magic
53 } __attribute__((packed));
54
55 static void writebuf(int fd, const char *buf, size_t len)
56 {
57     while (len > 0) {
58         ssize_t written;
59         written = write(fd, buf, len);
60         if (written < 0 && errno == EINTR)
61             continue;
62         g_assert(written >= 0);
63         buf += written;
64         len -= written;
65     }
66 }
67
68 /* All log writes (at least for a single log) are made by one thread, so we
69  * don't need to worry about concurrent access to the log file.  Log items to
70  * write are pulled off a queue (and so may be posted by any thread).
71  * fdatasync() is used to ensure the log items are stable on disk.
72  *
73  * The log is broken up into separate files, roughly of size LOG_SEGMENT_SIZE
74  * each.  If a log segment is not currently open (log->fd is negative), a new
75  * one is created.  Log segment filenames are assigned sequentially.
76  *
77  * Log replay ought to be implemented later, and ought to set the initial
78  * sequence number appropriately.
79  */
80 static gpointer log_thread(gpointer d)
81 {
82     BlueSkyLog *log = (BlueSkyLog *)d;
83
84     /* If there are multiple log items to write, we may write more than one
85      * before calling fsync().  The committed list is used to track all the
86      * items that should be marked as committed once that final fsync() is
87      * done. */
88     GSList *committed = NULL;
89
90     int dirfd = open(log->log_directory, O_DIRECTORY);
91     if (dirfd < 0) {
92         fprintf(stderr, "Unable to open logging directory: %m\n");
93         return NULL;
94     }
95
96     while (TRUE) {
97         if (log->fd < 0) {
98             char logfile[64];
99             g_snprintf(logfile, sizeof(logfile), "log-%08d", log->seq_num);
100             log->fd = openat(dirfd, logfile, O_CREAT|O_WRONLY|O_EXCL, 0600);
101             if (log->fd < 0 && errno == EEXIST) {
102                 fprintf(stderr, "Log file %s already exists...\n", logfile);
103                 log->seq_num++;
104                 continue;
105             } else if (log->fd < 0) {
106                 fprintf(stderr, "Error opening logfile %s: %m\n", logfile);
107                 return NULL;
108             }
109             fsync(log->fd);
110             fsync(dirfd);
111         }
112
113         BlueSkyLogItem *item = (BlueSkyLogItem *)g_async_queue_pop(log->queue);
114         g_mutex_lock(item->lock);
115
116         off_t logsize = lseek(log->fd, 0, SEEK_CUR);
117         struct log_header header;
118         struct log_footer footer;
119
120         header.magic = GUINT32_TO_LE(HEADER_MAGIC);
121         header.offset = GUINT64_TO_LE(logsize);
122         header.keysize = GUINT32_TO_LE(strlen(item->key));
123         header.size = GUINT32_TO_LE(item->data->len);
124         footer.magic = GUINT32_TO_LE(FOOTER_MAGIC);
125
126         uint32_t crc = BLUESKY_CRC32C_SEED;
127
128         writebuf(log->fd, (const char *)&header, sizeof(header));
129         crc = crc32c(crc, (const char *)&header, sizeof(header));
130
131         writebuf(log->fd, item->key, strlen(item->key));
132         crc = crc32c(crc, item->key, strlen(item->key));
133
134         writebuf(log->fd, item->data->data, item->data->len);
135         crc = crc32c(crc, item->data->data, item->data->len);
136
137         crc = crc32c(crc, (const char *)&footer,
138                      sizeof(footer) - sizeof(uint32_t));
139         footer.crc = crc32c_finalize(crc);
140         writebuf(log->fd, (const char *)&footer, sizeof(footer));
141
142         committed  = g_slist_prepend(committed, item);
143
144         /* Force an fsync either if we will be closing this log segment and
145          * opening a new file, or if there are no other log items currently
146          * waiting to be written. */
147         logsize += strlen(item->key) + item->data->len + sizeof(header) + sizeof(footer);
148
149         if (logsize >= LOG_SEGMENT_SIZE
150             || g_async_queue_length(log->queue) <= 0)
151         {
152             int batchsize = 0;
153             fdatasync(log->fd);
154             while (committed != NULL) {
155                 item = (BlueSkyLogItem *)committed->data;
156                 item->committed = TRUE;
157                 g_cond_signal(item->cond);
158                 g_mutex_unlock(item->lock);
159                 committed = g_slist_delete_link(committed, committed);
160                 batchsize++;
161             }
162             /* if (batchsize > 1)
163                 g_print("Log batch size: %d\n", batchsize); */
164         }
165
166         if (logsize < 0 || logsize >= LOG_SEGMENT_SIZE) {
167             close(log->fd);
168             log->fd = -1;
169             log->seq_num++;
170         }
171     }
172
173     return NULL;
174 }
175
176 BlueSkyLog *bluesky_log_new(const char *log_directory)
177 {
178     BlueSkyLog *log = g_new0(BlueSkyLog, 1);
179
180     log->log_directory = g_strdup(log_directory);
181     log->fd = -1;
182     log->seq_num = 0;
183     log->queue = g_async_queue_new();
184
185     g_thread_create(log_thread, log, FALSE, NULL);
186
187     return log;
188 }
189
190 BlueSkyLogItem *bluesky_log_item_new()
191 {
192     BlueSkyLogItem *item = g_new(BlueSkyLogItem, 1);
193     item->committed = FALSE;
194     item->lock = g_mutex_new();
195     item->cond = g_cond_new();
196     item->key = NULL;
197     item->data = NULL;
198     return item;
199 }
200
201 void bluesky_log_item_submit(BlueSkyLogItem *item, BlueSkyLog *log)
202 {
203     g_async_queue_push(log->queue, item);
204 }
205
206 static void bluesky_log_item_free(BlueSkyLogItem *item)
207 {
208     g_free(item->key);
209     bluesky_string_unref(item->data);
210     g_mutex_free(item->lock);
211     g_cond_free(item->cond);
212     g_free(item);
213 }
214
215 void bluesky_log_item_finish(BlueSkyLogItem *item)
216 {
217     g_mutex_lock(item->lock);
218     while (!item->committed)
219         g_cond_wait(item->cond, item->lock);
220     g_mutex_unlock(item->lock);
221     bluesky_log_item_free(item);
222 }