Add support for byterange requests in the storage layer.
[bluesky.git] / bluesky / bluesky-private.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 /* Declarations internal to the BlueSky library.  This header file should not
10  * be included by any users of the library (such as any filesystem
11  * proxy)--external users should only include bluesky.h. */
12
13 #ifndef _BLUESKY_PRIVATE_H
14 #define _BLUESKY_PRIVATE_H
15
16 #include "bluesky.h"
17
18 #ifdef __cplusplus
19 extern "C" {
20 #endif
21
22 extern int bluesky_verbose;
23
24 /* Target cache size levels. */
25 extern int bluesky_watermark_low_dirty;
26 extern int bluesky_watermark_medium_dirty;
27 extern int bluesky_watermark_high_dirty;
28
29 extern int bluesky_watermark_low_total;
30 extern int bluesky_watermark_medium_total;
31 extern int bluesky_watermark_high_total;
32
33 /* TODO: Make this go away entirely. */
34 BlueSkyFS *bluesky_new_fs(gchar *name);
35
36 void bluesky_inode_free_resources(BlueSkyInode *inode);
37
38 /* Linked list update functions for LRU lists. */
39 void bluesky_list_unlink(GList *head, GList *item);
40 GList *bluesky_list_prepend(GList *head, BlueSkyInode *inode);
41 GList *bluesky_list_append(GList *head, BlueSkyInode *inode);
42 BlueSkyInode *bluesky_list_head(GList *head);
43 BlueSkyInode *bluesky_list_tail(GList *head);
44
45 /* Serialization and deserialization of filesystem data for storing to
46  * persistent storage. */
47 void bluesky_serialize_superblock(GString *out, BlueSkyFS *fs);
48 BlueSkyFS *bluesky_deserialize_superblock(const gchar *buf);
49 BlueSkyCloudLog *bluesky_serialize_inode(BlueSkyInode *inode);
50 gboolean bluesky_deserialize_inode(BlueSkyInode *inode, BlueSkyCloudLog *item);
51
52 void bluesky_deserialize_cloudlog(BlueSkyCloudLog *item,
53                                   const char *data,
54                                   size_t len);
55
56 void bluesky_serialize_cloudlog(BlueSkyCloudLog *log,
57                                 GString *encrypted,
58                                 GString *authenticated,
59                                 GString *writable);
60
61 /* Cryptographic operations. */
62 #define CRYPTO_BLOCK_SIZE 16        /* 128-bit AES */
63 #define CRYPTO_KEY_SIZE   16
64 #define CRYPTO_HASH_SIZE  32        /* SHA-256 */
65
66 typedef struct BlueSkyCryptKeys {
67     uint8_t encryption_key[CRYPTO_KEY_SIZE];
68     uint8_t authentication_key[CRYPTO_HASH_SIZE];
69 } BlueSkyCryptKeys;
70
71 void bluesky_crypt_init();
72 void bluesky_crypt_hash_key(const char *keystr, uint8_t *out);
73 void bluesky_crypt_random_bytes(guchar *buf, gint len);
74 void bluesky_crypt_derive_keys(BlueSkyCryptKeys *keys, const gchar *master);
75 BlueSkyRCStr *bluesky_crypt_encrypt(BlueSkyRCStr *in, const uint8_t *key);
76 BlueSkyRCStr *bluesky_crypt_decrypt(BlueSkyRCStr *in, const uint8_t *key);
77
78 void bluesky_crypt_block_encrypt(gchar *cloud_block, size_t len,
79                                  BlueSkyCryptKeys *keys);
80 gboolean bluesky_crypt_block_decrypt(gchar *cloud_block, size_t len,
81                                      BlueSkyCryptKeys *keys);
82 void bluesky_cloudlog_encrypt(GString *segment, BlueSkyCryptKeys *keys);
83 void bluesky_cloudlog_decrypt(char *segment, size_t len,
84                               BlueSkyCryptKeys *keys);
85
86 /* Storage layer.  Requests can be performed asynchronously, so these objects
87  * help keep track of operations in progress. */
88 typedef enum {
89     STORE_OP_NONE,
90     STORE_OP_GET,
91     STORE_OP_PUT,
92     STORE_OP_DELETE,
93     STORE_OP_BARRIER,       // Waits for other selected operations to complete
94 } BlueSkyStoreOp;
95
96 typedef enum {
97     ASYNC_NEW,              // Operation not yet submitted to storage layer
98     ASYNC_PENDING,          // Submitted to storage layer
99     ASYNC_RUNNING,          // Operation is in progress
100     ASYNC_COMPLETE,         // Operation finished, results available
101 } BlueSkyAsyncStatus;
102
103 struct BlueSkyNotifierList;
104 typedef struct BlueSkyStoreAsync BlueSkyStoreAsync;
105 struct BlueSkyStoreAsync {
106     BlueSkyStore *store;
107
108     GMutex *lock;
109     GCond *completion_cond;     /* Used to wait for operation to complete. */
110
111     gint refcount;              /* Reference count for destruction. */
112
113     BlueSkyAsyncStatus status;
114
115     BlueSkyStoreOp op;
116     gchar *key;                 /* Key to read/write */
117     BlueSkyRCStr *data;         /* Data read/to write */
118
119     /* For range requests on reads: starting byte offset and length; len 0
120      * implies reading to the end of the object.  At completion, the backend
121      * should set range_done if a range read was made; if not set the entire
122      * object was read and the storage layer will select out just the
123      * appropriate bytes. */
124     size_t start, len;
125     gboolean range_done;
126
127     int result;                 /* Result code; 0 for success. */
128     struct BlueSkyNotifierList *notifiers;
129     gint notifier_count;
130
131     /* The barrier waiting on this operation.  Support for more than one
132      * barrier for a single async is not well-supported and should be avoided
133      * if possible. */
134     BlueSkyStoreAsync *barrier;
135
136     bluesky_time_hires start_time;  /* Time operation was submitted. */
137     bluesky_time_hires exec_time;   /* Time processing started on operation. */
138
139     gpointer store_private;     /* For use by the storage implementation */
140 };
141
142 /* Support for notification lists.  These are lists of one-shot functions which
143  * can be called when certain events--primarily, competed storage
144  * events--occur.  Multiple notifiers can be added, but no particular order is
145  * guaranteed for the notification functions to be called. */
146 struct BlueSkyNotifierList {
147     struct BlueSkyNotifierList *next;
148     GFunc func;
149     BlueSkyStoreAsync *async;
150     gpointer user_data;     // Passed to the function when called
151 };
152
153 /* The abstraction layer for storage, allowing multiple implementations. */
154 typedef struct {
155     /* Create a new store instance and return a handle to it. */
156     gpointer (*create)(const gchar *path);
157
158     /* Clean up any resources used by this store. */
159     void (*destroy)(gpointer store);
160
161     /* Submit an operation (get/put/delete) to the storage layer to be
162      * performed asynchronously. */
163     void (*submit)(gpointer store, BlueSkyStoreAsync *async);
164
165     /* Clean up any implementation-private data in a BlueSkyStoreAsync. */
166     void (*cleanup)(gpointer store, BlueSkyStoreAsync *async);
167
168     /* Find the lexicographically-largest file starting with the specified
169      * prefix. */
170     char * (*lookup_last)(gpointer store, const gchar *prefix);
171 } BlueSkyStoreImplementation;
172
173 void bluesky_store_register(const BlueSkyStoreImplementation *impl,
174                             const gchar *name);
175
176 char *bluesky_store_lookup_last(BlueSkyStore *store, const char *prefix);
177 BlueSkyStoreAsync *bluesky_store_async_new(BlueSkyStore *store);
178 gpointer bluesky_store_async_get_handle(BlueSkyStoreAsync *async);
179 void bluesky_store_async_ref(BlueSkyStoreAsync *async);
180 void bluesky_store_async_unref(BlueSkyStoreAsync *async);
181 void bluesky_store_async_wait(BlueSkyStoreAsync *async);
182 void bluesky_store_async_add_notifier(BlueSkyStoreAsync *async,
183                                       GFunc func, gpointer user_data);
184 void bluesky_store_async_mark_complete(BlueSkyStoreAsync *async);
185 void bluesky_store_async_submit(BlueSkyStoreAsync *async);
186 void bluesky_store_sync(BlueSkyStore *store);
187
188 void bluesky_store_add_barrier(BlueSkyStoreAsync *barrier,
189                                BlueSkyStoreAsync *async);
190
191 void bluesky_inode_start_sync(BlueSkyInode *inode);
192
193 void bluesky_block_touch(BlueSkyInode *inode, uint64_t i);
194 void bluesky_block_fetch(BlueSkyInode *inode, BlueSkyBlock *block,
195                          BlueSkyStoreAsync *barrier);
196 void bluesky_block_flush(BlueSkyInode *inode, BlueSkyBlock *block,
197                          GList **log_items);
198 void bluesky_file_flush(BlueSkyInode *inode, GList **log_items);
199 void bluesky_file_drop_cached(BlueSkyInode *inode);
200
201 /* Writing of data to the cloud in log segments and tracking the location of
202  * various pieces of data (both where in the cloud and where cached locally).
203  * */
204
205 typedef struct {
206     char bytes[16];
207 } BlueSkyCloudID;
208
209 typedef struct {
210     uint32_t directory;
211     uint32_t sequence;
212     uint32_t offset;
213     uint32_t size;
214 } BlueSkyCloudPointer;
215
216 typedef enum {
217     LOGTYPE_INVALID = -1,
218     LOGTYPE_UNKNOWN = 0,
219     LOGTYPE_DATA = 1,
220     LOGTYPE_INODE = 2,
221     LOGTYPE_INODE_MAP = 3,
222     LOGTYPE_CHECKPOINT = 4,
223
224     /* Used only as metadata in the local journal, not loaded as a
225      * BlueSkyCloudLogState nor stored in the cloud */
226     LOGTYPE_JOURNAL_MARKER = 16,
227     LOGTYPE_JOURNAL_CHECKPOINT = 17,
228 } BlueSkyCloudLogType;
229
230 /* Headers that go on items in local log segments and cloud log segments. */
231 struct log_header {
232     uint32_t magic;             // HEADER_MAGIC
233     uint8_t type;               // Object type + '0'
234     uint32_t offset;            // Starting byte offset of the log header
235     uint32_t size1;             // Size of the data item (bytes)
236     uint32_t size2;             //
237     uint32_t size3;             //
238     uint64_t inum;              // Inode which owns this data, if any
239     BlueSkyCloudID id;          // Object identifier
240 } __attribute__((packed));
241
242 struct log_footer {
243     uint32_t magic;             // FOOTER_MAGIC
244     uint32_t crc;               // Computed from log_header to log_footer.magic
245 } __attribute__((packed));
246
247 struct cloudlog_header {
248     char magic[4];
249     uint8_t crypt_auth[CRYPTO_HASH_SIZE];
250     uint8_t crypt_iv[CRYPTO_BLOCK_SIZE];
251     uint8_t type;
252     BlueSkyCloudID id;
253     uint64_t inum;
254     uint32_t size1, size2, size3;
255 } __attribute__((packed));
256
257 #define JOURNAL_MAGIC "\nLog"
258 #define CLOUDLOG_MAGIC "AgI-"
259 #define CLOUDLOG_MAGIC_ENCRYPTED "AgI="     // CLOUDLOG_MAGIC[3] ^= 0x10
260
261 /* A record which tracks an object which has been written to a local log,
262  * cached, locally, and/or written to the cloud. */
263 #define CLOUDLOG_JOURNAL    0x01
264 #define CLOUDLOG_CLOUD      0x02
265 #define CLOUDLOG_CACHE      0x04
266 #define CLOUDLOG_UNCOMMITTED 0x10
267 struct BlueSkyCloudLog {
268     gint refcount;
269     GMutex *lock;
270     GCond *cond;
271
272     BlueSkyFS *fs;
273
274     BlueSkyCloudLogType type;
275
276     // Bitmask of CLOUDLOG_* flags indicating where the object exists.
277     int location_flags;
278     int pending_read, pending_write;
279
280     // A stable identifier for the object (only changes when authenticated data
281     // is written out, but stays the same when the in-cloud cleaner relocates
282     // the object).
283     BlueSkyCloudID id;
284
285     // The inode which owns this data, if any, and an offset.
286     uint64_t inum;
287     int32_t inum_offset;
288
289     // The size of encrypted object data, not including any headers
290     int data_size;
291
292     // The location of the object in the cloud, if available.
293     BlueSkyCloudPointer location;
294
295     // TODO: Location in journal/cache
296     int log_seq, log_offset, log_size;
297
298     // Pointers to other objects.  Each link counts towards the reference count
299     // of the pointed-to object.  To avoid memory leaks there should be no
300     // cycles in the reference graph.
301     GArray *links;
302
303     // Serialized data, if available in memory (otherwise NULL), and a lock
304     // count which tracks if there are users that require the data to be kept
305     // around.
306     BlueSkyRCStr *data;
307     int data_lock_count;
308 };
309
310 /* Serialize objects into a log segment to be written to the cloud. */
311 struct BlueSkyCloudLogState {
312     GString *data;
313     BlueSkyCloudPointer location;
314     GList *inode_list;
315     GSList *writeback_list;     // Items which are being serialized right now
316     GList *pending_segments;    // Segments which are being uploaded now
317 };
318
319 gboolean bluesky_cloudlog_equal(gconstpointer a, gconstpointer b);
320 guint bluesky_cloudlog_hash(gconstpointer a);
321 BlueSkyCloudLog *bluesky_cloudlog_new(BlueSkyFS *fs, const BlueSkyCloudID *id);
322 gchar *bluesky_cloudlog_id_to_string(BlueSkyCloudID id);
323 BlueSkyCloudID bluesky_cloudlog_id_from_string(const gchar *idstr);
324 void bluesky_cloudlog_threads_init(BlueSkyFS *fs);
325 void bluesky_cloudlog_ref(BlueSkyCloudLog *log);
326 void bluesky_cloudlog_unref(BlueSkyCloudLog *log);
327 void bluesky_cloudlog_unref_delayed(BlueSkyCloudLog *log);
328 void bluesky_cloudlog_erase(BlueSkyCloudLog *log);
329 void bluesky_cloudlog_stats_update(BlueSkyCloudLog *log, int type);
330 void bluesky_cloudlog_sync(BlueSkyCloudLog *log);
331 void bluesky_cloudlog_insert(BlueSkyCloudLog *log);
332 void bluesky_cloudlog_insert_locked(BlueSkyCloudLog *log);
333 BlueSkyCloudLog *bluesky_cloudlog_get(BlueSkyFS *fs, BlueSkyCloudID id);
334 void bluesky_cloudlog_fetch(BlueSkyCloudLog *log);
335 BlueSkyCloudPointer bluesky_cloudlog_serialize(BlueSkyCloudLog *log,
336                                                BlueSkyFS *fs);
337 void bluesky_cloudlog_flush(BlueSkyFS *fs);
338
339 /* Logging infrastructure for ensuring operations are persistently recorded to
340  * disk. */
341 #define BLUESKY_CRC32C_SEED (~(uint32_t)0)
342 #define BLUESKY_CRC32C_VALIDATOR ((uint32_t)0xb798b438UL)
343 uint32_t crc32c(uint32_t crc, const char *buf, unsigned int length);
344 uint32_t crc32c_finalize(uint32_t crc);
345
346 struct BlueSkyLog {
347     BlueSkyFS *fs;
348     char *log_directory;
349     GAsyncQueue *queue;
350     int fd, dirfd;
351     int seq_num;
352     GSList *committed;
353
354     /* The currently-open log file. */
355     BlueSkyCacheFile *current_log;
356
357     /* Cache of log segments which have been memory-mapped. */
358     GMutex *mmap_lock;
359     GHashTable *mmap_cache;
360
361     /* A count of the disk space consumed (in 1024-byte units) by all files
362      * tracked by mmap_cache (whether mapped or not, actually). */
363     gint disk_used;
364
365     /* The smallest journal sequence number which may still contain data that
366      * must be preserved (since it it not yet in the cloud). */
367     int journal_watermark;
368 };
369
370 /* An object for tracking log files which are stored locally--either the
371  * journal for filesystem consistency or log segments which have been fetched
372  * back from cloud storage. */
373 struct BlueSkyCacheFile {
374     GMutex *lock;
375     GCond *cond;
376     gint refcount;
377     int type;                   // Only one of CLOUDLOG_{JOURNAL,CLOUD}
378     int log_dir;
379     int log_seq;
380     char *filename;             // Local filename, relateive to log directory
381     gint mapcount;              // References to the mmaped data
382     const char *addr;           // May be null if data is not mapped in memory
383     size_t len;
384     BlueSkyFS *fs;
385     BlueSkyLog *log;
386     gboolean fetching, ready;   // Cloud data: downloading or ready for use
387     int64_t atime;              // Access time, for cache management
388 };
389
390 BlueSkyLog *bluesky_log_new(const char *log_directory);
391 void bluesky_log_item_submit(BlueSkyCloudLog *item, BlueSkyLog *log);
392 void bluesky_log_finish_all(GList *log_items);
393 BlueSkyCloudLog *bluesky_log_get_commit_point(BlueSkyFS *fs);
394 void bluesky_log_write_commit_point(BlueSkyFS *fs, BlueSkyCloudLog *marker);
395
396 BlueSkyRCStr *bluesky_log_map_object(BlueSkyFS *fs, int log_dir, int log_seq,
397                                      int log_offset, int log_size);
398 void bluesky_mmap_unref(BlueSkyCacheFile *mmap);
399 void bluesky_cachefile_unref(BlueSkyCacheFile *cachefile);
400
401 BlueSkyCacheFile *bluesky_cachefile_lookup(BlueSkyFS *fs,
402                                            int clouddir, int log_seq);
403 void bluesky_cachefile_gc(BlueSkyFS *fs);
404
405 void bluesky_replay(BlueSkyFS *fs);
406
407 /* Used to track log segments that are being written to the cloud. */
408 typedef struct {
409     BlueSkyRCStr *data;
410     GSList *items;
411     GMutex *lock;
412     GCond *cond;
413     gboolean complete;
414 } SerializedRecord;
415
416 /***** Inode map management *****/
417
418 /* Mapping information for a single inode number.  These are grouped together
419  * into InodeMapRange objects. */
420 typedef struct {
421     uint64_t inum;
422
423     /* A pointer to the cloud log entry for this inode.  This may or may not
424      * actually have data loaded (it might just contain pointers to the data
425      * location, and in fact this will likely often be the case). */
426     BlueSkyCloudLog *item;
427 } InodeMapEntry;
428
429 typedef struct {
430     /* Starting and ending inode number values that fall in this section.
431      * Endpoint values are inclusive. */
432     uint64_t start, end;
433
434     /* A sorted list (by inode number) of InodeMapEntry objects. */
435     GSequence *map_entries;
436
437     /* The serialized version of the inode map data. */
438     BlueSkyCloudLog *serialized;
439
440     /* Have there been changes that require writing this section out again? */
441     gboolean dirty;
442 } InodeMapRange;
443
444 InodeMapEntry *bluesky_inode_map_lookup(GSequence *inode_map, uint64_t inum,
445                                         int action);
446 BlueSkyCloudLog *bluesky_inode_map_serialize(BlueSkyFS *fs);
447 void bluesky_inode_map_minimize(BlueSkyFS *fs);
448
449 gboolean bluesky_checkpoint_load(BlueSkyFS *fs);
450
451 #ifdef __cplusplus
452 }
453 #endif
454
455 #endif