Add proper per-file copyright notices/licenses and top-level license.
[bluesky.git] / bluesky / bluesky.h
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  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. Neither the name of the University nor the names of its contributors
15  *    may be used to endorse or promote products derived from this software
16  *    without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  */
30
31 #ifndef _BLUESKY_H
32 #define _BLUESKY_H
33
34 #include <stdint.h>
35 #include <stdio.h>
36 #include <inttypes.h>
37 #include <glib.h>
38
39 #ifdef __cplusplus
40 extern "C" {
41 #endif
42
43 /* Various options to tweak for performance benchmarking purposes. */
44 typedef struct {
45     /* OBSOLETE: Perform all get/put operations synchronously. */
46     int synchronous_stores;
47
48     /* OBSOLETE: Write data in cache immediately after file is modified. */
49     int writethrough_cache;
50
51     /* Can inodes be fetched asynchronously?  (Inode object is initially
52      * created in a pending state, and not unlocked until the data is actually
53      * available.) */
54     int sync_inode_fetches;
55
56     /* Should frontends handle requests serially or allow operations to proceed
57      * in parallel? */
58     int sync_frontends;
59
60     /* Target size of the disk cache at the proxy, in kilobytes. */
61     int cache_size;
62
63     /* Full segment fetches (1) or use range requests (0) for fetching segments
64      * from cloud? */
65     int full_segment_fetches;
66
67     /* Disable aggregating of data into log segments.  Each object will be
68      * stored in a separate segment. */
69     int disable_aggregation;
70
71     /* Disable cryptography.  This is for benchmarking purposes. */
72     int disable_crypto;
73
74     /* Disable aggregation of read requests.  Fetch items individually. */
75     int disable_read_aggregation;
76 } BlueSkyOptions;
77
78 extern BlueSkyOptions bluesky_options;
79
80 /* Maximum number of threads to use in any particular thread pool, or -1 for no
81  * limit */
82 extern int bluesky_max_threads;
83
84 /* A general-purpose counter for gathering run-time statistics. */
85 struct bluesky_stats {
86     const char *name;
87     int64_t count;
88     int64_t sum;
89 };
90 struct bluesky_stats *bluesky_stats_new(const char *name);
91 void bluesky_stats_add(struct bluesky_stats *stats, int64_t value);
92 void bluesky_stats_dump_all();
93 void bluesky_stats_run_periodic_dump(FILE *f);
94
95 /* BlueSky status and error codes.  Various frontends should translate these to
96  * the appropriate error code for whatever protocol they implement. */
97 typedef enum {
98     BSTATUS_OK = 0,             /* No error */
99     BSTATUS_IOERR,              /* I/O error of some form */
100     BSTATUS_NOENT,              /* File does not exist */
101 } BlueSkyStatus;
102
103 void bluesky_init(void);
104
105 gchar *bluesky_lowercase(const gchar *s);
106
107 struct BlueSkyCacheFile;
108 typedef struct BlueSkyCacheFile BlueSkyCacheFile;
109
110 typedef struct {
111     gint refcount;
112     BlueSkyCacheFile *mmap;
113     gchar *data;
114     gsize len;
115 } BlueSkyRCStr;
116
117 BlueSkyRCStr *bluesky_string_new(gpointer data, gsize len);
118 BlueSkyRCStr *bluesky_string_new_from_gstring(GString *s);
119 BlueSkyRCStr *bluesky_string_new_from_mmap(BlueSkyCacheFile *mmap,
120                                            int offset, gsize len);
121 void bluesky_string_ref(BlueSkyRCStr *string);
122 void bluesky_string_unref(BlueSkyRCStr *string);
123 BlueSkyRCStr *bluesky_string_dup(BlueSkyRCStr *string);
124 void bluesky_string_resize(BlueSkyRCStr *string, gsize len);
125
126 struct BlueSkyRangeset;
127 typedef struct BlueSkyRangeset BlueSkyRangeset;
128 typedef struct {
129     uint64_t start, length;
130     gpointer data;
131 } BlueSkyRangesetItem;
132
133 BlueSkyRangeset *bluesky_rangeset_new();
134 void bluesky_rangeset_free(BlueSkyRangeset *rangeset);
135 gboolean bluesky_rangeset_insert(BlueSkyRangeset *rangeset,
136                                  uint64_t start, uint64_t length,
137                                  gpointer data);
138 const BlueSkyRangesetItem *bluesky_rangeset_lookup(BlueSkyRangeset *rangeset,
139                                                    uint64_t offset);
140 const BlueSkyRangesetItem *bluesky_rangeset_lookup_next(BlueSkyRangeset *rangeset, uint64_t offset);
141 void bluesky_rangeset_get_extents(BlueSkyRangeset *rangeset,
142                                   uint64_t *start, uint64_t *length);
143
144 /* Storage interface.  This presents a key-value store abstraction, and can
145  * have multiple implementations: in-memory, on-disk, in-cloud. */
146 struct BlueSkyStore;
147 typedef struct BlueSkyStore BlueSkyStore;
148
149 struct BlueSkyLog;
150 typedef struct BlueSkyLog BlueSkyLog;
151
152 struct BlueSkyCloudLogState;
153 typedef struct BlueSkyCloudLogState BlueSkyCloudLogState;
154
155 struct BlueSkyCloudLog;
156 typedef struct BlueSkyCloudLog BlueSkyCloudLog;
157
158 void bluesky_store_init();
159 BlueSkyStore *bluesky_store_new(const gchar *type);
160 void bluesky_store_free(BlueSkyStore *store);
161 BlueSkyRCStr *bluesky_store_get(BlueSkyStore *store, const gchar *key);
162 void bluesky_store_put(BlueSkyStore *store,
163                        const gchar *key, BlueSkyRCStr *val);
164
165 /* File types.  The numeric values are chosen to match with those used in
166  * NFSv3. */
167 typedef enum {
168     BLUESKY_REGULAR = 1,
169     BLUESKY_DIRECTORY = 2,
170     BLUESKY_BLOCK = 3,
171     BLUESKY_CHARACTER = 4,
172     BLUESKY_SYMLINK = 5,
173     BLUESKY_SOCKET = 6,
174     BLUESKY_FIFO = 7,
175
176     /* Special types used only internally. */
177     BLUESKY_PENDING = 0,    /* Inode being loaded; type not yet determined */
178     BLUESKY_INVALID = -1,   /* Inode is invalid (failed to load) */
179 } BlueSkyFileType;
180
181 /* Filesystem state.  Each filesystem which is exported is represented by a
182  * single bluesky_fs structure in memory. */
183 struct BlueSkyCryptKeys;
184
185 typedef struct {
186     GMutex *lock;
187
188     gchar *name;                /* Descriptive name for the filesystem */
189     GHashTable *inodes;         /* Cached inodes */
190     uint64_t next_inum;         /* Next available inode for allocation */
191
192     BlueSkyStore *store;
193     BlueSkyLog *log;
194     BlueSkyCloudLogState *log_state;
195
196     /* Filesystem crypto keys */
197     char *master_key;
198     struct BlueSkyCryptKeys *keys;
199
200     /* Accounting for memory used for caches.  Space is measured in blocks, not
201      * bytes.  Updates to these variables must be made atomically. */
202     gint cache_dirty;
203
204     /* Like above, but tracking data stored in the cloudlog entries
205      * specifically:
206      *  - cache_log_dirty: data uncommitted to journal and cloud
207      *  - cache_log_writeback: data being written to journal
208      *  - cache_log_journal: data committed to journal
209      *  - cache_log_cloud: data written to cloud as well
210      * Log entries should progress from the top state to the bottom, and are
211      * only ever counted in one category at a time. */
212     gint cache_log_dirty, cache_log_writeback,
213          cache_log_journal, cache_log_cloud;
214
215     /* Linked list of inodes, sorted by access/modification times for cache
216      * management.  Editing these lists is protected by the filesystem lock; to
217      * avoid deadlock do not attempt to take any other locks while the FS lock
218      * is held for list editing purposes.  Items at the head of the list are
219      * most recently accessed/modified. */
220     GList unlogged_list;        // Changes not yet synced to journal
221     GList dirty_list;           // Not yet written to cloud storage
222     GList accessed_list;        // All in-memory inodes
223
224     /* Mutex for the flush daemon, to prevent concurrent execution. */
225     GMutex *flushd_lock;
226
227     /* Used to wait for the cache daemon to free up space */
228     GCond *flushd_cond;
229
230     /* Mapping of object identifiers (blocks, inodes) to physical location (in
231      * the local cache or in the logs in the cloud). */
232     GHashTable *locations;
233
234     /* The inode map, which maps inode numbers to the location of the most
235      * recent version. */
236     GSequence *inode_map;
237
238     /* Queue for asynchronous cloudlog unrefs, where needed. */
239     GAsyncQueue *unref_queue;
240
241     /* Thread pool for asynchronous inode fetches */
242     GThreadPool *inode_fetch_thread_pool;
243 } BlueSkyFS;
244
245 /* Inode number of the root directory. */
246 #define BLUESKY_ROOT_INUM 1
247
248 /* Timestamp, measured in microseconds since the Unix epoch. */
249 typedef int64_t bluesky_time;
250
251 /* High-resolution timer, measured in nanoseconds. */
252 typedef int64_t bluesky_time_hires;
253 bluesky_time_hires bluesky_now_hires();
254
255 /* In-memory representation of an inode within a Blue Sky server.  This
256  * corresponds roughly with information that is committed to persistent
257  * storage.  Locking/refcounting rules:
258  *   - To access or modify any data fields, the lock must be held.  This
259  *     includes file blocks.
260  *   - One reference is held by the BlueSkyFS inode hash table.  If that is the
261  *     only reference (and the inode is unlocked), the inode is subject to
262  *     dropping from the cache.
263  *   - Any pending operations should hold extra references to the inode as
264  *     appropriate to keep it available until the operation completes.
265  *   - Locking dependency order is, when multiple locks are to be acquired, to
266  *     acquire locks on parents in the filesystem tree before children.
267  *     (TODO: What about rename when we acquire locks in unrelated parts of the
268  *     filesystem?)
269  *   - An inode should not be locked while the filesystem lock is already held,
270  *     since some code may do an inode lookup (which acquires the filesystem
271  *     lock) while a different inode is locked.
272  * */
273 typedef struct {
274     GMutex *lock;
275     gint refcount;
276
277     BlueSkyFS *fs;
278
279     BlueSkyFileType type;
280     uint32_t mode;
281     uint32_t uid, gid;
282     uint32_t nlink;
283
284     /* Rather than track an inode number and generation number, we will simply
285      * never re-use a fileid after a file is deleted.  64 bits should be enough
286      * that we don't exhaust the identifier space. */
287     uint64_t inum;
288
289     /* change_count is increased with every operation which modifies the inode,
290      * and can be used to determine if cached data is still valid.
291      * change_commit is the value of change_count when the inode was last
292      * committed to stable storage (the log).
293      * change_cloud tracks which version was last commited to cloud storage. */
294     uint64_t change_count, change_commit, change_cloud;
295
296     /* Timestamp for controlling when modified data is flushed to stable
297      * storage.  When an inode is first modified from a clean state, this is
298      * set to the current time.  If the inode is clean, it is set to zero. */
299     int64_t change_time;
300
301     /* Last access time to this inode, for controlling cache evictions. */
302     int64_t access_time;
303
304     /* Version of the object last serialized and committed to storage. */
305     BlueSkyCloudLog *committed_item;
306
307     /* Pointers to the linked-list elements for this inode in the accessed and
308      * dirty linked lists.  We re-use the GList structure, using ->next to
309      * point to the head of the list and ->prev to point to the tail.  The data
310      * element is unused. */
311     GList *unlogged_list, *accessed_list, *dirty_list;
312
313     int64_t atime;              /* Microseconds since the Unix epoch */
314     int64_t ctime;
315     int64_t mtime;
316     int64_t ntime;              /* "new time": time object was created */
317
318     /* File-specific fields */
319     uint64_t size;
320     GArray *blocks;
321
322     /* Directory-specific fields */
323     GSequence *dirents;         /* List of entries for READDIR */
324     GHashTable *dirhash;        /* Hash table by name for LOOKUP */
325     GHashTable *dirhash_folded; /* As above, but case-folded */
326     uint64_t parent_inum;       /* inode for ".."; 0 if the root directory */
327
328     /* Symlink-specific fields */
329     gchar *symlink_contents;
330
331     /* A field for short-term use internally while the lock is held. */
332     gpointer private_data;
333 } BlueSkyInode;
334
335 /* A directory entry.  The name is UTF-8 and is a freshly-allocated string.
336  * Each directory entry is listed in two indices: dirents is indexed by cookie
337  * and dirhash by name.  The cookie is a randomly-assigned 32-bit value, unique
338  * within the directory, that remains unchanged until the entry is deleted.  It
339  * is used to provide a stable key for restarting a READDIR call. */
340 typedef struct {
341     gchar *name;
342     gchar *name_folded;         /* Name, folded for case-insensitive lookup */
343     uint32_t cookie;
344     uint64_t inum;
345 } BlueSkyDirent;
346
347 /* File data is divided into fixed-size blocks (except the last block which may
348  * be short?).  These blocks are backed by storage in a key/value store, but
349  * may also be dirty if modifications have been made in-memory that have not
350  * been committed. */
351 #define BLUESKY_BLOCK_SIZE 32768ULL
352 #define BLUESKY_MAX_FILE_SIZE (BLUESKY_BLOCK_SIZE << 24)
353 typedef enum {
354     BLUESKY_BLOCK_ZERO = 0,     /* Data is all zeroes, not explicitly stored */
355     BLUESKY_BLOCK_REF = 1,      /* Reference to cloud log item, data clean */
356     BLUESKY_BLOCK_DIRTY = 2,    /* Data needs to be committed to store */
357 } BlueSkyBlockType;
358
359 typedef struct {
360     BlueSkyBlockType type;
361     BlueSkyCloudLog *ref;       /* if REF: cloud log entry with data */
362     BlueSkyRCStr *dirty;        /* if DIRTY: raw data in memory */
363 } BlueSkyBlock;
364
365 BlueSkyFS *bluesky_init_fs(gchar *name, BlueSkyStore *store,
366                            const gchar *master_key);
367
368 gboolean bluesky_inode_is_ready(BlueSkyInode *inode);
369
370 int64_t bluesky_get_current_time();
371 void bluesky_inode_update_ctime(BlueSkyInode *inode, gboolean update_mtime);
372 uint64_t bluesky_fs_alloc_inode(BlueSkyFS *fs);
373 void bluesky_init_inode(BlueSkyInode *i, BlueSkyFileType type);
374 BlueSkyInode *bluesky_new_inode(uint64_t inum, BlueSkyFS *fs, BlueSkyFileType type);
375
376 BlueSkyInode *bluesky_get_inode(BlueSkyFS *fs, uint64_t inum);
377 void bluesky_inode_ref(BlueSkyInode *inode);
378 void bluesky_inode_unref(BlueSkyInode *inode);
379 void bluesky_insert_inode(BlueSkyFS *fs, BlueSkyInode *inode);
380
381 void bluesky_dirent_destroy(gpointer dirent);
382 uint64_t bluesky_directory_lookup(BlueSkyInode *inode, gchar *name);
383 uint64_t bluesky_directory_ilookup(BlueSkyInode *inode, gchar *name);
384 BlueSkyDirent *bluesky_directory_read(BlueSkyInode *dir, uint32_t cookie);
385 gboolean bluesky_directory_insert(BlueSkyInode *dir, const gchar *name,
386                                   uint64_t inum);
387 void bluesky_directory_dump(BlueSkyInode *dir);
388
389 void bluesky_file_truncate(BlueSkyInode *inode, uint64_t size);
390 void bluesky_file_write(BlueSkyInode *inode, uint64_t offset,
391                         const char *data, gint len);
392 void bluesky_file_read(BlueSkyInode *inode, uint64_t offset,
393                        char *buf, gint len);
394
395 void bluesky_inode_fetch(BlueSkyFS *fs, uint64_t inum);
396 void bluesky_inode_prefetch(BlueSkyFS *fs, uint64_t inum);
397
398 gint bluesky_dirent_compare(gconstpointer a, gconstpointer b,
399                             gpointer unused);
400
401 void bluesky_flushd_invoke(BlueSkyFS *fs);
402 void bluesky_flushd_invoke_conditional(BlueSkyFS *fs);
403 void bluesky_inode_do_sync(BlueSkyInode *inode);
404 void bluesky_flushd_thread_launch(BlueSkyFS *fs);
405
406 void bluesky_debug_dump(BlueSkyFS *fs);
407
408 /* Request response time tracking. */
409 typedef struct BlueSkyProfile {
410     int magic;
411     GMutex *lock;
412     char *description;
413     GList *events;
414 } BlueSkyProfile;
415
416 BlueSkyProfile *bluesky_profile_new();
417 void bluesky_profile_free(BlueSkyProfile *profile);
418 void bluesky_profile_add_event(BlueSkyProfile *profile, char *message);
419 void bluesky_profile_print(BlueSkyProfile *profile);
420 BlueSkyProfile *bluesky_profile_get();
421 void bluesky_profile_set(BlueSkyProfile *profile);
422 void bluesky_profile_set_output(FILE *stream);
423
424 #ifdef __cplusplus
425 }
426 #endif
427
428 #endif