Automatically split segments to meet size targets.
[cumulus.git] / tarstore.h
1 /* LBS: An LFS-inspired filesystem backup system
2  * Copyright (C) 2006  Michael Vrable
3  *
4  * Backup data is stored in a collection of objects, which are grouped together
5  * into segments for storage purposes.  This implementation of the object store
6  * is built on top of libtar, and represents segments as TAR files and objects
7  * as files within them. */
8
9 #ifndef _LBS_TARSTORE_H
10 #define _LBS_TARSTORE_H
11
12 #include <stdint.h>
13 #include <libtar.h>
14
15 #include <string>
16 #include <iostream>
17 #include <sstream>
18
19 #include "store.h"
20
21 /* A simple wrapper around a single TAR file to represent a segment.  Objects
22  * may only be written out all at once, since the tar header must be written
23  * first; incremental writing is not supported. */
24 class Tarfile {
25 public:
26     Tarfile(const std::string &path, const std::string &segment);
27     ~Tarfile();
28
29     void write_object(int id, const char *data, size_t len);
30
31     // Return an estimate of the size of the file.
32     size_t size_estimate() { return size; }
33
34 private:
35     void internal_write_object(const std::string &path,
36                                const char *data, size_t len);
37
38     size_t size;
39     std::string segment_name;
40     std::ostringstream checksums;
41     TAR *t;
42 };
43
44 class TarSegmentStore {
45 public:
46     // New segments will be stored in the given directory.
47     TarSegmentStore(const std::string &path) { this->path = path; }
48     ~TarSegmentStore() { sync(); }
49
50     // Writes an object to segment in the store, and returns the name
51     // (segment/object) to refer to it.  The optional parameter group can be
52     // used to control object placement; objects with different group
53     // parameters are kept in separate segments.
54     std::string write_object(const char *data, size_t len,
55                              const std::string &group = "");
56
57     // Ensure all segments have been fully written.
58     void sync();
59
60 private:
61     struct segment_info {
62         Tarfile *file;
63         std::string name;       // UUID
64         int count;              // Objects written to this segment
65     };
66
67     std::string path;
68     std::map<std::string, struct segment_info *> segments;
69
70     // Ensure that all segments in the given group have been fully written.
71     void close_segment(const std::string &group);
72 };
73
74 #endif // _LBS_TARSTORE_H