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