Split cloud log segments into modestly-sized chunks.
[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         item->pending_write &= ~CLOUDLOG_JOURNAL;
81         item->location_flags |= CLOUDLOG_JOURNAL;
82         g_cond_signal(item->cond);
83         g_mutex_unlock(item->lock);
84         log->committed = g_slist_delete_link(log->committed, log->committed);
85         bluesky_cloudlog_unref(item);
86         batchsize++;
87     }
88
89     if (bluesky_verbose && batchsize > 1)
90         g_print("Log batch size: %d\n", batchsize);
91 }
92
93 static gboolean log_open(BlueSkyLog *log)
94 {
95     char logname[64];
96
97     if (log->fd >= 0) {
98         log_commit(log);
99         close(log->fd);
100         log->seq_num++;
101         log->fd = -1;
102     }
103
104     while (log->fd < 0) {
105         g_snprintf(logname, sizeof(logname), "log-%08d", log->seq_num);
106         log->fd = openat(log->dirfd, logname, O_CREAT|O_WRONLY|O_EXCL, 0600);
107         if (log->fd < 0 && errno == EEXIST) {
108             fprintf(stderr, "Log file %s already exists...\n", logname);
109             log->seq_num++;
110             continue;
111         } else if (log->fd < 0) {
112             fprintf(stderr, "Error opening logfile %s: %m\n", logname);
113             return FALSE;
114         }
115     }
116
117     if (ftruncate(log->fd, LOG_SEGMENT_SIZE) < 0) {
118         fprintf(stderr, "Unable to truncate logfile %s: %m\n", logname);
119     }
120     fsync(log->fd);
121     fsync(log->dirfd);
122     return TRUE;
123 }
124
125 /* All log writes (at least for a single log) are made by one thread, so we
126  * don't need to worry about concurrent access to the log file.  Log items to
127  * write are pulled off a queue (and so may be posted by any thread).
128  * fdatasync() is used to ensure the log items are stable on disk.
129  *
130  * The log is broken up into separate files, roughly of size LOG_SEGMENT_SIZE
131  * each.  If a log segment is not currently open (log->fd is negative), a new
132  * one is created.  Log segment filenames are assigned sequentially.
133  *
134  * Log replay ought to be implemented later, and ought to set the initial
135  * sequence number appropriately.
136  */
137 static gpointer log_thread(gpointer d)
138 {
139     BlueSkyLog *log = (BlueSkyLog *)d;
140
141     while (TRUE) {
142         if (log->fd < 0) {
143             if (!log_open(log)) {
144                 return NULL;
145             }
146         }
147
148         BlueSkyCloudLog *item
149             = (BlueSkyCloudLog *)g_async_queue_pop(log->queue);
150         g_mutex_lock(item->lock);
151         g_assert(item->data != NULL);
152
153         /* The item may have already been written to the journal... */
154         if ((item->location_flags | item->pending_write) & CLOUDLOG_JOURNAL) {
155             g_mutex_unlock(item->lock);
156             bluesky_cloudlog_unref(item);
157             g_atomic_int_add(&item->data_lock_count, -1);
158             continue;
159         }
160
161         item->pending_write |= CLOUDLOG_JOURNAL;
162
163         struct log_header header;
164         struct log_footer footer;
165         size_t size = sizeof(header) + sizeof(footer) + item->data->len;
166         off_t offset = 0;
167         if (log->fd >= 0)
168             offset = lseek(log->fd, 0, SEEK_CUR);
169
170         /* Check whether the item would overflow the allocated journal size.
171          * If so, start a new log segment.  We only allow oversized log
172          * segments if they contain a single log entry. */
173         if (offset + size >= LOG_SEGMENT_SIZE && offset > 0) {
174             log_open(log);
175             offset = 0;
176         }
177
178         header.magic = GUINT32_TO_LE(HEADER_MAGIC);
179         header.offset = GUINT64_TO_LE(offset);
180         header.size = GUINT32_TO_LE(item->data->len);
181         header.id = item->id;
182         footer.magic = GUINT32_TO_LE(FOOTER_MAGIC);
183
184         uint32_t crc = BLUESKY_CRC32C_SEED;
185
186         writebuf(log->fd, (const char *)&header, sizeof(header));
187         crc = crc32c(crc, (const char *)&header, sizeof(header));
188
189         writebuf(log->fd, item->data->data, item->data->len);
190         crc = crc32c(crc, item->data->data, item->data->len);
191
192         crc = crc32c(crc, (const char *)&footer,
193                      sizeof(footer) - sizeof(uint32_t));
194         footer.crc = crc32c_finalize(crc);
195         writebuf(log->fd, (const char *)&footer, sizeof(footer));
196
197         item->log_seq = log->seq_num;
198         item->log_offset = offset + sizeof(header);
199         item->log_size = item->data->len;
200
201         offset += sizeof(header) + sizeof(footer) + item->data->len;
202
203         log->committed  = g_slist_prepend(log->committed, item);
204         g_atomic_int_add(&item->data_lock_count, -1);
205         g_mutex_unlock(item->lock);
206
207         /* Force an if there are no other log items currently waiting to be
208          * written. */
209         if (g_async_queue_length(log->queue) <= 0)
210             log_commit(log);
211     }
212
213     return NULL;
214 }
215
216 BlueSkyLog *bluesky_log_new(const char *log_directory)
217 {
218     BlueSkyLog *log = g_new0(BlueSkyLog, 1);
219
220     log->log_directory = g_strdup(log_directory);
221     log->fd = -1;
222     log->seq_num = 0;
223     log->queue = g_async_queue_new();
224     log->mmap_lock = g_mutex_new();
225     log->mmap_cache = g_hash_table_new(NULL, NULL);
226
227     log->dirfd = open(log->log_directory, O_DIRECTORY);
228     if (log->dirfd < 0) {
229         fprintf(stderr, "Unable to open logging directory: %m\n");
230         return NULL;
231     }
232
233     g_thread_create(log_thread, log, FALSE, NULL);
234
235     return log;
236 }
237
238 void bluesky_log_item_submit(BlueSkyCloudLog *item, BlueSkyLog *log)
239 {
240     bluesky_cloudlog_ref(item);
241     g_atomic_int_add(&item->data_lock_count, 1);
242     g_async_queue_push(log->queue, item);
243 }
244
245 void bluesky_log_finish_all(GList *log_items)
246 {
247     while (log_items != NULL) {
248         BlueSkyCloudLog *item = (BlueSkyCloudLog *)log_items->data;
249
250         g_mutex_lock(item->lock);
251         while ((item->pending_write & CLOUDLOG_JOURNAL))
252             g_cond_wait(item->cond, item->lock);
253         g_mutex_unlock(item->lock);
254         bluesky_cloudlog_unref(item);
255
256         log_items = g_list_delete_link(log_items, log_items);
257     }
258 }
259
260 /* Memory-map the given log object into memory (read-only) and return a pointer
261  * to it. */
262 static int page_size = 0;
263
264 BlueSkyRCStr *bluesky_log_map_object(BlueSkyLog *log,
265                                      int log_seq, int log_offset, int log_size)
266 {
267     if (page_size == 0) {
268         page_size = getpagesize();
269     }
270
271     BlueSkyMmap *map;
272     g_mutex_lock(log->mmap_lock);
273     map = g_hash_table_lookup(log->mmap_cache, GINT_TO_POINTER(log_seq));
274
275     if (map == NULL) {
276         char logname[64];
277         g_snprintf(logname, sizeof(logname), "log-%08d", log_seq);
278         int fd = openat(log->dirfd, logname, O_RDONLY);
279
280         if (fd < 0) {
281             fprintf(stderr, "Error opening logfile %s: %m\n", logname);
282             g_mutex_unlock(log->mmap_lock);
283             return NULL;
284         }
285
286         map = g_new0(BlueSkyMmap, 1);
287
288         off_t length = lseek(fd, 0, SEEK_END);
289         map->log_seq = log_seq;
290         map->addr = (const char *)mmap(NULL, length, PROT_READ, MAP_SHARED,
291                                        fd, 0);
292         map->len = length;
293         map->log = log;
294         g_atomic_int_set(&map->refcount, 0);
295
296         g_hash_table_insert(log->mmap_cache, GINT_TO_POINTER(log_seq), map);
297
298         g_print("Mapped log segment %d...\n", log_seq);
299
300         close(fd);
301     }
302
303     g_mutex_unlock(log->mmap_lock);
304
305     return bluesky_string_new_from_mmap(map, log_offset, log_size);
306 }
307
308 void bluesky_mmap_unref(BlueSkyMmap *mmap)
309 {
310     if (mmap == NULL)
311         return;
312
313     if (g_atomic_int_dec_and_test(&mmap->refcount)) {
314         /* There is a potential race condition here: the BlueSkyLog contains a
315          * hash table of currently-existing BlueSkyMmap objects, which does not
316          * hold a reference.  Some other thread might grab a new reference to
317          * this object after reading it from the hash table.  So, before
318          * destruction we need to grab the lock for the hash table, then check
319          * the reference count again.  If it is still zero, we can proceed with
320          * object destruction. */
321         BlueSkyLog *log = mmap->log;
322         g_mutex_lock(log->mmap_lock);
323         if (g_atomic_int_get(&mmap->refcount) > 0) {
324             g_mutex_unlock(log->mmap_lock);
325             return;
326         }
327
328         g_hash_table_remove(log->mmap_cache, GINT_TO_POINTER(mmap->log_seq));
329         munmap((void *)mmap->addr, mmap->len);
330         g_free(mmap);
331         g_mutex_unlock(log->mmap_lock);
332     }
333 }
334