Replace boost::scoped_ptr with std::unique_ptr.
[cumulus.git] / store.h
diff --git a/store.h b/store.h
index 0cd2c4b..b58ea34 100644 (file)
--- a/store.h
+++ b/store.h
-/* LBS: An LFS-inspired filesystem backup system
- * Copyright (C) 2006  Michael Vrable
+/* Cumulus: Efficient Filesystem Backup to the Cloud
+ * Copyright (C) 2006-2008 The Cumulus Developers
+ * See the AUTHORS file for a list of contributors.
  *
- * Backup data is stored in a collection of objects, which are grouped together
- * into segments for storage purposes.  This file provides interfaces for
- * reading and writing objects and segments. */
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+
+/* Backup data is stored in a collection of objects, which are grouped together
+ * into segments for storage purposes.  This implementation of the object store
+ * represents segments as TAR files and objects as files within them. */
 
 #ifndef _LBS_STORE_H
 #define _LBS_STORE_H
 
 #include <stdint.h>
 
-#include <exception>
+#include <list>
 #include <map>
+#include <memory>
+#include <set>
 #include <string>
+#include <iostream>
 #include <sstream>
-#include <vector>
+
+#include "localdb.h"
+#include "remote.h"
+#include "ref.h"
+#include "third_party/sha1.h"
+
+class LbsObject;
 
 /* In memory datatype to represent key/value pairs of information, such as file
  * metadata.  Currently implemented as map<string, string>. */
 typedef std::map<std::string, std::string> dictionary;
 
-/* IOException will be thrown if an error occurs while reading or writing in
- * one of the I/O wrappers.  Depending upon the context; this may be fatal or
- * not--typically, errors reading/writing the store will be serious, but errors
- * reading an individual file are less so. */
-class IOException : public std::exception {
-private:
-    std::string error;
-public:
-    explicit IOException(const std::string &err) { error = err; }
-    virtual ~IOException() throw () { }
-    std::string getError() const { return error; }
+/* Simplified TAR header--we only need to store regular files, don't need to
+ * handle long filenames, etc. */
+static const int TAR_BLOCK_SIZE = 512;
+
+struct tar_header
+{
+    char name[100];
+    char mode[8];
+    char uid[8];
+    char gid[8];
+    char size[12];
+    char mtime[12];
+    char chksum[8];
+    char typeflag;
+    char linkname[100];
+    char magic[8];
+    char uname[32];
+    char gname[32];
+    char devmajor[8];
+    char devminor[8];
+    char prefix[155];
+    char padding[12];
 };
 
-/* OutputStream is an abstract interface for writing data without seeking.
- * Output could be to a file, to an object within a segment, or even to a
- * memory buffer to help serialize data. */
-class OutputStream {
+class FileFilter {
 public:
-    OutputStream();
-    virtual ~OutputStream() { }
-
-    // Write the given data buffer
-    void write(const void *data, size_t len);
-
-    // Return the total number of bytes written so far
-    int64_t get_pos() const { return bytes_written; }
+    // It is valid for program to be NULL or empty; if so, no filtering is
+    // done.
+    static FileFilter *New(int fd, const char *program);
 
-    // Convenience functions for writing other data types.  Values are always
-    // written out in little-endian order.
-    void write_u8(uint8_t val);
-    void write_u16(uint16_t val);
-    void write_u32(uint32_t val);
-    void write_u64(uint64_t val);
+    // Wait for the filter process to terminate.
+    int wait();
 
-    void write_s32(int32_t val) { write_u32((uint32_t)val); }
-    void write_s64(int64_t val) { write_u64((uint64_t)val); }
-
-    void write_varint(uint64_t val);
-
-    void write_string(const std::string &s);
-    void write_dictionary(const dictionary &d);
-
-protected:
-    // Function which actually causes a write: must be overridden by
-    // implementation.
-    virtual void write_internal(const void *data, size_t len) = 0;
+    // Accessors for the file descriptors.
+    int get_raw_fd() const { return fd_raw; }
+    int get_wrapped_fd() const { return fd_wrapped; }
 
 private:
-    int64_t bytes_written;
+    FileFilter(int raw, int wrapped, pid_t pid);
+
+    // Launch a process to filter data written to a file descriptor.  fd_out is
+    // the file descriptor where the filtered data should be written.  program
+    // is the filter program to execute (a single string which will be
+    // interpreted by /bin/sh).  The return value is a file descriptor to which
+    // the data to be filtered should be written.  The process ID of the filter
+    // process is stored at address filter_pid if non-NULL.
+    static int spawn_filter(int fd_out, const char *program, pid_t *filter_pid);
+
+    // The original file descriptor passed when creating the FileFilter object.
+    int fd_raw;
+
+    // The wrapped file descriptor: writes here are piped through the filter
+    // program.
+    int fd_wrapped;
+
+    // The filter process if one was launched, or -1 if there is no filter
+    // program.
+    pid_t pid;
 };
 
-/* An OutputStream implementation which writes data to memory and returns the
- * result as a string. */
-class StringOutputStream : public OutputStream {
+/* A simple wrapper around a single TAR file to represent a segment.  Objects
+ * may only be written out all at once, since the tar header must be written
+ * first; incremental writing is not supported. */
+class Tarfile {
 public:
-    StringOutputStream();
-    std::string contents() const { return buf.str(); }
+    Tarfile(RemoteFile *file, const std::string &segment);
+    ~Tarfile();
 
-protected:
-    virtual void write_internal(const void *data, size_t len);
+    void write_object(int id, const char *data, size_t len);
 
-private:
-    std::stringstream buf;
-};
+    // Return an estimate of the size of the file.
+    size_t size_estimate();
 
-/* An OutputStream implementation which writes data via the C stdio layer. */
-class FileOutputStream : public OutputStream {
-public:
-    explicit FileOutputStream(FILE *file);
-    virtual ~FileOutputStream();
+private:
+    size_t size;
+    std::string segment_name;
 
-protected:
-    virtual void write_internal(const void *data, size_t len);
+    RemoteFile *file;
+    std::unique_ptr<FileFilter> filter;
 
-private:
-    FILE *f;
+    // Write data to the tar file
+    void tar_write(const char *data, size_t size);
 };
 
-/* An OutputStream which is simply sends writes to another OutputStream, but
- * does provide separate tracking of bytes written. */
-class WrapperOutputStream : public OutputStream {
+class TarSegmentStore {
 public:
-    explicit WrapperOutputStream(OutputStream &o);
-    virtual ~WrapperOutputStream() { }
-
-protected:
-    virtual void write_internal(const void *data, size_t len);
+    // New segments will be stored in the given directory.
+    TarSegmentStore(RemoteStore *remote,
+                    LocalDb *db = NULL)
+        { this->remote = remote; this->db = db; }
+    ~TarSegmentStore() { sync(); }
+
+    // Writes an object to segment in the store, and returns the name
+    // (segment/object) to refer to it.  The optional parameter group can be
+    // used to control object placement; objects with different group
+    // parameters are kept in separate segments.
+    ObjectReference write_object(const char *data, size_t len,
+                                 const std::string &group = "",
+                                 const std::string &checksum = "",
+                                 double age = 0.0);
+
+    // Ensure all segments have been fully written.
+    void sync();
+
+    // Dump statistics to stdout about how much data has been written
+    void dump_stats();
 
 private:
-    OutputStream &real;
-};
-
-/* Simple wrappers that encode integers using a StringOutputStream and return
- * the encoded result. */
-std::string encode_u16(uint16_t val);
-std::string encode_u32(uint32_t val);
-std::string encode_u64(uint64_t val);
-
-struct uuid {
-    uint8_t bytes[16];
+    struct segment_info {
+        Tarfile *file;
+        std::string group;
+        std::string name;           // UUID
+        int count;                  // Objects written to this segment
+        int data_size;              // Combined size of objects written
+        std::string basename;       // Name of segment without directory
+        RemoteFile *rf;
+    };
+
+    RemoteStore *remote;
+    std::map<std::string, struct segment_info *> segments;
+    LocalDb *db;
+
+    // Ensure that all segments in the given group have been fully written.
+    void close_segment(const std::string &group);
+
+    // Parse an object reference string and return just the segment name
+    // portion.
+    std::string object_reference_to_segment(const std::string &object);
 };
 
-/* A class which is used to pack multiple objects into a single segment, with a
- * lookup table to quickly locate each object.  Call new_object() to get an
- * OutputStream to which a new object may be written, and optionally
- * finish_object() when finished writing the current object.  Only one object
- * may be written to a segment at a time; if multiple objects must be written
- * concurrently, they must be to different segments. */
-class SegmentWriter {
+/* An in-memory representation of an object, which can be incrementally built
+ * before it is written out to a segment. */
+class LbsObject {
 public:
-    SegmentWriter(OutputStream *output, struct uuid u);
-    ~SegmentWriter();
-
-    struct uuid get_uuid() const { return id; }
-
-    // Start writing out a new object to this segment.
-    OutputStream *new_object();
-    void finish_object();
-
-    // Utility functions for generating and formatting UUIDs for display.
-    static struct uuid generate_uuid();
-    static std::string format_uuid(const struct uuid u);
+    LbsObject();
+    ~LbsObject();
+
+    // If an object is placed in a group, it will be written out to segments
+    // only containing other objects in the same group.  A group name is simply
+    // a string.
+    //std::string get_group() const { return group; }
+    void set_group(const std::string &g) { group = g; }
+
+    // Data in an object must be written all at once, and cannot be generated
+    // incrementally.  Data can be an arbitrary block of binary data of any
+    // size.  The pointer to the data need only remain valid until write() is
+    // called.  If checksum is non-NULL then it is assumed to contain a hash
+    // value for the data; this provides an optimization in case the caller has
+    // already checksummed the data.  Otherwise the set_data will compute a
+    // hash of the data itself.
+    void set_data(const char *d, size_t len, const char *checksum);
+
+    // Explicitly sets the age of the data, for later garbage-collection or
+    // repacking purposes.  If not set, the age defaults to the current time.
+    // The age is stored in the database as a floating point value, expressing
+    // the time in Julian days.
+    void set_age(double age) { this->age = age; }
+
+    // Write an object to a segment, thus making it permanent.  This function
+    // can be called at most once.
+    void write(TarSegmentStore *store);
+
+    // An object is assigned a permanent name once it has been written to a
+    // segment.  Until that time, its name cannot be determined.
+    ObjectReference get_ref() { return ref; }
 
 private:
-    typedef std::vector<std::pair<int64_t, int64_t> > object_table;
-
-    OutputStream *out;
-    struct uuid id;
-
-    int64_t object_start_offset;
-    OutputStream *object_stream;
-
-    object_table objects;
+    std::string group;
+    double age;
+    const char *data;
+    size_t data_len;
+    std::string checksum;
+
+    bool written;
+    ObjectReference ref;
 };
 
-/* A SegmentStore, as the name suggests, is used to store the contents of many
- * segments.  The SegmentStore internally tracks where data should be placed
- * (such as a local directory or remote storage), and allows new segments to be
- * easily created as needed. */
-class SegmentStore {
-public:
-    // New segments will be stored in the given directory.
-    SegmentStore(const std::string &path);
-
-    SegmentWriter *new_segment();
+/* Program through which segment data is piped before being written to file. */
+extern const char *filter_program;
 
-private:
-    std::string directory;
-};
+/* Extension which should be appended to segments written out (.tar is already
+ * included; this adds to it) */
+extern const char *filter_extension;
 
 #endif // _LBS_STORE_H