Report compressed size of data written in a backup as well as uncompressed.
[cumulus.git] / store.cc
1 /* LBS: An LFS-inspired filesystem backup system
2  * Copyright (C) 2008  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  * represents segments as TAR files and objects as files within them. */
7
8 #include <assert.h>
9 #include <errno.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 <map>
22 #include <set>
23 #include <string>
24 #include <iostream>
25
26 #include "store.h"
27 #include "ref.h"
28
29 using std::max;
30 using std::list;
31 using std::map;
32 using std::pair;
33 using std::set;
34 using std::string;
35
36 /* Default filter program is bzip2 */
37 const char *filter_program = "bzip2 -c";
38 const char *filter_extension = ".bz2";
39
40 static void cloexec(int fd)
41 {
42     long flags = fcntl(fd, F_GETFD);
43
44     if (flags < 0)
45         return;
46
47     fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
48 }
49
50 Tarfile::Tarfile(RemoteFile *file, const string &segment)
51     : size(0),
52       segment_name(segment)
53 {
54     assert(sizeof(struct tar_header) == TAR_BLOCK_SIZE);
55
56     this->file = file;
57     real_fd = file->get_fd();
58     filter_fd = spawn_filter(real_fd, filter_program, &filter_pid);
59 }
60
61 Tarfile::~Tarfile()
62 {
63     char buf[TAR_BLOCK_SIZE];
64
65     /* Append the EOF marker: two blocks filled with nulls. */
66     memset(buf, 0, sizeof(buf));
67     tar_write(buf, TAR_BLOCK_SIZE);
68     tar_write(buf, TAR_BLOCK_SIZE);
69
70     if (close(filter_fd) != 0)
71         throw IOException("Error closing Tarfile");
72
73     /* ...and wait for filter process to finish. */
74     int status;
75     waitpid(filter_pid, &status, 0);
76
77     if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
78         throw IOException("Filter process error");
79     }
80
81     close(real_fd);
82 }
83
84 /* Launch a child process which can act as a filter (compress, encrypt, etc.)
85  * on the TAR output.  The file descriptor to which output should be written
86  * must be specified; the return value is the file descriptor which will be
87  * attached to the standard input of the filter program. */
88 int spawn_filter(int fd_out, const char *program, pid_t *filter_pid)
89 {
90     int fds[2];
91     pid_t pid;
92
93     /* Create a pipe for communicating with the filter process. */
94     if (pipe(fds) < 0) {
95         throw IOException("Unable to create pipe for filter");
96     }
97
98     /* Create a child process which can exec() the filter program. */
99     pid = fork();
100     if (pid < 0)
101         throw IOException("Unable to fork filter process");
102
103     if (pid > 0) {
104         /* Parent process */
105         close(fds[0]);
106         cloexec(fds[1]);
107         if (filter_pid != NULL)
108             *filter_pid = pid;
109     } else {
110         /* Child process.  Rearrange file descriptors.  stdin is fds[0], stdout
111          * is fd_out, stderr is unchanged. */
112         close(fds[1]);
113
114         if (dup2(fds[0], 0) < 0)
115             exit(1);
116         close(fds[0]);
117
118         if (dup2(fd_out, 1) < 0)
119             exit(1);
120         close(fd_out);
121
122         /* Exec the filter program. */
123         execlp("/bin/sh", "/bin/sh", "-c", program, NULL);
124
125         /* Should not reach here except for error cases. */
126         fprintf(stderr, "Could not exec filter: %m\n");
127         exit(1);
128     }
129
130     return fds[1];
131 }
132
133 void Tarfile::tar_write(const char *data, size_t len)
134 {
135     size += len;
136
137     while (len > 0) {
138         int res = write(filter_fd, data, len);
139
140         if (res < 0) {
141             if (errno == EINTR)
142                 continue;
143             fprintf(stderr, "Write error: %m\n");
144             throw IOException("Write error");
145         }
146
147         len -= res;
148         data += res;
149     }
150 }
151
152 void Tarfile::write_object(int id, const char *data, size_t len)
153 {
154     struct tar_header header;
155     memset(&header, 0, sizeof(header));
156
157     char buf[64];
158     sprintf(buf, "%08x", id);
159     string path = segment_name + "/" + buf;
160
161     assert(path.size() < 100);
162     memcpy(header.name, path.data(), path.size());
163     sprintf(header.mode, "%07o", 0600);
164     sprintf(header.uid, "%07o", 0);
165     sprintf(header.gid, "%07o", 0);
166     sprintf(header.size, "%011o", len);
167     sprintf(header.mtime, "%011o", (int)time(NULL));
168     header.typeflag = '0';
169     strcpy(header.magic, "ustar  ");
170     strcpy(header.uname, "root");
171     strcpy(header.gname, "root");
172
173     memset(header.chksum, ' ', sizeof(header.chksum));
174     int checksum = 0;
175     for (int i = 0; i < TAR_BLOCK_SIZE; i++) {
176         checksum += ((uint8_t *)&header)[i];
177     }
178     sprintf(header.chksum, "%06o", checksum);
179
180     tar_write((const char *)&header, TAR_BLOCK_SIZE);
181
182     if (len == 0)
183         return;
184
185     tar_write(data, len);
186
187     char padbuf[TAR_BLOCK_SIZE];
188     size_t blocks = (len + TAR_BLOCK_SIZE - 1) / TAR_BLOCK_SIZE;
189     size_t padding = blocks * TAR_BLOCK_SIZE - len;
190     memset(padbuf, 0, padding);
191     tar_write(padbuf, padding);
192 }
193
194 /* Estimate the size based on the size of the actual output file on disk.
195  * However, it might be the case that the filter program is buffering all its
196  * data, and might potentially not write a single byte until we have closed
197  * our end of the pipe.  If we don't do so until we see data written, we have
198  * a problem.  So, arbitrarily pick an upper bound on the compression ratio
199  * that the filter will achieve (128:1), and return a size estimate which is
200  * the larger of a) bytes actually seen written to disk, and b) input
201  * bytes/128. */
202 size_t Tarfile::size_estimate()
203 {
204     struct stat statbuf;
205
206     if (fstat(real_fd, &statbuf) == 0)
207         return max((int64_t)statbuf.st_size, (int64_t)(size / 128));
208
209     /* Couldn't stat the file on disk, so just return the actual number of
210      * bytes, before compression. */
211     return size;
212 }
213
214 static const size_t SEGMENT_SIZE = 4 * 1024 * 1024;
215
216 /* Backup size summary: segment type -> (uncompressed size, compressed size) */
217 static map<string, pair<int64_t, int64_t> > group_sizes;
218
219 ObjectReference TarSegmentStore::write_object(const char *data, size_t len,
220                                               const std::string &group)
221 {
222     struct segment_info *segment;
223
224     // Find the segment into which the object should be written, looking up by
225     // group.  If no segment exists yet, create one.
226     if (segments.find(group) == segments.end()) {
227         segment = new segment_info;
228
229         segment->name = generate_uuid();
230         segment->group = group;
231         segment->basename = segment->name + ".tar";
232         segment->basename += filter_extension;
233         segment->count = 0;
234         segment->size = 0;
235         segment->rf = remote->alloc_file(segment->basename, "segments");
236         segment->file = new Tarfile(segment->rf, segment->name);
237
238         segments[group] = segment;
239     } else {
240         segment = segments[group];
241     }
242
243     int id = segment->count;
244     char id_buf[64];
245     sprintf(id_buf, "%08x", id);
246
247     segment->file->write_object(id, data, len);
248     segment->count++;
249     segment->size += len;
250
251     group_sizes[group].first += len;
252
253     ObjectReference ref(segment->name, id_buf);
254
255     // If this segment meets or exceeds the size target, close it so that
256     // future objects will go into a new segment.
257     if (segment->file->size_estimate() >= SEGMENT_SIZE)
258         close_segment(group);
259
260     return ref;
261 }
262
263 void TarSegmentStore::sync()
264 {
265     while (!segments.empty())
266         close_segment(segments.begin()->first);
267 }
268
269 void TarSegmentStore::dump_stats()
270 {
271     printf("Data written:\n");
272     for (map<string, pair<int64_t, int64_t> >::iterator i = group_sizes.begin();
273          i != group_sizes.end(); ++i) {
274         printf("    %s: %lld (%lld compressed)\n", i->first.c_str(),
275                i->second.first, i->second.second);
276     }
277 }
278
279 void TarSegmentStore::close_segment(const string &group)
280 {
281     struct segment_info *segment = segments[group];
282
283     delete segment->file;
284
285     if (db != NULL) {
286         SHA1Checksum segment_checksum;
287         if (segment_checksum.process_file(segment->rf->get_local_path().c_str())) {
288             string checksum = segment_checksum.checksum_str();
289             db->SetSegmentChecksum(segment->name, segment->basename, checksum,
290                                    segment->size);
291         }
292
293         struct stat stat_buf;
294         if (stat(segment->rf->get_local_path().c_str(), &stat_buf) == 0) {
295             group_sizes[segment->group].second += stat_buf.st_size;
296         }
297     }
298
299     segment->rf->send();
300
301     segments.erase(segments.find(group));
302     delete segment;
303 }
304
305 string TarSegmentStore::object_reference_to_segment(const string &object)
306 {
307     return object;
308 }
309
310 LbsObject::LbsObject()
311     : group(""), data(NULL), data_len(0), written(false)
312 {
313 }
314
315 LbsObject::~LbsObject()
316 {
317 }
318
319 void LbsObject::write(TarSegmentStore *store)
320 {
321     assert(data != NULL);
322     assert(!written);
323
324     ref = store->write_object(data, data_len, group);
325     written = true;
326 }
327
328 void LbsObject::checksum()
329 {
330     assert(written);
331
332     SHA1Checksum hash;
333     hash.process(data, data_len);
334     ref.set_checksum(hash.checksum_str());
335 }