Rework filter process code to make the interface simpler.
[cumulus.git] / store.cc
1 /* Cumulus: Efficient Filesystem Backup to the Cloud
2  * Copyright (C) 2008-2009 The Cumulus Developers
3  * See the AUTHORS file for a list of contributors.
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18  */
19
20 /* Backup data is stored in a collection of objects, which are grouped together
21  * into segments for storage purposes.  This implementation of the object store
22  * represents segments as TAR files and objects as files within them. */
23
24 #include <assert.h>
25 #include <errno.h>
26 #include <stdio.h>
27 #include <string.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <sys/resource.h>
31 #include <sys/wait.h>
32 #include <unistd.h>
33 #include <fcntl.h>
34 #include <time.h>
35
36 #include <algorithm>
37 #include <list>
38 #include <map>
39 #include <set>
40 #include <string>
41 #include <iostream>
42
43 #include "hash.h"
44 #include "localdb.h"
45 #include "store.h"
46 #include "ref.h"
47 #include "util.h"
48
49 using std::max;
50 using std::list;
51 using std::map;
52 using std::pair;
53 using std::set;
54 using std::string;
55
56 /* Default filter program is bzip2 */
57 const char *filter_program = "bzip2 -c";
58 const char *filter_extension = ".bz2";
59
60 Tarfile::Tarfile(RemoteFile *file, const string &segment)
61     : size(0),
62       segment_name(segment)
63 {
64     assert(sizeof(struct tar_header) == TAR_BLOCK_SIZE);
65
66     this->file = file;
67     this->filter = FileFilter::New(file->get_fd(), filter_program);
68 }
69
70 Tarfile::~Tarfile()
71 {
72     char buf[TAR_BLOCK_SIZE];
73
74     /* Append the EOF marker: two blocks filled with nulls. */
75     memset(buf, 0, sizeof(buf));
76     tar_write(buf, TAR_BLOCK_SIZE);
77     tar_write(buf, TAR_BLOCK_SIZE);
78
79     if (close(filter->get_wrapped_fd()) != 0)
80         fatal("Error closing Tarfile");
81
82     /* ...and wait for filter process to finish. */
83     if (filter->wait() != 0) {
84         fatal("Filter process error");
85     }
86 }
87
88 FileFilter::FileFilter(int raw, int wrapped, pid_t pid)
89     : fd_raw(raw), fd_wrapped(wrapped), pid(pid) { }
90
91 FileFilter *FileFilter::New(int fd, const char *program)
92 {
93     if (program == NULL || strlen(program) == 0) {
94         return new FileFilter(fd, fd, -1);
95     }
96
97     pid_t pid;
98     int wrapped_fd = spawn_filter(fd, program, &pid);
99     close(fd);
100     return new FileFilter(fd, wrapped_fd, pid);
101 }
102
103 int FileFilter::wait()
104 {
105     // No filter program was launched implies no need to wait.
106     if (pid == -1)
107         return 0;
108
109     int status;
110     if (waitpid(pid, &status, 0) < 0) {
111         fprintf(stderr, "Error waiting for filter process: %m\n");
112         return -1;
113     }
114
115     if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
116         fprintf(stderr, "Filter process error: %d\n", WEXITSTATUS(status));
117     }
118
119     return status;
120 }
121
122 /* Launch a child process which can act as a filter (compress, encrypt, etc.)
123  * on the TAR output.  The file descriptor to which output should be written
124  * must be specified; the return value is the file descriptor which will be
125  * attached to the standard input of the filter program. */
126 int FileFilter::spawn_filter(int fd_out, const char *program, pid_t *filter_pid)
127 {
128     int fds[2];
129     pid_t pid;
130
131     /* Create a pipe for communicating with the filter process. */
132     if (pipe(fds) < 0) {
133         fatal("Unable to create pipe for filter");
134     }
135
136     /* Create a child process which can exec() the filter program. */
137     pid = fork();
138     if (pid < 0)
139         fatal("Unable to fork filter process");
140
141     if (pid > 0) {
142         /* Parent process */
143         close(fds[0]);
144         cloexec(fds[1]);
145         if (filter_pid != NULL)
146             *filter_pid = pid;
147     } else {
148         /* Child process.  Rearrange file descriptors.  stdin is fds[0], stdout
149          * is fd_out, stderr is unchanged. */
150         close(fds[1]);
151
152         if (dup2(fds[0], 0) < 0)
153             exit(1);
154         close(fds[0]);
155
156         if (dup2(fd_out, 1) < 0)
157             exit(1);
158         close(fd_out);
159
160         /* Exec the filter program. */
161         execlp("/bin/sh", "/bin/sh", "-c", program, NULL);
162
163         /* Should not reach here except for error cases. */
164         fprintf(stderr, "Could not exec filter: %m\n");
165         exit(1);
166     }
167
168     return fds[1];
169 }
170
171 void Tarfile::tar_write(const char *data, size_t len)
172 {
173     size += len;
174
175     while (len > 0) {
176         int res = write(filter->get_wrapped_fd(), data, len);
177
178         if (res < 0) {
179             if (errno == EINTR)
180                 continue;
181             fprintf(stderr, "Write error: %m\n");
182             fatal("Write error");
183         }
184
185         len -= res;
186         data += res;
187     }
188 }
189
190 void Tarfile::write_object(int id, const char *data, size_t len)
191 {
192     struct tar_header header;
193     memset(&header, 0, sizeof(header));
194
195     char buf[64];
196     sprintf(buf, "%08x", id);
197     string path = segment_name + "/" + buf;
198
199     assert(path.size() < 100);
200     memcpy(header.name, path.data(), path.size());
201     sprintf(header.mode, "%07o", 0600);
202     sprintf(header.uid, "%07o", 0);
203     sprintf(header.gid, "%07o", 0);
204     sprintf(header.size, "%011o", (int)len);
205     sprintf(header.mtime, "%011o", (int)time(NULL));
206     header.typeflag = '0';
207     strcpy(header.magic, "ustar  ");
208     strcpy(header.uname, "root");
209     strcpy(header.gname, "root");
210
211     memset(header.chksum, ' ', sizeof(header.chksum));
212     int checksum = 0;
213     for (int i = 0; i < TAR_BLOCK_SIZE; i++) {
214         checksum += ((uint8_t *)&header)[i];
215     }
216     sprintf(header.chksum, "%06o", checksum);
217
218     tar_write((const char *)&header, TAR_BLOCK_SIZE);
219
220     if (len == 0)
221         return;
222
223     tar_write(data, len);
224
225     char padbuf[TAR_BLOCK_SIZE];
226     size_t blocks = (len + TAR_BLOCK_SIZE - 1) / TAR_BLOCK_SIZE;
227     size_t padding = blocks * TAR_BLOCK_SIZE - len;
228     memset(padbuf, 0, padding);
229     tar_write(padbuf, padding);
230 }
231
232 /* Estimate the size based on the size of the actual output file on disk.
233  * However, it might be the case that the filter program is buffering all its
234  * data, and might potentially not write a single byte until we have closed
235  * our end of the pipe.  If we don't do so until we see data written, we have
236  * a problem.  So, arbitrarily pick an upper bound on the compression ratio
237  * that the filter will achieve (128:1), and return a size estimate which is
238  * the larger of a) bytes actually seen written to disk, and b) input
239  * bytes/128. */
240 size_t Tarfile::size_estimate()
241 {
242     struct stat statbuf;
243
244     if (fstat(filter->get_raw_fd(), &statbuf) == 0)
245         return max((int64_t)statbuf.st_size, (int64_t)(size / 128));
246
247     /* Couldn't stat the file on disk, so just return the actual number of
248      * bytes, before compression. */
249     return size;
250 }
251
252 static const size_t SEGMENT_SIZE = 4 * 1024 * 1024;
253
254 /* Backup size summary: segment type -> (uncompressed size, compressed size) */
255 static map<string, pair<int64_t, int64_t> > group_sizes;
256
257 ObjectReference TarSegmentStore::write_object(const char *data, size_t len,
258                                               const std::string &group,
259                                               const std::string &checksum,
260                                               double age)
261 {
262     struct segment_info *segment;
263
264     // Find the segment into which the object should be written, looking up by
265     // group.  If no segment exists yet, create one.
266     if (segments.find(group) == segments.end()) {
267         segment = new segment_info;
268
269         segment->name = generate_uuid();
270         segment->group = group;
271         segment->basename = segment->name + ".tar";
272         segment->basename += filter_extension;
273         segment->count = 0;
274         segment->data_size = 0;
275         segment->rf = remote->alloc_file(segment->basename,
276                                          group == "metadata" ? "segments0"
277                                                              : "segments1");
278         segment->file = new Tarfile(segment->rf, segment->name);
279
280         segments[group] = segment;
281     } else {
282         segment = segments[group];
283     }
284
285     int id = segment->count;
286     char id_buf[64];
287     sprintf(id_buf, "%08x", id);
288
289     segment->file->write_object(id, data, len);
290     segment->count++;
291     segment->data_size += len;
292
293     group_sizes[group].first += len;
294
295     ObjectReference ref(segment->name, id_buf);
296     ref.set_range(0, len, true);
297     if (checksum.size() > 0)
298         ref.set_checksum(checksum);
299     if (db != NULL)
300         db->StoreObject(ref, age);
301
302     // If this segment meets or exceeds the size target, close it so that
303     // future objects will go into a new segment.
304     if (segment->file->size_estimate() >= SEGMENT_SIZE)
305         close_segment(group);
306
307     return ref;
308 }
309
310 void TarSegmentStore::sync()
311 {
312     while (!segments.empty())
313         close_segment(segments.begin()->first);
314 }
315
316 void TarSegmentStore::dump_stats()
317 {
318     printf("Data written:\n");
319     for (map<string, pair<int64_t, int64_t> >::iterator i = group_sizes.begin();
320          i != group_sizes.end(); ++i) {
321         printf("    %s: %lld (%lld compressed)\n", i->first.c_str(),
322                (long long)i->second.first, (long long)i->second.second);
323     }
324 }
325
326 void TarSegmentStore::close_segment(const string &group)
327 {
328     struct segment_info *segment = segments[group];
329
330     delete segment->file;
331
332     if (db != NULL) {
333         struct stat stat_buf;
334         int disk_size = 0;
335         if (stat(segment->rf->get_local_path().c_str(), &stat_buf) == 0) {
336             disk_size = stat_buf.st_size;
337             group_sizes[segment->group].second += disk_size;
338         }
339
340         string checksum
341             = Hash::hash_file(segment->rf->get_local_path().c_str());
342
343         db->SetSegmentMetadata(segment->name, segment->rf->get_remote_path(),
344                                checksum, group, segment->data_size, disk_size);
345     }
346
347     segment->rf->send();
348
349     segments.erase(segments.find(group));
350     delete segment;
351 }
352
353 string TarSegmentStore::object_reference_to_segment(const string &object)
354 {
355     return object;
356 }
357
358 LbsObject::LbsObject()
359     : group(""), age(0.0), data(NULL), data_len(0), written(false)
360 {
361 }
362
363 LbsObject::~LbsObject()
364 {
365 }
366
367 void LbsObject::set_data(const char *d, size_t len, const char *checksum)
368 {
369     data = d;
370     data_len = len;
371
372     if (checksum != NULL) {
373         this->checksum = checksum;
374     } else {
375         Hash *hash = Hash::New();
376         hash->update(data, data_len);
377         this->checksum = hash->digest_str();
378         delete hash;
379     }
380 }
381
382 void LbsObject::write(TarSegmentStore *store)
383 {
384     assert(data != NULL);
385     assert(!written);
386
387     ref = store->write_object(data, data_len, group, checksum, age);
388     written = true;
389 }