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