1 /* Cumulus: Efficient Filesystem Backup to the Cloud
2 * Copyright (C) 2008-2009 The Cumulus Developers
3 * See the AUTHORS file for a list of contributors.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 /* Backup data is stored in a collection of objects, which are grouped together
21 * into segments for storage purposes. This implementation of the object store
22 * represents segments as TAR files and objects as files within them. */
28 #include <sys/types.h>
30 #include <sys/resource.h>
56 /* Default filter program is bzip2 */
57 const char *filter_program = "bzip2 -c";
58 const char *filter_extension = ".bz2";
60 Tarfile::Tarfile(RemoteFile *file, const string &segment)
64 assert(sizeof(struct tar_header) == TAR_BLOCK_SIZE);
67 this->filter = FileFilter::New(file->get_fd(), filter_program);
72 char buf[TAR_BLOCK_SIZE];
74 /* Append the EOF marker: two blocks filled with nulls. */
75 memset(buf, 0, sizeof(buf));
76 tar_write(buf, TAR_BLOCK_SIZE);
77 tar_write(buf, TAR_BLOCK_SIZE);
79 if (close(filter->get_wrapped_fd()) != 0)
80 fatal("Error closing Tarfile");
82 /* ...and wait for filter process to finish. */
83 if (filter->wait() != 0) {
84 fatal("Filter process error");
88 FileFilter::FileFilter(int raw, int wrapped, pid_t pid)
89 : fd_raw(raw), fd_wrapped(wrapped), pid(pid) { }
91 FileFilter *FileFilter::New(int fd, const char *program)
93 if (program == NULL || strlen(program) == 0) {
94 return new FileFilter(fd, fd, -1);
98 int wrapped_fd = spawn_filter(fd, program, &pid);
100 return new FileFilter(fd, wrapped_fd, pid);
103 int FileFilter::wait()
105 // No filter program was launched implies no need to wait.
110 if (waitpid(pid, &status, 0) < 0) {
111 fprintf(stderr, "Error waiting for filter process: %m\n");
115 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
116 fprintf(stderr, "Filter process error: %d\n", WEXITSTATUS(status));
122 /* Launch a child process which can act as a filter (compress, encrypt, etc.)
123 * on the TAR output. The file descriptor to which output should be written
124 * must be specified; the return value is the file descriptor which will be
125 * attached to the standard input of the filter program. */
126 int FileFilter::spawn_filter(int fd_out, const char *program, pid_t *filter_pid)
131 /* Create a pipe for communicating with the filter process. */
133 fatal("Unable to create pipe for filter");
136 /* Create a child process which can exec() the filter program. */
139 fatal("Unable to fork filter process");
145 if (filter_pid != NULL)
148 /* Child process. Rearrange file descriptors. stdin is fds[0], stdout
149 * is fd_out, stderr is unchanged. */
152 if (dup2(fds[0], 0) < 0)
156 if (dup2(fd_out, 1) < 0)
160 /* Exec the filter program. */
161 execlp("/bin/sh", "/bin/sh", "-c", program, NULL);
163 /* Should not reach here except for error cases. */
164 fprintf(stderr, "Could not exec filter: %m\n");
171 void Tarfile::tar_write(const char *data, size_t len)
176 int res = write(filter->get_wrapped_fd(), data, len);
181 fprintf(stderr, "Write error: %m\n");
182 fatal("Write error");
190 void Tarfile::write_object(int id, const char *data, size_t len)
192 struct tar_header header;
193 memset(&header, 0, sizeof(header));
196 sprintf(buf, "%08x", id);
197 string path = segment_name + "/" + buf;
199 assert(path.size() < 100);
200 memcpy(header.name, path.data(), path.size());
201 sprintf(header.mode, "%07o", 0600);
202 sprintf(header.uid, "%07o", 0);
203 sprintf(header.gid, "%07o", 0);
204 sprintf(header.size, "%011o", (int)len);
205 sprintf(header.mtime, "%011o", (int)time(NULL));
206 header.typeflag = '0';
207 strcpy(header.magic, "ustar ");
208 strcpy(header.uname, "root");
209 strcpy(header.gname, "root");
211 memset(header.chksum, ' ', sizeof(header.chksum));
213 for (int i = 0; i < TAR_BLOCK_SIZE; i++) {
214 checksum += ((uint8_t *)&header)[i];
216 sprintf(header.chksum, "%06o", checksum);
218 tar_write((const char *)&header, TAR_BLOCK_SIZE);
223 tar_write(data, len);
225 char padbuf[TAR_BLOCK_SIZE];
226 size_t blocks = (len + TAR_BLOCK_SIZE - 1) / TAR_BLOCK_SIZE;
227 size_t padding = blocks * TAR_BLOCK_SIZE - len;
228 memset(padbuf, 0, padding);
229 tar_write(padbuf, padding);
232 /* Estimate the size based on the size of the actual output file on disk.
233 * However, it might be the case that the filter program is buffering all its
234 * data, and might potentially not write a single byte until we have closed
235 * our end of the pipe. If we don't do so until we see data written, we have
236 * a problem. So, arbitrarily pick an upper bound on the compression ratio
237 * that the filter will achieve (128:1), and return a size estimate which is
238 * the larger of a) bytes actually seen written to disk, and b) input
240 size_t Tarfile::size_estimate()
244 if (fstat(filter->get_raw_fd(), &statbuf) == 0)
245 return max((int64_t)statbuf.st_size, (int64_t)(size / 128));
247 /* Couldn't stat the file on disk, so just return the actual number of
248 * bytes, before compression. */
252 static const size_t SEGMENT_SIZE = 4 * 1024 * 1024;
254 /* Backup size summary: segment type -> (uncompressed size, compressed size) */
255 static map<string, pair<int64_t, int64_t> > group_sizes;
257 ObjectReference TarSegmentStore::write_object(const char *data, size_t len,
258 const std::string &group,
259 const std::string &checksum,
262 struct segment_info *segment;
264 // Find the segment into which the object should be written, looking up by
265 // group. If no segment exists yet, create one.
266 if (segments.find(group) == segments.end()) {
267 segment = new segment_info;
269 segment->name = generate_uuid();
270 segment->group = group;
271 segment->basename = segment->name + ".tar";
272 segment->basename += filter_extension;
274 segment->data_size = 0;
275 segment->rf = remote->alloc_file(segment->basename,
276 group == "metadata" ? "segments0"
278 segment->file = new Tarfile(segment->rf, segment->name);
280 segments[group] = segment;
282 segment = segments[group];
285 int id = segment->count;
287 sprintf(id_buf, "%08x", id);
289 segment->file->write_object(id, data, len);
291 segment->data_size += len;
293 group_sizes[group].first += len;
295 ObjectReference ref(segment->name, id_buf);
296 ref.set_range(0, len, true);
297 if (checksum.size() > 0)
298 ref.set_checksum(checksum);
300 db->StoreObject(ref, age);
302 // If this segment meets or exceeds the size target, close it so that
303 // future objects will go into a new segment.
304 if (segment->file->size_estimate() >= SEGMENT_SIZE)
305 close_segment(group);
310 void TarSegmentStore::sync()
312 while (!segments.empty())
313 close_segment(segments.begin()->first);
316 void TarSegmentStore::dump_stats()
318 printf("Data written:\n");
319 for (map<string, pair<int64_t, int64_t> >::iterator i = group_sizes.begin();
320 i != group_sizes.end(); ++i) {
321 printf(" %s: %lld (%lld compressed)\n", i->first.c_str(),
322 (long long)i->second.first, (long long)i->second.second);
326 void TarSegmentStore::close_segment(const string &group)
328 struct segment_info *segment = segments[group];
330 delete segment->file;
333 struct stat stat_buf;
335 if (stat(segment->rf->get_local_path().c_str(), &stat_buf) == 0) {
336 disk_size = stat_buf.st_size;
337 group_sizes[segment->group].second += disk_size;
341 = Hash::hash_file(segment->rf->get_local_path().c_str());
343 db->SetSegmentMetadata(segment->name, segment->rf->get_remote_path(),
344 checksum, group, segment->data_size, disk_size);
349 segments.erase(segments.find(group));
353 string TarSegmentStore::object_reference_to_segment(const string &object)
358 LbsObject::LbsObject()
359 : group(""), age(0.0), data(NULL), data_len(0), written(false)
363 LbsObject::~LbsObject()
367 void LbsObject::set_data(const char *d, size_t len, const char *checksum)
372 if (checksum != NULL) {
373 this->checksum = checksum;
375 Hash *hash = Hash::New();
376 hash->update(data, data_len);
377 this->checksum = hash->digest_str();
382 void LbsObject::write(TarSegmentStore *store)
384 assert(data != NULL);
387 ref = store->write_object(data, data_len, group, checksum, age);