Make segment compression/encryption filter to command-line-selectable.
[cumulus.git] / store.cc
1 /* LBS: An LFS-inspired filesystem backup system
2  * Copyright (C) 2007  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 #include <assert.h>
10 #include <stdio.h>
11 #include <sys/types.h>
12 #include <sys/stat.h>
13 #include <sys/resource.h>
14 #include <sys/wait.h>
15 #include <unistd.h>
16 #include <fcntl.h>
17 #include <time.h>
18
19 #include <algorithm>
20 #include <list>
21 #include <set>
22 #include <string>
23 #include <iostream>
24
25 #include "store.h"
26 #include "ref.h"
27
28 using std::max;
29 using std::list;
30 using std::set;
31 using std::string;
32
33 /* Default filter program is bzip2 */
34 const char *filter_program = "bzip2 -c";
35 const char *filter_extension = ".bz2";
36
37 static void cloexec(int fd)
38 {
39     long flags = fcntl(fd, F_GETFD);
40
41     if (flags < 0)
42         return;
43
44     fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
45 }
46
47 Tarfile::Tarfile(const string &path, const string &segment)
48     : size(0),
49       segment_name(segment)
50 {
51     real_fd = open(path.c_str(), O_WRONLY | O_CREAT, 0600);
52     if (real_fd < 0)
53         throw IOException("Error opening output file");
54
55     filter_fd = spawn_filter(real_fd);
56
57     if (tar_fdopen(&t, filter_fd, (char *)path.c_str(), NULL,
58                    O_WRONLY | O_CREAT, 0600, TAR_VERBOSE | TAR_GNU) == -1)
59         throw IOException("Error opening Tarfile");
60 }
61
62 Tarfile::~Tarfile()
63 {
64     /* Close the tar file... */
65     tar_append_eof(t);
66
67     if (tar_close(t) != 0)
68         throw IOException("Error closing Tarfile");
69
70     /* ...and wait for filter process to finish. */
71     int status;
72     waitpid(filter_pid, &status, 0);
73
74     if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
75         throw IOException("Filter process error");
76     }
77
78     close(real_fd);
79 }
80
81 /* Launch a child process which can act as a filter (compress, encrypt, etc.)
82  * on the TAR output.  The file descriptor to which output should be written
83  * must be specified; the return value is the file descriptor which will be
84  * attached to the standard input of the filter program. */
85 int Tarfile::spawn_filter(int fd_out)
86 {
87     int fds[2];
88
89     /* Create a pipe for communicating with the filter process. */
90     if (pipe(fds) < 0) {
91         throw IOException("Unable to create pipe for filter");
92     }
93
94     /* Create a child process which can exec() the filter program. */
95     filter_pid = fork();
96     if (filter_pid < 0)
97         throw IOException("Unable to fork filter process");
98
99     if (filter_pid > 0) {
100         /* Parent process */
101         close(fds[0]);
102         cloexec(fds[1]);
103     } else {
104         /* Child process.  Rearrange file descriptors.  stdin is fds[0], stdout
105          * is fd_out, stderr is unchanged. */
106         close(fds[1]);
107
108         if (dup2(fds[0], 0) < 0)
109             exit(1);
110         close(fds[0]);
111
112         if (dup2(fd_out, 1) < 0)
113             exit(1);
114         close(fd_out);
115
116         /* Exec the filter program. */
117         execlp("/bin/sh", "/bin/sh", "-c", filter_program, NULL);
118
119         /* Should not reach here except for error cases. */
120         fprintf(stderr, "Could not exec filter: %m\n");
121         exit(1);
122     }
123
124     return fds[1];
125 }
126
127 void Tarfile::write_object(int id, const char *data, size_t len)
128 {
129     char buf[64];
130     sprintf(buf, "%08x", id);
131     string path = segment_name + "/" + buf;
132
133     internal_write_object(path, data, len);
134 }
135
136 void Tarfile::internal_write_object(const string &path,
137                                     const char *data, size_t len)
138 {
139     memset(&t->th_buf, 0, sizeof(struct tar_header));
140
141     th_set_type(t, S_IFREG | 0600);
142     th_set_user(t, 0);
143     th_set_group(t, 0);
144     th_set_mode(t, 0600);
145     th_set_size(t, len);
146     th_set_mtime(t, time(NULL));
147     th_set_path(t, const_cast<char *>(path.c_str()));
148     th_finish(t);
149
150     if (th_write(t) != 0)
151         throw IOException("Error writing tar header");
152
153     size += T_BLOCKSIZE;
154
155     if (len == 0)
156         return;
157
158     size_t blocks = (len + T_BLOCKSIZE - 1) / T_BLOCKSIZE;
159     size_t padding = blocks * T_BLOCKSIZE - len;
160
161     for (size_t i = 0; i < blocks - 1; i++) {
162         if (tar_block_write(t, &data[i * T_BLOCKSIZE]) == -1)
163             throw IOException("Error writing tar block");
164     }
165
166     char block[T_BLOCKSIZE];
167     memset(block, 0, sizeof(block));
168     memcpy(block, &data[T_BLOCKSIZE * (blocks - 1)], T_BLOCKSIZE - padding);
169     if (tar_block_write(t, block) == -1)
170         throw IOException("Error writing final tar block");
171
172     size += blocks * T_BLOCKSIZE;
173 }
174
175 /* Estimate the size based on the size of the actual output file on disk.
176  * However, it might be the case that the filter program is buffering all its
177  * data, and might potentially not write a single byte until we have closed
178  * our end of the pipe.  If we don't do so until we see data written, we have
179  * a problem.  So, arbitrarily pick an upper bound on the compression ratio
180  * that the filter will achieve (128:1), and return a size estimate which is
181  * the larger of a) bytes actually seen written to disk, and b) input
182  * bytes/128. */
183 size_t Tarfile::size_estimate()
184 {
185     struct stat statbuf;
186
187     if (fstat(real_fd, &statbuf) == 0)
188         return max((int64_t)statbuf.st_size, (int64_t)(size / 128));
189
190     /* Couldn't stat the file on disk, so just return the actual number of
191      * bytes, before compression. */
192     return size;
193 }
194
195 static const size_t SEGMENT_SIZE = 4 * 1024 * 1024;
196
197 ObjectReference TarSegmentStore::write_object(const char *data, size_t len,
198                                               const std::string &group)
199 {
200     struct segment_info *segment;
201
202     // Find the segment into which the object should be written, looking up by
203     // group.  If no segment exists yet, create one.
204     if (segments.find(group) == segments.end()) {
205         segment = new segment_info;
206
207         segment->name = generate_uuid();
208
209         string filename = path + "/" + segment->name + ".tar";
210         filename += filter_extension;
211         segment->file = new Tarfile(filename, segment->name);
212
213         segment->count = 0;
214
215         segments[group] = segment;
216     } else {
217         segment = segments[group];
218     }
219
220     int id = segment->count;
221     char id_buf[64];
222     sprintf(id_buf, "%08x", id);
223
224     segment->file->write_object(id, data, len);
225     segment->count++;
226
227     ObjectReference ref(segment->name, id_buf);
228
229     // If this segment meets or exceeds the size target, close it so that
230     // future objects will go into a new segment.
231     if (segment->file->size_estimate() >= SEGMENT_SIZE)
232         close_segment(group);
233
234     return ref;
235 }
236
237 void TarSegmentStore::sync()
238 {
239     while (!segments.empty())
240         close_segment(segments.begin()->first);
241 }
242
243 void TarSegmentStore::close_segment(const string &group)
244 {
245     struct segment_info *segment = segments[group];
246
247     delete segment->file;
248     segments.erase(segments.find(group));
249     delete segment;
250 }
251
252 string TarSegmentStore::object_reference_to_segment(const string &object)
253 {
254     return object;
255 }
256
257 LbsObject::LbsObject()
258     : group(""), data(NULL), data_len(0), written(false)
259 {
260 }
261
262 LbsObject::~LbsObject()
263 {
264 }
265
266 void LbsObject::write(TarSegmentStore *store)
267 {
268     assert(data != NULL);
269     assert(!written);
270
271     ref = store->write_object(data, data_len, group);
272     written = true;
273 }
274
275 void LbsObject::checksum()
276 {
277     assert(written);
278
279     SHA1Checksum hash;
280     hash.process(data, data_len);
281     ref.set_checksum(hash.checksum_str());
282 }