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