Gradually converting code to use cloud logs for storing data.
[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  * TODO: Licensing
7  */
8
9 #ifndef _BLUESKY_H
10 #define _BLUESKY_H
11
12 #include <stdint.h>
13 #include <inttypes.h>
14 #include <glib.h>
15
16 #ifdef __cplusplus
17 extern "C" {
18 #endif
19
20 /* Various options to tweak for performance benchmarking purposes. */
21 typedef struct {
22     /* Perform all get/put operations synchronously. */
23     int synchronous_stores;
24
25     /* Write data in cache immediately after file is modified. */
26     int writethrough_cache;
27
28     /* Can inodes be fetched asynchronously?  (Inode object is initially
29      * created in a pending state, and not unlocked until the data is actually
30      * available.) */
31     int sync_inode_fetches;
32
33     /* Should frontends handle requests serially or allow operations to proceed
34      * in parallel? */
35     int sync_frontends;
36 } BlueSkyOptions;
37
38 extern BlueSkyOptions bluesky_options;
39
40 /* Maximum number of threads to use in any particular thread pool, or -1 for no
41  * limit */
42 extern int bluesky_max_threads;
43
44 /* A general-purpose counter for gathering run-time statistics. */
45 struct bluesky_stats {
46     const char *name;
47     int64_t count;
48     int64_t sum;
49 };
50 struct bluesky_stats *bluesky_stats_new(const char *name);
51 void bluesky_stats_add(struct bluesky_stats *stats, int64_t value);
52 void bluesky_stats_dump_all();
53
54 /* BlueSky status and error codes.  Various frontends should translate these to
55  * the appropriate error code for whatever protocol they implement. */
56 typedef enum {
57     BSTATUS_OK = 0,             /* No error */
58     BSTATUS_IOERR,              /* I/O error of some form */
59     BSTATUS_NOENT,              /* File does not exist */
60 } BlueSkyStatus;
61
62 void bluesky_init(void);
63
64 gchar *bluesky_lowercase(const gchar *s);
65
66 /* Reference-counted blocks of memory, used for passing data in and out of
67  * storage backends and in other places. */
68 typedef struct {
69     gint refcount;
70     gchar *data;
71     gsize len;
72 } BlueSkyRCStr;
73
74 BlueSkyRCStr *bluesky_string_new(gpointer data, gsize len);
75 BlueSkyRCStr *bluesky_string_new_from_gstring(GString *s);
76 void bluesky_string_ref(BlueSkyRCStr *string);
77 void bluesky_string_unref(BlueSkyRCStr *string);
78 BlueSkyRCStr *bluesky_string_dup(BlueSkyRCStr *string);
79 void bluesky_string_resize(BlueSkyRCStr *string, gsize len);
80
81 /* Cryptographic operations. */
82 #define CRYPTO_BLOCK_SIZE 16        /* 128-bit AES */
83 #define CRYPTO_KEY_SIZE   16
84
85 void bluesky_crypt_init();
86 void bluesky_crypt_hash_key(const char *keystr, uint8_t *out);
87 void bluesky_crypt_random_bytes(guchar *buf, gint len);
88 BlueSkyRCStr *bluesky_crypt_encrypt(BlueSkyRCStr *in, const uint8_t *key);
89 BlueSkyRCStr *bluesky_crypt_decrypt(BlueSkyRCStr *in, const uint8_t *key);
90
91 /* Storage interface.  This presents a key-value store abstraction, and can
92  * have multiple implementations: in-memory, on-disk, in-cloud. */
93 struct _BlueSkyStore;
94 typedef struct _BlueSkyStore BlueSkyStore;
95
96 struct _BlueSkyLog;
97 typedef struct _BlueSkyLog BlueSkyLog;
98
99 struct _BlueSkyCloudLogState;
100 typedef struct _BlueSkyCloudLogState BlueSkyCloudLogState;
101
102 struct _BlueSkyCloudLog;
103 typedef struct _BlueSkyCloudLog BlueSkyCloudLog;
104
105 void bluesky_store_init();
106 BlueSkyStore *bluesky_store_new(const gchar *type);
107 void bluesky_store_free(BlueSkyStore *store);
108 BlueSkyRCStr *bluesky_store_get(BlueSkyStore *store, const gchar *key);
109 void bluesky_store_put(BlueSkyStore *store,
110                        const gchar *key, BlueSkyRCStr *val);
111
112 /* File types.  The numeric values are chosen to match with those used in
113  * NFSv3. */
114 typedef enum {
115     BLUESKY_REGULAR = 1,
116     BLUESKY_DIRECTORY = 2,
117     BLUESKY_BLOCK = 3,
118     BLUESKY_CHARACTER = 4,
119     BLUESKY_SYMLINK = 5,
120     BLUESKY_SOCKET = 6,
121     BLUESKY_FIFO = 7,
122
123     /* Special types used only internally. */
124     BLUESKY_PENDING = 0,    /* Inode being loaded; type not yet determined */
125     BLUESKY_INVALID = -1,   /* Inode is invalid (failed to load) */
126 } BlueSkyFileType;
127
128 /* Filesystem state.  Each filesystem which is exported is represented by a
129  * single bluesky_fs structure in memory. */
130 typedef struct {
131     GMutex *lock;
132
133     gchar *name;                /* Descriptive name for the filesystem */
134     GHashTable *inodes;         /* Cached inodes */
135     uint64_t next_inum;         /* Next available inode for allocation */
136
137     BlueSkyStore *store;
138     BlueSkyLog *log;
139     BlueSkyCloudLogState *log_state;
140
141     /* Accounting for memory used for caches.  Space is measured in blocks, not
142      * bytes.  We track both total data in the caches and dirty data (total
143      * data includes dirty data).  Updates to these variables must be made
144      * atomically. */
145     gint cache_total, cache_dirty;
146
147     /* Linked list of inodes, sorted by access/modification times for cache
148      * management.  Editing these lists is protected by the filesystem lock; to
149      * avoid deadlock do not attempt to take any other locks while the FS lock
150      * is held for list editing purposes.  Items at the head of the list are
151      * most recently accessed/modified. */
152     GList unlogged_list;        // Changes not yet synced to journal
153     GList dirty_list;           // Not yet written to cloud storage
154     GList accessed_list;        // All in-memory inodes
155
156     /* Mutex for the flush daemon, to prevent concurrent execution. */
157     GMutex *flushd_lock;
158
159     /* Mapping of object identifiers (blocks, inodes) to physical location (in
160      * the local cache or in the logs in the cloud). */
161     GHashTable *locations;
162 } BlueSkyFS;
163
164 /* Inode number of the root directory. */
165 #define BLUESKY_ROOT_INUM 1
166
167 /* Timestamp, measured in microseconds since the Unix epoch. */
168 typedef int64_t bluesky_time;
169
170 /* High-resolution timer, measured in nanoseconds. */
171 typedef int64_t bluesky_time_hires;
172 bluesky_time_hires bluesky_now_hires();
173
174 /* In-memory representation of an inode within a Blue Sky server.  This
175  * corresponds roughly with information that is committed to persistent
176  * storage.  Locking/refcounting rules:
177  *   - To access or modify any data fields, the lock must be held.  This
178  *     includes file blocks.
179  *   - One reference is held by the BlueSkyFS inode hash table.  If that is the
180  *     only reference (and the inode is unlocked), the inode is subject to
181  *     dropping from the cache.
182  *   - Any pending operations should hold extra references to the inode as
183  *     appropriate to keep it available until the operation completes.
184  *   - Locking dependency order is, when multiple locks are to be acquired, to
185  *     acquire locks on parents in the filesystem tree before children.
186  *     (TODO: What about rename when we acquire locks in unrelated parts of the
187  *     filesystem?)
188  *   - An inode should not be locked while the filesystem lock is already held,
189  *     since some code may do an inode lookup (which acquires the filesystem
190  *     lock) while a different inode is locked.
191  * */
192 typedef struct {
193     GMutex *lock;
194     gint refcount;
195
196     BlueSkyFS *fs;
197
198     BlueSkyFileType type;
199     uint32_t mode;
200     uint32_t uid, gid;
201     uint32_t nlink;
202
203     /* Rather than track an inode number and generation number, we will simply
204      * never re-use a fileid after a file is deleted.  64 bits should be enough
205      * that we don't exhaust the identifier space. */
206     uint64_t inum;
207
208     /* change_count is increased with every operation which modifies the inode,
209      * and can be used to determine if cached data is still valid.
210      * change_commit is the value of change_count when the inode was last
211      * committed to stable storage (the log).
212      * change_cloud tracks which version was last commited to cloud storage. */
213     uint64_t change_count, change_commit, change_cloud;
214
215     /* Timestamp for controlling when modified data is flushed to stable
216      * storage.  When an inode is first modified from a clean state, this is
217      * set to the current time.  If the inode is clean, it is set to zero. */
218     int64_t change_time;
219
220     /* Last access time to this inode, for controlling cache evictions. */
221     int64_t access_time;
222
223     /* Additional state for tracking cache writeback status. */
224     uint64_t change_pending;    /* change_count version currently being committed to storage */
225
226     /* Version of the object last serialized and committed to storage. */
227     BlueSkyCloudLog *committed_item;
228
229     /* Pointers to the linked-list elements for this inode in the accessed and
230      * dirty linked lists.  We re-use the GList structure, using ->next to
231      * point to the head of the list and ->prev to point to the tail.  The data
232      * element is unused. */
233     GList *unlogged_list, *accessed_list, *dirty_list;
234
235     int64_t atime;              /* Microseconds since the Unix epoch */
236     int64_t ctime;
237     int64_t mtime;
238     int64_t ntime;              /* "new time": time object was created */
239
240     /* File-specific fields */
241     uint64_t size;
242     GArray *blocks;
243
244     /* Directory-specific fields */
245     GSequence *dirents;         /* List of entries for READDIR */
246     GHashTable *dirhash;        /* Hash table by name for LOOKUP */
247     GHashTable *dirhash_folded; /* As above, but case-folded */
248     uint64_t parent_inum;       /* inode for ".."; 0 if the root directory */
249
250     /* Symlink-specific fields */
251     gchar *symlink_contents;
252 } BlueSkyInode;
253
254 /* A directory entry.  The name is UTF-8 and is a freshly-allocated string.
255  * Each directory entry is listed in two indices: dirents is indexed by cookie
256  * and dirhash by name.  The cookie is a randomly-assigned 32-bit value, unique
257  * within the directory, that remains unchanged until the entry is deleted.  It
258  * is used to provide a stable key for restarting a READDIR call. */
259 typedef struct {
260     gchar *name;
261     gchar *name_folded;         /* Name, folded for case-insensitive lookup */
262     uint32_t cookie;
263     uint64_t inum;
264 } BlueSkyDirent;
265
266 /* File data is divided into fixed-size blocks (except the last block which may
267  * be short?).  These blocks are backed by storage in a key/value store, but
268  * may also be dirty if modifications have been made in-memory that have not
269  * been committed. */
270 #define BLUESKY_BLOCK_SIZE 32768ULL
271 #define BLUESKY_MAX_FILE_SIZE (BLUESKY_BLOCK_SIZE << 24)
272 typedef enum {
273     BLUESKY_BLOCK_ZERO = 0,     /* Data is all zeroes, not explicitly stored */
274     BLUESKY_BLOCK_REF = 1,      /* Reference to key/value store, not cached */
275     BLUESKY_BLOCK_CACHED = 2,   /* Data is cached in memory, clean */
276     BLUESKY_BLOCK_DIRTY = 3,    /* Data needs to be committed to store */
277 } BlueSkyBlockType;
278
279 typedef struct {
280     BlueSkyBlockType type;
281     BlueSkyRCStr *data;         /* Pointer to data in memory if cached */
282     BlueSkyCloudLog *cloudref;  /* Reference to cloud log entry with data */
283 } BlueSkyBlock;
284
285 BlueSkyFS *bluesky_init_fs(gchar *name, BlueSkyStore *store);
286 void bluesky_superblock_flush(BlueSkyFS *fs);
287
288 gboolean bluesky_inode_is_ready(BlueSkyInode *inode);
289
290 int64_t bluesky_get_current_time();
291 void bluesky_inode_update_ctime(BlueSkyInode *inode, gboolean update_mtime);
292 uint64_t bluesky_fs_alloc_inode(BlueSkyFS *fs);
293 void bluesky_init_inode(BlueSkyInode *i, BlueSkyFileType type);
294 BlueSkyInode *bluesky_new_inode(uint64_t inum, BlueSkyFS *fs, BlueSkyFileType type);
295
296 BlueSkyInode *bluesky_get_inode(BlueSkyFS *fs, uint64_t inum);
297 void bluesky_inode_ref(BlueSkyInode *inode);
298 void bluesky_inode_unref(BlueSkyInode *inode);
299 void bluesky_insert_inode(BlueSkyFS *fs, BlueSkyInode *inode);
300
301 void bluesky_dirent_destroy(gpointer dirent);
302 uint64_t bluesky_directory_lookup(BlueSkyInode *inode, gchar *name);
303 uint64_t bluesky_directory_ilookup(BlueSkyInode *inode, gchar *name);
304 BlueSkyDirent *bluesky_directory_read(BlueSkyInode *dir, uint32_t cookie);
305 gboolean bluesky_directory_insert(BlueSkyInode *dir, const gchar *name,
306                                   uint64_t inum);
307 void bluesky_directory_dump(BlueSkyInode *dir);
308
309 void bluesky_file_truncate(BlueSkyInode *inode, uint64_t size);
310 void bluesky_file_write(BlueSkyInode *inode, uint64_t offset,
311                         const char *data, gint len);
312 void bluesky_file_read(BlueSkyInode *inode, uint64_t offset,
313                        char *buf, gint len);
314
315 void bluesky_inode_fetch(BlueSkyFS *fs, uint64_t inum);
316
317 gint bluesky_dirent_compare(gconstpointer a, gconstpointer b,
318                             gpointer unused);
319
320 void bluesky_flushd_invoke(BlueSkyFS *fs);
321 void bluesky_flushd_invoke_conditional(BlueSkyFS *fs);
322 void bluesky_inode_do_sync(BlueSkyInode *inode);
323 void bluesky_flushd_thread_launch(BlueSkyFS *fs);
324
325 void bluesky_debug_dump(BlueSkyFS *fs);
326
327 #ifdef __cplusplus
328 }
329 #endif
330
331 #endif