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