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