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